My boolean flag isn't triggering when it's supposed to - python-3.x

At the play_again input, whenever I input "n" to end the loop, python seems to ignore it and prints :
Your cards: [x, x], current score: xx
Computers first card: x.
Would you like to draw another card? Press 'y' to draw or 'n' to stand.
Even though I have set end_game back to True.
What gives?
import random
from art import logo
from replit import clear
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
def calculate_score(card_list):
if len(card_list) == 2 and sum(card_list) == 21:
return 0
if 11 in card_list and sum(card_list) > 21:
card_list.remove(11)
card_list.append(1)
return sum(card_list)
def compare(user, computer):
if user == computer:
return "I'ts a draw!"
elif user == 0:
return "You win with a BlackJack!"
elif computer == 0:
return "Computer wins with a BlackJack!"
elif computer > 21:
return "You win! Computer busts."
elif user > 21:
return "Computer wins, you bust!"
elif user > computer:
return "You win!"
else:
return "You lose!"
def main_loop():
print(logo)
user_cards = []
computer_cards = []
game_end = False
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not game_end:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f"Your cards: {user_cards}, current score: {user_score}")
print(f"Computers first card: {computer_cards[0]}.")
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print(f"Your final hand: {user_cards}, Your final score{user_score}.")
print(f"Computers final hand: {computer_cards}, Computers final score {computer_score}." )
print(compare(user_score, computer_score))
while input("Would you like to play a game of BlackJack?: ") == 'y':
clear()
main_loop()
else:
print('Goodbye!')
quit()

Please check your variable name game_end in "while not game_end:" loop,
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw
or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
I think it's "game_end" in else: , you put end_game , please change it, other function working fine.

Related

Why isn't my while loop ending when it fulfills one of the conditions?

I'm in the progress of building a basic blackjack game and I've made a while loop that should terminate once either player hand or house hand is greater than 21 but it just keeps looping?
the crazy thing is that I actually did make it work once but I accidentally broke it again while testing another function that I tried to get working (turning the 11 into a 1 if greater than 21) and I can't seem to get it working again?
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
player_hand = []
house_hand = []
def player_opening_hand():
for hand in range (0,2):
player_hand.append(random.choice(cards))
def house_opening_hand():
for hand in range(0,2):
house_hand.append(random.choice(cards))
def total_score(hand):
return sum(hand)
def new_draw(draw):
draw.append(random.choice(cards))
# if total_score(draw) > 21 and 11 in draw:
# draw[11] = 1
def current_score():
print(f'Your cards: {player_hand}, total score: {total_score(player_hand)}')
print(f"computer's first card: {house_hand[0]}")
def final_score():
print(f'Your cards: {player_hand}, total score: {total_score(player_hand)}')
print(f"computer's cards: {house_hand}, house total score: {total_score(house_hand)}")
#Intro to the player
begin = input('welcome to pyjack, would you like to start a new game? enter "y" or "n": ')
if begin == 'y':
# first two cards for both players are dealt,
player_opening_hand()
house_opening_hand()
current_score()
if total_score(player_hand) == 21:
print('you won!')
else:
while total_score(player_hand) and total_score(house_hand) < 21:
player_choice = input('Type "y" to get another draw or type "n" to pass: ')
if player_choice == 'y':
new_draw(player_hand)
current_score()
if total_score(player_hand) > 21:
final_score()
print('you went over 21, you lose!')
elif total_score(player_hand) > total_score(house_hand):
final_score()
print('your hand is bigger than the house! you win!')
elif total_score(player_hand) == 21 and total_score(house_hand) < 21:
final_score()
print('Blackjack! you win!')
else:
final_score()
print('you lose!')
You always have to mention the both conditions using AND or OR operators.
Here condition is to be:
while total_score(player_hand) < 21 and total_score(house_hand) < 21:
I hope this will work for you.
while total_score(player_hand) and total_score(house_hand) < 21:
does not do what you think it does. The correct code is
while total_score(player_hand) < 21 and total_score(house_hand) < 21:

Why the "stop" input doesnt stop the hitorstop() and run the code for the condition elif todo == "stop"

import random
class Player:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
run = True
def __init__(self):
self.name = input("Enter your name : ")
self.Bet = inputs.bet(self)
self.Aceval = inputs.Aval(self)
class Dealer:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
class inputs:
def bet(self):
"""
takes in the bet from the user and stores it in the player class
:return: output
"""
self.bet = input("Enter the amount for your bet : ")
output = self.bet
if self.bet.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.bet(self)
else:
return int(output)
def Aval(self):
"""
Takes the value for ace and stores it in the player class
:return: output
"""
self.aval = input("Enter the value for ACE (1 or 10) : ")
output = self.aval
if self.aval.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.Aval(self)
elif self.aval.isnumeric() == True:
if self.aval in ["1", "10"]:
return int(output)
else:
print("I understand you suffer braincell deficiency but I need you to fire up those 2 braincells you have and enter the proper number")
return inputs.Aval(self)
def valcalc(card):
"""
takes the card for player.deck and returns the value of that card
:return: card value
"""
if card[0] in ("K", "Q", "J"):
return 10
elif card[0] == "A":
return p.Aceval
else:
if len(card) > 2:
return int(card[0:2])
else:
return int(card[0])
def hitorstop(todo):
if todo.lower() == ("hit" or "stop"):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
if todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
p = Player()
d = Dealer()
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
print("Dealer's card is :" + str(dcard) + "+")
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
hitorstop(input("Do you want to hit or stop : "))
Why does the code below todo == "stop" run when i put in stop as input , it just keeps looping asking for the input again and again if i put "stop" for hitorstop() function
.................................................................................................................................................................................................................................................................................................................................................
You need to replace the line todo.lower() == ("hit" or "stop"): with todo.lower() in ("hit", "stop"): to make it work.
However, this entire condition is redundant in the first place and you can remove it.
You don't need it since you compare the input with "hit" and "stop" later, so it is useless to compare twice.
Here is the replace:
def hitorstop(todo):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
elif todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
else:
hitorstop(input("\n\nDo you want to hit or stop : "))

python program error while combine two program

i have wrote two program, one is tic tac toe,one is guest number, and it is fine when run separately and when i combine them( my aim is when to people win in the guest number game, the people can pick a box in tic tac toe)
It work normally and when it start to select to second box, the error occur
it is show asz follow
Traceback (most recent call last):
File "C:\Users\User\Desktop\try3.py", line 207, in
winner = single_game(options[choice-1])
File "C:\Users\User\Desktop\try3.py", line 125, in single_game
player_pos[cur_player].append(move)
KeyError: <main.Player object at 0x000001D6C01CC730>
can anyone see what wrong with my program. Thanks
import random
from random import randint
class Player():
def __init__(self, player_name):
self.name = player_name
self.score = 0
self.guess = 0
def enterGuess(self,rand, play):
if play == True:
self.guess = int(input(self.name+ " enter a guess 1-100:"))
if self.guess == rand:
print ("Correct Guess")
play = False
self.score = self.score + 1
elif self.guess < rand:
print ("Too low")
else:
print ("Too high")
return play
def playGame():
player1.score = 0
player1.guess = 0
player2.score = 0
player2.guess = 0
randNum = randint(1,100)
play = True
print ("\nNew game")
while play:
play=player1.enterGuess(randNum, play)
play=player2.enterGuess(randNum, play)
def coinToss():
flip = random.randint(0, 1)
if (flip == 0):
return("Head")
else:
return("Tail")
print(coinToss)
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[4], values[5]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[6], values[7], values[8]))
print("\t | |")
print("\n")
def print_scoreboard(score_board):
print("\t--------------------------------")
print("\t SCOREBOARD ")
print("\t--------------------------------")
players = list(score_board.keys())
print("\t ", players[0], "\t ", score_board[players[0]])
print("\t ", players[1], "\t ", score_board[players[1]])
print("\t--------------------------------\n")
def check_win(player_pos, cur_player):
soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
for x in soln:
if all(y in player_pos[cur_player] for y in x):
return True
return False
def check_draw(player_pos):
if len(player_pos['X']) + len(player_pos['O']) == 9:
return True
return False
def single_game(cur_player):
values = [' ' for x in range(9)]
player_pos = {'X':[], 'O':[]}
while True:
print_tic_tac_toe(values)
try:
print("The player ", cur_player, " turn. Which box? : ", end="")
move = int(input())
except ValueError:
print("Wrong Input!!! Try Again")
continue
if move < 1 or move > 9:
print("Wrong Input!!! Try Again")
continue
if values[move-1] != ' ':
print("Place already filled. Try again!!")
continue
values[move-1] = cur_player
player_pos[cur_player].append(move)
if check_win(player_pos, cur_player):
print_tic_tac_toe(values)
print( cur_player, " has won the game!!")
print("\n")
return cur_player
if check_draw(player_pos):
print_tic_tac_toe(values)
print("Game Drawn")
print("\n")
return 'D'
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
if __name__ == "__main__":
print ("Player 1")
player1=Player(input("Enter name:"))
print ("Player 2")
player2=Player(input("Enter name:"))
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
player_choice = {'X' : "", 'O' : ""}
options = ['X', 'O']
score_board = {player1: 0, player2: 0}
print_scoreboard(score_board)
while True:
print("Turn to choose for", cur_player)
print("Enter 1 for X")
print("Enter 2 for O")
print("Enter 3 to Quit")
try:
choice = int(input())
except ValueError:
print("Wrong Input!!! Try Again\n")
continue
if choice == 1:
player_choice['X'] = cur_player
if cur_player == player1:
player_choice['O'] = player2
else:
player_choice['O'] = player1
elif choice == 2:
player_choice['O'] = cur_player
if cur_player == player1:
player_choice['X'] = player2
else:
player_choice['X'] = player1
elif choice == 3:
print("Final Scores")
print_scoreboard(score_board)
break
else:
print("Wrong Choice!!!! Try Again\n")
winner = single_game(options[choice-1])
if winner != 'D' :
player_won = player_choice[winner]
score_board[player_won] = score_board[player_won] + 1
print_scoreboard(score_board)

How to delete lines of output, python?

So here is my code:
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
My output is:
Click 1 for attack
Click 2 for shield
:1
Krotos: 75
Sephiroth: 75
Click 1 for attack
Click 2 for shield
:
How can I get rid of the first three lines so it only shows the newest information? Any new ideas would be useful. I have tried using google but I can't find anything.
Try this below :
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def clear():
import os
os.system("clear") # Linux
os.system("cls") # Windows
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
clear() # -------------> Call clear function after your input
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
You can clear the console after every attack:
import os
os.system("cls") #windows
os.system("clear") #linux

I am writing my first assignment and i cant seem figure out why i am unable to enter my first function

First of im sorry about bombarding my post with a bunch of code, but im putting it here hoping that it will help you guys understanding my question better.
I am trying to figure out why my IDE is unwilling to execute the first function of my code. Obviously im doing something wrong, but im to unexperienced to see it for myself. All help would be greatly appriciated.
If you have any further comments or tips on my code feel free contribute.
import random
print("Press '1' for New Single Player Game - Play against computer component: ")
print("Press '2' for New Two Player Game - Play against another person, using same computer: ")
print("Press '3' for Bonus Feature - A bonus feature of choice: ")
print("Press '4' for User Guide - Display full instructions for using your application: ")
print("Press '5' for Quit - Exit the program: ")
def choose_program():
what_program = int(input("What program would you like to initiate?? Type in the 'number-value' from the chart above: "))
if what_program == 1 or 2 or 3 or 4 or 5:
program_choice = int(input("Make a choice: "))
if (program_choice > 5) or (program_choice < 1):
print("Please choose a number between 1 through 5 ")
choose_program()
elif program_choice == 1:
print("You picked a New Single Player Game - Play against computer component")
def single_player():
start_game = input("Would you like to play 'ROCK PAPER SCISSORS LIZARD SPOCK'?? Type 'y' for YES, and 'n' for NO): ").lower()
if start_game == "y":
print("Press '1' for Rock: ")
print("Press '2' for Paper: ")
print("Press '3' for Scissors: ")
print("Press '4' for Lizard: ")
print("Press '5' for Spock: ")
elif start_game != "n":
print("Please type either 'y' for YES or 'n' for NO: ")
single_player()
def player_one():
human_one = int(input("Make a choice: "))
if (human_one > 5) or (human_one < 1):
print("Please choose a number between 1 through 5 ")
player_one()
elif human_one == 1:
print("You picked ROCK!")
elif human_one == 2:
print("You picked PAPER!")
elif human_one == 3:
print("You picked SCISSORS!")
elif human_one == 4:
print("You picked LIZARD!")
elif human_one == 5:
print("You picked SPOCK!")
return human_one
def computers_brain():
cpu_one = random.randint(1, 5)
if cpu_one == 1:
print("Computers choice iiiiiis ROCK!")
elif cpu_one == 2:
print("Computers choice iiiiiis PAPER!")
elif cpu_one == 3:
print("Computers choice iiiiiis SCISSORS!")
elif cpu_one == 4:
print("Computers choice iiiiiis LIZARD!")
elif cpu_one == 5:
print("Computers choice iiiiiis SPOCK!")
return cpu_one
def who_won(human, cpu, human_wins, cpu_wins, draw):
if human == 1 and cpu == 3 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 2 and cpu == 1 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 3 and cpu == 2 or cpu == 4:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 4 and cpu == 2 or cpu == 5:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == 5 and cpu == 1 or cpu == 3:
print("Human is invincible!!")
human_wins = human_wins.append(1)
elif human == cpu:
print("Human & computer think alike, such technology")
draw = draw.append(1)
else:
print("Computer have beaten it's master, incredible..")
cpu_wins = cpu_wins.append(1)
return
def end_score(human_wins, cpu_wins, draw):
human_wins = sum(human_wins)
cpu_wins = sum(cpu_wins)
draw = sum(draw)
print("Humans final score is: ", human_wins)
print("Computers final score is: ", cpu_wins)
print("Total draws: ", draw)
def main():
human = 0
human_wins = []
cpu = 0
cpu_wins = []
draw = []
finalhuman_wins = 0
finalcpu_wins = 0
finaldraw = 0
Continue = 'y'
single_player()
while Continue == 'y':
human = player_one()
cpu = computers_brain()
who_won(human, cpu, human_wins, cpu_wins, draw)
Continue = input("Would you like to play again (y/n):").lower()
if Continue == 'n':
print("Printing final scores.")
break
end_score(human_wins, cpu_wins, draw)
main()
elif program_choice == 2:
print("You picked a New Two Player Game - Play against another person, using same computer")
elif program_choice == 3:
print("You picked the Bonus Feature - A bonus feature of choice")
elif program_choice == 4:
print("You picked the User Guide - Display full instructions for using your application")
elif program_choice == 5:
print("You picked to Quit - Exit the program")
return program_choice
elif what_program != 1 or 2 or 3 or 4 or 5:
print("To initiate a program you need to type in the appropriate number to initiate this program, either 1, 2, 3, 4 & 5 ")
choose_program()
Outout in IDE:
Press '1' for New Single Player Game - Play against computer component:
Press '2' for New Two Player Game - Play against another person, using same computer:
Press '3' for Bonus Feature - A bonus feature of choice:
Press '4' for User Guide - Display full instructions for using your application:
Press '5' for Quit - Exit the program:
Process finished with exit code 0
Thank you in advance for your help :)

Resources