i would like to make a blackjack algorithm and i have almost finished the code. Although i get all the time the error NameError: name 'pointCoint' is not defined. I found out on the internet that i should change raw_input into input due to the python version 3.6 which i am using. Can somebody help me and have a look at my code whether i am missing something? dealerCount = pointCoint(dealer)
NameError: name 'pointCoint' is not defined
Thanks
You have created a function called pointCount(...), not pointCoint. Change pointCoint to pointCount.
Complete code:
from random import shuffle
def deck():
deck = []
for suit in ['H', 'D', 'S', 'C']:
for rank in ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']:
deck.append(suit+rank)
shuffle(deck)
return deck
def pointCount(myCards):
myCount = 0
aceCount = 0
for i in myCards:
if(i[1] == 'J' or i[1] == 'Q' or i[1] == 'K' or i[1] == 'T'):
myCount += 10
elif(i[1] != 'A'):
myCount += int(i[1])
else:
aceCount += 1
if(aceCount == 1 and myCount >= 10):
myCount += 11
elif(aceCount != 0):
myCount += 1
return myCount
def createPlayingHands(myDeck):
dealerHand = []
playerHand = []
dealerHand.append(myDeck.pop())
dealerHand.append(myDeck.pop())
playerHand.append(myDeck.pop())
playerHand.append(myDeck.pop())
while(pointCount(dealerHand) <= 16):
dealerHand.append(myDeck.pop())
return [dealerHand, playerHand]
game = ""
myDeck = deck()
hands = createPlayingHands(myDeck)
dealer = hands[0]
player = hands[1]
while(game != "exit"):
dealerCount = pointCount(dealer)
playerCount = pointCount(player)
print("Dealer has:")
print(dealer[0])
print("Player1, you have:")
print(player)
if(playerCount == 21):
print("Blackjack Player wins")
break
elif(playerCount > 21):
print("player Busts with " + str(playerCount) + "points")
break
elif(playerCount > 21):
print("Dealer Busts with " + str(dealerCount) + "points")
break
game = input("What would you like to do? M: Hit me, S: Stand? ")
if(game == 'H'):
player.append(myDeck.pop())
elif(playerCount > dealerCount):
print("Player wins with " + str(playerCount) + "points")
print("Dealer has: " + str(dealer) + "or" + str(dealerCount) + "points")
break
else:
print("Dealer wins")
print("Dealer has: " + str(dealer) + "or" + str(dealerCount) + "points")
break
Related
I have been trying to get below result out of this Program but for some reason it is not giving the required output.
Required Results:
Input1 : bbaasssrppoccbaaacbaba Output1 : ['bbaa','sssrppoccbaaa','cba','ba']
Input2: hjgAvjhjKLhbfvbZSF Output2 :['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f','vbZSF']
What i am getting
Output: ['bbaa', 'sssrppoccbaaa', 'cba'] & Output: ['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f'] from below code which is not getting last substring "ba" & "vbZSF".
s1 = 'bbaasssrppoccbaaacbaba'
# s1 = 'hjgAvjhjKLhbfvbZSF'
decSub = ''
listSub = []
i= 0
while i < len(s1):
current = s1[i]
previous = s1[i] if i == 0 else s1[i-1]
if ord(current) <= ord(previous):
decSub += current
else:
listSub.append(decSub)
decSub = ''
decSub += current
i +=1
print(listSub)
It would be great if somebody could suggest a fix or a better way to achieve this result.Thanks in advance
You just need to append the missing decSub in the list.
Updated Code:
s1 = 'bbaasssrppoccbaaacbaba'
# s1 = 'hjgAvjhjKLhbfvbZSF'
decSub = ''
listSub = []
i= 0
while i < len(s1):
current = s1[i]
previous = s1[i] if i == 0 else s1[i-1]
if ord(current) <= ord(previous):
decSub += current
else:
listSub.append(decSub)
decSub = ''
decSub += current
i += 1
listSub.append(decSub)
print(listSub)
Output:
# s1 = 'bbaasssrppoccbaaacbaba'
['bbaa', 'sssrppoccbaaa', 'cba', 'ba']
# s1 = 'hjgAvjhjKLhbfvbZSF'
['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f', 'vbZSF']
while loop is better choice for iterations without arbitrary boundaries - in your case for loop is probably a better choice.
Try the following instead:
from typing import List
def split_special(txt: str) -> List[str]:
if len(txt) == 0:
return []
res = [txt[0]]
prev = ord(txt[0])
for l in map(ord, txt[1:]):
if prev >= l:
res[-1] += chr(l)
else:
res.append(chr(l))
prev = l
return res
Outputs:
>>> print(Input1)
bbaasssrppoccbaaacbaba
>>> print(split_special(Input1))
['bbaa', 'sssrppoccbaaa', 'cba', 'ba']
>>> print(Input2)
hjgAvjhjKLhbfvbZSF
>>> print(split_special(Input2))
['h', 'jgA', 'vjh', 'jK', 'L', 'hb', 'f', 'vbZSF']
I am trying to create a Tic-Tac-Toe AI that will never lose. My code works sometimes but it does not work other times. Sometimes it will find the best move and print it out correctly but other times it will just fail. For example, once the AI takes the center if you press nine and take the top right corner then the AI will take a top left corner. Then if you take the bottom right corner the AI takes the middle left tile and then if you take the middle right tile then you will win. I wanted the AI to take the middle right to stop you from winning. I am a beginner programmer so please excuse me if the code is not written in the most optimal way. Why is that? Also can you please elaborate your explanation so I can understand what is wrong? Here is the code:
the_board = {'7': ' ', '8': ' ', '9': ' ',
'4': ' ', '5': ' ', '6': ' ',
'1': ' ', '2': ' ', '3': ' '}
def print_board(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
def check_for_win(current_state_of_the_board, player_sign):
if current_state_of_the_board["7"] == current_state_of_the_board["8"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["4"] == current_state_of_the_board["5"] == current_state_of_the_board["6"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["2"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["1"] == current_state_of_the_board["4"] == current_state_of_the_board["7"] == player_sign:
return "Victory"
elif current_state_of_the_board["2"] == current_state_of_the_board["5"] == current_state_of_the_board["8"] == player_sign:
return "Victory"
elif current_state_of_the_board["3"] == current_state_of_the_board["6"] == current_state_of_the_board["9"] == player_sign:
return "Victory"
elif current_state_of_the_board["7"] == current_state_of_the_board["5"] == current_state_of_the_board["3"] == player_sign:
return "Victory"
elif current_state_of_the_board["9"] == current_state_of_the_board["5"] == current_state_of_the_board["1"] == player_sign:
return "Victory"
else:
return "No Victory"
def get_copy_of_the_board(current_board, move, player_sign):
copy_of_the_board = current_board
if copy_of_the_board[str(move)] == " ":
copy_of_the_board[str(move)] = player_sign
return copy_of_the_board
else:
return copy_of_the_board
def check_for_computer_win():
for number in range(1, 10):
print( check_for_win(get_copy_of_the_board(the_board, number, "X"), "X"))
if check_for_win(get_copy_of_the_board(the_board, number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_win():
for number in range(1, 10):
print(check_for_win(get_copy_of_the_board(the_board, number, "O"), "O"))
if check_for_win(get_copy_of_the_board(the_board, number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_computer_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "X")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "X"), "X") == "Victory":
return str(number)
else:
return "Check next condition"
def check_for_player_forks():
for number in range(1, 10):
first_copy = get_copy_of_the_board(the_board, number, "O")
for second_number in range(1, 10):
if check_for_win(get_copy_of_the_board(first_copy, second_number, "O"), "O") == "Victory":
return str(number)
else:
return "Check next condition"
def get_computer_move():
if check_for_computer_win() != "Check next condition":
comp_move = check_for_computer_win()
return comp_move
else:
if check_for_player_win() != "Check next condition":
comp_move = check_for_player_win()
return comp_move
else:
if check_for_computer_forks() != "Check next condition":
comp_move = check_for_computer_forks()
return comp_move
else:
if check_for_player_forks() != "Check next condition":
comp_move = check_for_player_forks()
return comp_move
else:
for move in ["5"]:
if the_board[move] == " ":
comp_move = "5"
return comp_move
for move in ["7", "9", "1", "3"]:
if the_board[str(move)] == " ":
return move
for move in ["4", "8", "6", "2"]:
if the_board[str(move)] == " ":
return move
def game():
count = 0
turn = "computer"
while count < 9:
if turn == "computer":
print("The computer move is: ")
final_computer_move = get_computer_move()
if the_board["1"] == "O":
pass
else:
if final_computer_move == "1":
pass
else:
the_board["1"] = " "
the_board[final_computer_move] = "X"
print_board(the_board)
if check_for_win(the_board, "X") == "Victory":
print("The computer has won!")
exit()
else:
turn = "player"
count += 1
else:
player_move = input("Where would you like to move?")
the_board[player_move] = "O"
print_board(the_board)
if check_for_win(the_board, "O") == "Victory":
print("You have won!")
exit()
else:
turn = "computer"
count += 1
game()
Thanks in advance!!
I'm doing an assignment that requires me to simulate a dice roll game.
My problem is that when I roll the dice whithin my function and then later call it,
when I display try to display the die1, die2, die3 value from another function the values ar empty, unless I use global values, but I want to understand how the functions work and what i'm doing wrong rather than work around with global. :)
#importing the random library to make the random.randint function available
import random
#Making declrations for variable values
total_games = (0)
chip_balance = 100
total_chips = ()
games_won = 0
games_lost = 0
even_stevens = 0
games_draw = 0
play_game = 0
die1 = ()
die2 = ()
die3 = ()
#defining the dice roll function and logic
def die_roll(die1, die2, die3):
#Global Statements to make the die values available to the pre_display_dice function and the display_dice function.
die1 = random.randint (1, 12)
die2 = random.randint (1, 12)
die3 = random.randint (1, 12)
return die1, die2, die3
#defining the authorship details in this function
def display_details():
print('File : tobxz001_inbetween.py')
#defining the get_play_game_function to set the loop
def get_play_game():
global play_game
play_game = input('Would you like to play in-between [y|n]?')
while play_game != 'y' and play_game != 'n':
play_game = input("please enter either 'y' or 'n': ")
play_game = play_game.lower()
return play_game
#defining the Play_again function
def play_again():
global play_game
play_game = input('Would you like to play again squire?')
while play_game != 'y' and play_game != 'n':
play_game = input("please enter either 'y' or 'n' :")
play_game = play_game.lower()
#Defining the dice display here. Only two values are displayed before the bet is made
def pre_display_dice():
print('Dice rolled:')
print('+-------------------------------------+')
print('| Die 1 | | Die 2 |')
print('| ',die1,' | 0 | ',die2, ' |')
print('+-------------------------------------+')
#Defining the final dice roll display with all values of the roll displayed after the bet is made
def display_dice():
print('Dice rolled:')
print('+-------------------------------------+')
print('| Die 1 | | Die 2 |')
print('| ',die1,' | ',die3, ' | ',die2, ' |')
print('+-------------------------------------+')
#Defining the game summary here. Wins, Loses, and draws are called from this function at the end of the game
def game_summary():
print('\n')
print('Game Summary')
print('============')
print('\n')
print('You played',total_games,'Games:')
print('|--> Games Won:', games_won)
print('|--> Games Lost', games_lost)
print('|--> Even-Stevens:', even_stevens)
display_details()
get_play_game()
while play_game == 'y':
die_roll(die1, die2, die3)
temp = int()
winner = ()
loser = (0)
bet_result = ()
#Code for swapping the dice around to always display the lower value on the left
if (die1 >= die2):
temp = die1
die1 = die2
die2 = temp
else:
die1 = die1
die2 = die2
if die1 == die2:
total_games = total_games + 1
print('\n')
print('You hit the post')
print("Even-Stevens! Let\'s play again!")
print('\n')
get_play_game
pre_display_dice()
print('\n')
print("Number of Chips : ", chip_balance)
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha():
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
while bet > chip_balance:
print('Sorry, you may only bet what you have ')
bet = input("Place your bet: ")
while bet == '':
bet = input("Can't be an empty bet please try again ")
while bet.isalpha() or bet == '':
bet = input("Must be a numerical value entered \n \n Place You're bet:")
bet = int(bet)
chip_balance = chip_balance - bet
if die1 < die3 & die3 < die2:
winner = (bet * 2) + chip_balance
chip_balance = winner
else:
chip_balance
#Code to compare if the results are even or not STAGE 3, if they aren't Die3 will be rolled
if die1 == die2:
print('\n')
display_dice()
print('You hit the post')
print("Even-Stevens! Let\'s play again!")
print('\n')
even_stevens = even_stevens + 1
total_games = total_games + 1
else:
print('\n')
display_dice()
print('\n')
#Winning and Losing logic
#Winning conditions
if die1 < die3 & die3 < die2:
print("***You Win!***")
print("You now have", chip_balance, "Chips")
print('\n')
games_won = games_won + 1
total_games = total_games + 1
#Evaluate to see if any of the dice' match is done here
elif die1 == die3 or die3 == die2:
print('\n')
print("***You hit the post - You Lose! ***")
print("You now have", chip_balance, "chips left")
print('\n')
games_lost = games_lost + 1
total_games = total_games + 1
#Losing Logic
else:
print("*** Sorry - You Lose! ***")
print('\n')
print("You now have", chip_balance, "chips left!")
games_lost = games_lost + 1
total_games = total_games + 1
#Chip balance check, if it's zero, game is over, otherwise keep playing
if chip_balance == 0:
print('\n')
print('You\'re all out of chips! \n ***GAME OVER***')
play_game = 'n'
else:
play_again()
if play_game == 'n':
game_summary()
if play_game == 'n':
print('\n')
print('No worries... another time perhaps...:)')
I am making a quiz which can work with different difficulties and it works fine. The only thing is that its like my code ignores my if statement at the bottom. even when the variable 'w' = 9, which is when i have answered 9 questions, it still doesn't print the statement it just continues looping.
import csv
w = 0
score = 0
global q
with open("Computing.txt", "r") as file:
reader = csv.reader(file)
for row in reader:
dif_c = str(dif) + " "
if dif_c + str(q) + ")" in row[0]:
print (row[0].split(dif_c)[1])
print (row[1])
if dif == 1:
print (row[2])
input10 = input("Answer 'a' or 'b': ")
elif dif == 2:
print(row[2] + "\n" + row[3])
input10 = input("Answer 'a','b' or 'c': ")
elif dif == 3:
print(row[2] + "\n" + row[3] + "\n" + row[4])
input10 = input("Answer 'a','b','c' or 'd': ")
if input10 == row[dif + 2]:
print("Correct")
score = score + 1
w = w + 1
elif input10 != row[dif + 2]:
print("Incorrect")
w = w + 1
if w == 9:
print("Game over")
print("You got", r, "right out of 10")
while True:
quiz()
this is all the quiz function and i defined w and score as 0 within the function which i know wouldnt work but i have no clue how to fix it
Your 'if' condition to check 'w == 9' should be inside the 'for' loop and you need to break out of the 'for' loop based on that condition. Otherwise it will continue to loop.
Currently your 'if' check is outside the 'for' loop.
So it should be changed to something like this:
import csv
w = 0
score = 0
global q
with open("Computing.txt", "r") as file:
reader = csv.reader(file)
for row in reader:
dif_c = str(dif) + " "
if dif_c + str(q) + ")" in row[0]:
print (row[0].split(dif_c)[1])
print (row[1])
if dif == 1:
print (row[2])
input10 = input("Answer 'a' or 'b': ")
elif dif == 2:
print(row[2] + "\n" + row[3])
input10 = input("Answer 'a','b' or 'c': ")
elif dif == 3:
print(row[2] + "\n" + row[3] + "\n" + row[4])
input10 = input("Answer 'a','b','c' or 'd': ")
if input10 == row[dif + 2]:
print("Correct")
score = score + 1
w = w + 1
elif input10 != row[dif + 2]:
print("Incorrect")
w = w + 1
if w == 9:
print("Game over")
print("You got", r, "right out of 10")
break
I'm a beginner in coding and I'm making a simple rpg. I'm currently making a floor with only 4 rooms. I want the game to loop infinitely. I also want the game to prompt the player to enter a valid command when they enter an invalid command, but the while loop repeats infinitely. Can someone give me a fix that a beginner can understand, and maybe some pointers? The while loop is
while foo(move) == False:.
def foo(m):
"""
"""
if m.lower == 'l' or m.lower == 'r' or m.lower == 'help' or m.lower == 'pokemon':
return True
else:
return False
print() #Put storyline here
print("You may input 'help' to display the commands.")
print()
gamePlay = True
floor4 = ['floor 4 room 4', 'floor 4 room 3', 'floor 4 room 2', 'floor 4 room 1']
floor4feature = ['nothing here', 'nothing here', 'stairs going down', 'a Squirtle']
currentRoom = 0
pokemonGot = ['Bulbasaur']
while gamePlay == True:
print("You are on " + floor4[currentRoom] + ". You find " + floor4feature[currentRoom] + ".")
move = input("What would you like to do? ")
while foo(move) == False:
move = input("There's a time and place for everything, but not now! What would you like to do? ")
if move.lower() == 'l':
if currentRoom > 0:
currentRoom = currentRoom - 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'r':
if currentRoom < len(floor4) - 1:
currentRoom = currentRoom + 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'help':
print("Input 'r' to move right. Input 'l' to move left. Input 'pokemon' to see what Pokemon are on your team. Input 'help' to see the commands again.")
elif move.lower() == 'pokemon':
print("The Pokemon on your team are: " + str(pokemonGot) + ".")
print()
In foo you are comparing a function definition, m.lower, to a character. Try m.lower () to call the function.