Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am making a Blackjack game in Python, and I am using a while loop. In my code I got an input with an if statement where if the player choose to play another round (types in "Y"), the game starts again (which I got no problem with). My problem is that if the player types in "N" (for no), the game still reruns. What I am trying to do is that when the player types in "N", the game is ended. What is wrong in my code? I am stuck and can't figure it out.
Also as you can see in my code, I use the closed = True several times in the while-loop and it works (for example if the player gets a score of 21, the game ends). The only time the closed = True does not work is in the elif play_again.lower() != "Y": closed = True part of my code.
closed = False
while not closed:
if player_total == 21:
print("\nCongrats, the player got a Blackjack!")
closed = True
else:
input_answer = int(input("\n1 - Hit \n2 - Stand \n \nDo you wish to Hit or Stand? "))
if input_answer == 1:
print("You chose to Hit.")
give_cards(player_hand, 1)
player_total = bjm.calculate_hand_value(player_hand)
print(f'\nThe player has got a new card: {player_hand[2]}. \nThe player currently has {", ".join(player_hand)},'
f' with a total value of {player_total}.')
if player_total > 21:
print("Busted! You got a total value over 21.")
closed = True
elif input_answer == 2:
print("\nYou chose to Stand.")
print(f'The dealers cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
print(f'The players cards are {", ".join(player_hand)} with a total value of {player_total}.')
print_result(player_hand, dealer_hand)
play_again = input("\nDo you want to play another round? Y/N: ")
if play_again.lower() != "N":
print("You wanted to play another round, you will be dealt two new cards.\n")
player_hand.clear()
dealer_hand.clear()
give_cards(player_hand, 2)
give_cards(dealer_hand, 2)
print(f'\nThe players new cards are: {" and a ".join(player_hand)}, with a total value of {player_total}.')
print(f'The dealers new cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
elif play_again.lower() != "Y":
closed = True
closed = True
A better way than what you are using right now to end the loop is to simply replace your condition in closed = True with break.
Additionally, the reason your code isn't working is because you are trying to compare the .lower() (which will always give you a lower case letter) with a capital case letter, which means that this condition:
elif play_again.lower() != "Y":
closed = True
will never be true.
replace it with "y" instead of "Y"
I'm not sure why you are using double negatives. Try this instead:
while True:
...
elif play_again.lower() != "Y":
break #instead of closed=True
Remove the .lower(). You are trying to lowercase and validate it with Y or N which will never get to else statement
Example -
play_again = input("\nDo you want to play another round? Y/N: ")
if play_again != "N":
print("You wanted to play another round, you will be dealt two new cards.\n")
elif play_again != "Y":
print("Dont want to play")
You could set the acceptable answers as
valid_answers = ['yes', 'no']
if valid_answers == "no":
print("You wanted to play another round, you will be dealt two new cards.\n")
player_hand.clear()
dealer_hand.clear()
give_cards(player_hand, 2)
give_cards(dealer_hand, 2)
print(f'\nThe players new cards are: {" and a ".join(player_hand)}, with a total value of {player_total}.')
print(f'The dealers new cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
else:
closed = True
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
they closed this question so I can't delete it because people "answered it" whatever
The problem is that the scoreboard isn't updating when the game ends; it's only shown at the beginning.
How do we fix this? Do we need to implement a loop, or rearrange parts of our code?
Here is the code:
import time
print("Tic-Tac-Toe Game ")
print("Please Wait...")
time.sleep(3)
def game_winner(player):
if Game==Draw:
print("Game Draw")
return 'D'
elif Game==Win:
player-=1
if player != 0:
print("Player 1 Won")
return
else:
print("Player 2 Won")
return
So, I just ran your code and managed to get through one game correctly. You are right that upon completion of one game, entering "yes" does not show the scoreboard correctly.
You already have your code set up as various functions, which is good. What you might want to do is have a play(board, player:str, move:int) function that accepts the player and the respective move and updates the board each time. You will need a modified while loop, because a draw, win or lose condition would end the game. The play() function should just keep track of the current player, and switch between 0 and 1, respectively as each move is played.
You might have something like:
# Set player 0 to start, X
start_player = 0
while not checkGameEnd():
# Take player input
move = int(input("Where do you want to move?"))
# Make the play
play(board, start_player, move)
# Print the board
printBoard()
# Change player
start_player = 1 if start_player is 0 else 1
# Game should end here
printScores()
playAgain()
This is sort of pseudo-code, but you can modify the logic as per your usecase.
The scoreboard printed at the end for me when I responded n to the question 'Do you want to play again?'.
However, it showed 0-0 because the code doesn't update the scores. I think you want to add the following in the game_winner function:
elif Game ==Win:
player -= 1
if player != 0:
print("Player 1 Won")
score_board[player1] += 1
return
else:
print("Player 2 Won")
score_board[player2] += 1
return
Also, you'll need to move the game_winner(player) function call at the end outside of the while loop so that it only called once.
you need to modify the score_board variable at the end of each match, so that when you print it at the end of the game it will be updated with the final score,to do so you can modify your game_winner function like this:
def game_winner(player):
if Game==Draw:
print("Game Draw")
score_board[player1] += 0.5
score_board[player2] += 0.5
return 'D'
elif Game ==Win:
player -= 1
if player != 0:
print("Player 1 Won")
score_board[player1] += 1
return
else:
print("Player 2 Won")
score_board[player2] += 1
return
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So I am creating a new simple game to practice my python programming, it is a point/score system that I wanted to implement. I also wanted to make it so it's intelligent by asking the user if it wants to play. So I have three problems at the moment, when I ask the user if it wants to play I wasn't sure what to do if they said no or "n" if they didn't want to play, instead what happens is that it just continues playing then crashes saying "n" is not defined. The second problem that I have is when the user puts the right answer for the random function I put print("You guessed it right!") but it just prints a bunch of them. My third and final problem is the point system, I wasn't sure if it executed after the million printed statements, but I'll see after I fix it.
Here is my game
import random
total_tries = 4
score = 0
print("Welcome to Guess the number game!")
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))
guess = int(input("I am thinking of a number between 1 and 20: "))
while n!= guess:
if guess < n:
total_tries - 1
print("That is too low!")
guess = int(input("Enter a number again: "))
elif guess > n:
print("That is too high")
total_tries - 1
guess = int(input("Enter a number again: "))
else:
break
while n == guess:
score = +1
print("You guessed it right!")
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
print("Mark:", str(mark) + ""%"")
print("Goodbye")
Error when putting no for playing:
while n!= guess:
NameError: name 'n' is not defined
For question 1 you want the system to exit when the user says no. I would do this by using sys.exit to kill the code.
import sys
...
answer = input("Would you like to play? y/n: ")
if answer == "y":
n = (random.randrange(1, 10))**strong text**
else:
sys.exit('User does not want to play, exiting')
For problem 2 you are getting your print statement a million times because you're failing to exit. In the code below n is always equal to guess because you never change n. You don't need a while statement here because you already know you only left the above section when n started to equal guess. Another issue to think about. How will you make it stop when the number of turns runs out?
while n == guess:
score = +1
print("You guessed it right!")
For the third question, think about what will happen here if the number of turns reaches 0.
if total_tries == 0:
print("Thank you for playing, you got", score, "questions correct.")
mark = (score/total_tries) * 100
In particular, what would happen when you try to calculate mark?
This condition will only trigger when answer is "y"
if answer == "y":
n = (random.randrange(1, 10))
Remove this and the code will run or modify it as such
if answer == "y":
n = (random.randrange(1, 10))
elif answer == "n"
# set n to some other value
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to write a python word puzzle game which may have multiple players and points are given based on the length of the words found.
Here is my function which 'plays' the game, however, it always results in "Game over!" no matter if my answer is right or wrong. So it quits the game every time.
def play_game(players, board , words, answers):
found_words = []
num_remaining = num_words_on_puzzle - len(found_words)
player_num = 0
while num_remaining > 0:
print_headers(players, board, found_words, num_remaining)
guess_input = input("{player}, make a guess: ".format(
player=players[player_num % len(players)][0]))
# Allow player to quit
if guess_input.lower() == 'q' or 'quit':
break
# Determine if the guess is valid
guess = convert_guess(guess_input)
if is_valid_answer(answers, guess):
# Update a players score since answer is valid
update_score(players[player_num % len(players)], matching_answer(answers, guess))
# Add this word to found_words list
found_words.append(matching_answer(answers, guess))
print("Congratulations, you found '%s'." % matching_answer(answers, guess))
print("That's %d points(s)." % word_score(matching_answer(answers, guess)))
else:
print("Sorry, that is incorrect.")
num_remaining = num_words_on_puzzle - len(found_words)
player_num += 1
print("\nGame over!\n")
print("The final scores are: \n")
print_score(players)
print(answers)
I hope someone can help me see where my issue is.
The line:
if guess_input.lower() == 'q' or 'quit':
always evaluates to True, because it goes as
if (uess_input.lower() == 'q') or ('quit') which is (False) or (True) --> True as any String != '' is True
Change
if guess_input.lower() == 'q' or 'quit':
to
if guess_input.lower() in ['q', 'quit']
I am making a custom version of hangman for a college assignment using python, but currently I'm having an issue with two parts to my code, its a game of hangman.
I have included the entire code below so that if anyone can answer they have the full information from the code.
The issues I'm having are that this part of the code is not ignoring the input before so it still lets you guess multiple letters.
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
The second issue I have is that once you win the game it doesn't ask if you want to play again properly (I have tried multiple methods to try to fix this including another while loop inside the if statement.
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
print
...
while True:
...
if failed == 0:
print("Ye be living for now")
print("The word was: " + myword)
# Current Bug: Play again here, cannot use same line as end.
print
guess = input("guess a letter: ").lower()
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
guesses += guess
...
play_again = input("If you'd like to play again, please type 'yes' or 'y': ").lower()
if play_again == "yes" or play_again == "y":
continue
else:
play_again != "yes" or play_again != "y"
break
This should solve your problem of taking multiple letters as input
if len(guess) > 1:
print("Ye can't be cheatin' now, ye be using up ya guesses.")
failed += 1
# Current Bug: still takes input into consideration when it shouldn't
else:
guesses += guess
This will only add the input to guesses if its length is less than 1.
And if you want to ask the game to play again, after winning put your code in a while loop. Something like this:
play_again = 'y'
while(play_again == 'y' or play_again='yes'):
win = False
while(!win):
<your code for game, set win = True after winning>
play_again = input("Want to play again y or n: ").lower()
Edit: You can add failed along with win in the while loop as well.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
For some reason my program keeps rolling the dice again regardless of the users answer, and it doesn't print the goodbye message.
I'll include the code below so you can test yourself (Python 3)
from random import randint
def rollthedice():
print("The number you rolled was: "+ str(randint(1,6)))
rollthedice()
shouldwecontinue = input("Do you wish to roll again? (y or n) ").lower()
if shouldwecontinue == "y" or "yes":
rollthedice()
elif shouldwecontinue == "n" or "no":
print("Goodbye.")
elif shouldwecontinue != type(str):
print("Sorry the program only accepts 'y' or 'n' as a response.")
The desired effect of the program should be that if the user enters y, it rolls the dice again, respectively starting the whole program again. Whereas, if the user enters no then it should print the Goodbye message.
or doesn't work like that. Right now your program is evaluating (shouldwecontinue == "y") or "yes", and since Python interprets "yes" as truthy, then that condition always succeeds. The simplest fix is to change it to shouldwecontinue == "y" or shouldwecontinue == "yes". And then similar changes for the other conditional expressions, of course.