import random
import string
import time

playgame = True

while playgame == True:
	deck1 = {}
	suits = ['♠', '♥', '♦', '♣']
	facevalue = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
	points = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

	deck2 = []

	count = 0
	count2 = 0
	count3 = 0
	players = {}
	currplayer = 0
	scores = []
	value = [0]
	aces = 0
	final = []

	while count < len(facevalue):
		while count2 < 4:
			deck2.append (str(facevalue[count]) + str(suits[count2]))
			deck1[deck2[count3]] = points[count]
			count2 += 1
			count3 +=1

		count += 1
		count2 = 0

	def howmanyplayers():
		correct = False
		n = 0
		while correct == False: 
			try:
				num_players = int(input('How many human players? (#)') )
			except:
				num_players = 1
			if (num_players > 0):
				correct = True
				print('Now preparing game for', num_players, 'human player(s) and the CPU')
				print('\n')
				while n <= num_players:
					players['Player'+str(n)] = []
					players['Player'+str(n)].append(value)
					n += 1
				np = (num_players)
		#print(players)
		return num_players

	def newgame(deck2):
		for num in range(1,random.randint(1,50),1):
			random.shuffle(deck2)
		return deck2

	def dealstart():
		card = 0
		for i in range(0,2):
			for num in range(0, (np+1)):
				players['Player'+str(num)].append (str(deck2[card]))
				card += 1
				#print(players)
		return card

	def scorehand():
		tempscore = 0
		tempcard = []
		blackjack = False
		aceinplay = False
		aces = 0
		for item in players['Player'+str(currplayer)][1:]:
			tempcard += [deck1[(item)]]
			#print(tempcard)
			if 11 in tempcard:
				aceinplay = True
				aces += 1
			
			tempscore = sum(tempcard)
			
			if tempscore == 21 and len(players['Player'+str(currplayer)][1:]) == 2:
				blackjack = True

			if aces > 0:
				for num in range (0,aces):

					if tempscore > 21 and aces > 0 and aceinplay == True:
						tempscore -= 10
						aces -= 1
						if aces <= 0:
							aceinplay = False

		return [tempscore, blackjack, aceinplay, aces]

	def playhand(card, dealer, np, dbj):
		finalscores = []
		#print (scorehand())
		playerdone = False
		if dbj == True:
			playerdone = True
			print('The Dealer is showing:', end='\t')
			print(players['Player'+str(np)][1:])

		if dbj == False:
			print('The Dealer is showing:', end='\t')
			print("['??']", players['Player'+str(np)][2:])

		while playerdone == False and dealer == False:
			standhit = ''
			#print(scorehand())
			print('Player'+str(currplayer+1)+':', end='\t')
			print('You have:', end="\t")
			print(players['Player'+str(currplayer)][1:], end='\t')
			print('(', scorehand()[0], 'points)')
			#print(wincheck)
			
			if scorehand()[0] == 21 and len(players['Player'+str(currplayer)][1:]) == 2:
				print('BLACKJACK!')
				playerdone = True
			elif scorehand()[0] == 21 and len(players['Player'+str(currplayer)][1:]) != 2:
				print('Twenty One!')
				print('\n')
				playerdone = True
				pass

			if playerdone != True:
				standhit = input('Do you want to (S)tand or (H)it?').lower()
				
				if standhit == '':
					standhit = 's'

				elif standhit[0] == 's':
					playerdone = True
					print('Outstanding.')
					print('Keep an eye on your', scorehand()[0],'and see how it holds up...')
					time.sleep(1)
					
				elif standhit[0] == 'h':
					players['Player'+str(currplayer+1)].append (str(deck2[card]))
					card += 1
					if card >= 52:
						newgame()
						card = 0
						print('---shuffling---')
					print('You drew a:', players['Player'+str(currplayer)][-1])
					print('Your hand is now:', players['Player'+str(currplayer)][1:])

				else:
					standhit[0] != 's' and standhit[0] != 'h' 
					print('Standing.')
					playerdone = True
					print('Outstanding.')
					print('Keep an eye on your', scorehand()[0],'and see how it holds up...')

				wincheck = scorehand()
				#print(wincheck[0])
				if wincheck[0] > 21:
					print("Your total is now:", wincheck[0])
					print("Sorry, you've busted. Better luck next time.")
					playerdone = True
				#elif wincheck[0] > 21 and wincheck[2] == True and wincheck[3] > 0:
					#scorehand[0] -= 10
					#wincheck[3] += -1
				#print('wincheck:', wincheck)
				#print('scorehand:', scorehand())
				print('\n')


		while playerdone == False and dealer == True:
			print('The dealer has a hand of:', players['Player'+str(currplayer)][1:])
			if scorehand()[0] == 21 and len(players['Player'+str(currplayer)][1:]) == 2:
				print('BLACKJACK!')
				playerdone = True
			elif scorehand()[0] == 21 and len(players['Player'+str(currplayer)][1:]) != 2:
				print('Twenty One!')
				playerdone = True
			
			if playerdone != True:
				if scorehand()[0] > 16 and scorehand()[0] <=21:
					print('The House stays with', players['Player'+str(currplayer)][1:])
					time.sleep(1)
					print('House score:',scorehand()[0])
					playerdone = True
				elif scorehand()[0] < 16:
					players['Player'+str(currplayer)].append (str(deck2[card]))
					card += 1
					if card >= 52:
						newgame()
						print('---shuffling---')
					print('The House drew a:', players['Player'+str(currplayer)][-1])
					#print('...and now has a hand of:', players['Player'+str(currplayer)][1:])
					time.sleep(1)
				else:
					print('The House BUSTED...')
					playerdone = True
					dealer = False
					time.sleep(1)
		final.append (scorehand()[0])
		return card, finalscores

	def thedealer():
		print('Time for the dealer:', end='\t')
		print('(AKA: Player'+str(currplayer+1)+')')
		#print('The cards:')
		#print(players['Player'+str(currplayer)][1:])
		print('And is showing', scorehand()[0], 'points')
		dealer = True
		playhand(card, dealer, np, dbj)

	def gameover(np,fins):
		print('\n')
		endscore=[]

		for num in range(0,np+1):
			currplayer = num
			if final[num] > 21 and num != np:
				print('Player'+str(num),'Busted...')
				final[num] = 0
			elif 1 < final[num] < 21:
				if num == np:
					pass #print('The Dealer has a final score of:',final[num])
				else:
					#print('Player'+str(num+1), 'has a final score of:',final[num])
					pass
			elif final[num] == 21:
				#print('Player'+str(num+1), 'got 21!')
				pass
			endscore.append (final[num])
			#print (max(final))

		# print('\n')
		# for num in range(0,np+1):
		# 	if 
		#print(fins)
		#print(endscore)
		print('\n')
		print('And the results are:')
		for num1 in range(0, np):
			if endscore[np] == 0 and endscore[num1] != 'Busted':
				print('Player'+str(num1+1), 'wins with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
			elif endscore[num1] != 0 and endscore[num1] > endscore[np]:
				print('Player'+str(num1+1), 'wins with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
			elif endscore[num1] != 0 and endscore[num1] == endscore[np]: # and endscore[num1] == max(endscore):
				print('Player'+str(num1+1), 'ties (push) with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
			else:
				print('Player'+str(num1+1), 'loses with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
		
		if endscore[np] != 0 and endscore[-1] == max(endscore):
			print('The Dealer wins with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')

		# if endscore[0] != 0 and endscore[0] >= endscore[1:]
		# 	print('The Dealer', 'wins with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
		# #elif endscore[0] != 0 and endscore[num1] > endscore[np]:
		# #	print('The Dealer', 'wins with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
		# elif endscore[0] != 0 and endscore[0] == max(endscore[1:]): # and endscore[num1] == max(endscore):
		# 	print('The Dealer ties (push) with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')
		# else:
		# 	print('The Dealer loses with a hand of:', players['Player'+str(num1)][1:], '('+str(endscore[num1])+')')

		return endscore


		

			



	np = howmanyplayers()
	deck2 = newgame(deck2)
	card = dealstart()
	card += 1

	#print(card)
	#print("Deck1", deck1)
	#print("Deck2", deck2)
	wincheck = scorehand()
	#print(wincheck)
	currplayer=0

	dealerbjack = scorehand()[1]
	if dealerbjack == True:
		dbj = True
	else:
		dbj = False

	for num in range(0,np):
		dealer = False
		if dbj == True:
			playerdone = True
		currcard, fins = playhand(card, dealer, np, dbj)
		currplayer += 1
		playerdone = False

	dealer = True



	thedealer()
	gameover(np, fins)

	try:
		doover = input('Shall we play again? (y/n)').lower()
		if doover[0]== 'y':
			playgame = True
		else:
			playgame = False
	except:
		playgame = False


