I created a game, in which there is a secret number, and you guess, then the computer guesses. The secret number changes every round. To win, either you or the computer needs to get a score of 2.
I don't know how many rounds it will take, so I loop the game 100 times in a while loop with the condition that the user_Score and computer_Score is not equal to 2,
However, when I run my code, it seems like it just skips the condition, and goes on 100 times, and I don't understand why.
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
The above code is the part which I am talking about, it is in the near bottom of my code
import random
computer_score = 0
user_score = 0
def game():
global user_score
global computer_score
secret_number = random.randrange(10)
while True:
user_guess = input("Guess a number from 0 - 10: ")
if user_guess.isdigit():
user_guess = int(user_guess)
if 0 <= user_guess <= 10:
break
else:
print("Enter a valid number from 0 - 10")
else:
print("Please enter a valid number from 0 - 10")
computer_guess = random.randrange(10)
if user_guess == secret_number:
print("Hooray! You guessed correctly")
user_score += 1
print(f"Your score is {user_score}")
else:
print("Sorry wrong guess")
print("Now Player 2's turn")
if computer_guess == secret_number:
print("Player 2 guessed the correct number!")
computer_score += 1
print(f"Player 2's score is {computer_score}")
else:
print("Player 2 guesed incorrectly")
print( f" Your score: {user_score}" + " " + f"Player 2 score: {computer_score}")
game()
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
if user_score == 2:
print(f"Hooray! You won with a score of {user_score} points")
print(f"Player 2 got {computer_score} points")
elif computer_score == 2:
print(f"Sorry, you lost. Your score is {user_score}, and Player 2 got {computer_score} points")
print( f" Your final score: {user_score}" + " " + f"Player 2 final score: {computer_score}" )
while user_score != 2 or computer_score != 2:
for _ in range(100):
game()
If a player gets a score of two, that will not stop the inner for loop. It's going to loop to 100, because that's what you told it to do.
I'm confused why you need the inner loop at all, though. Isn't the outer while loop enough?
while user_score != 2 or computer_score != 2:
game()
Also, wouldn't you want to use and here, instead of or? The way this is written, it will only stop if both scores are equal to 2. And if one of the players gets to a score of 3 while the other player has a score of 0 or 1, this loop will never exit.
It will always show this same fault. Because, at the beginning of the game when 1st round is over, the for loop starts iterating and it will continue for 100 times. Best way is to remove the for loop and just run the while loop.
while user_score != 2 or computer_score != 2:
game()
Related
Something is wrong with this code, even though no error has been reported. The program simply skips both while loops. Can someone help me?
def play_game():
#print(logo)
user_cards = []
computer_cards = []
is_game_over = False
for _ in range(2):
user_cards.append(deal_card()) #deal_card() is predifined function
computer_cards.append(deal_card())
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards) #calculate score is predefined function
print(f" Your cards: {user_cards}, current score: {user_score}")
print(f" Computer's first card: {computer_cards[0]}")
if user_score == 0 or computer_score == 0 or user_score > 21:
is_game_over = True
else:
while is_game_over:
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == "y":
user_cards.append(deal_card())
else:
is_game_over = 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}, final score: {user_score}")
print(f" Computer's final hand: {computer_cards}, final score: {computer_score}")
print(compare(user_score, computer_score))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clear()
play_game()
You should add a not keyword before your while condition as it's now stating that it will keep running while it's game over, and your variable starts as false so it won't even enter once right now.
Fixed while loop:
while not is_game_over:
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == "y":
user_cards.append(deal_card())
else:
is_game_over = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
As you can see, I'm a complete beginner at Python so any help would be appreciated. My issue is that I'm trying to test the code for all the scenarios, but I'm unable to test the tiebreaker. Sure, I could just insert Player1Score = Player2Score (which I've hash tagged to show the location) but that would just send the program into an endless loop, which defeats the purpose of the tiebreaker. So is there any way that I can I can have the program only go through the tiebreaker segment once and then let a single player win?
(I apologize if I've made any errors with my question, I'm new to stackoverflow as well)
import random
def DiceGame():
Count = 0
Player1Score = 0
Player2Score = 0
while Count <= 4:
Count += 1
print ("\n It is Round",Count, "\n")
print ("It is Player 1's turn.")
x = input("Press [Enter] to roll.")
Score = Rolls()
Player1Score += Score
print ("Player 1, your score so far is",Player1Score)
print ("It is Player 2's turn.")
x = input("Press [Enter] to roll.")
Score = Rolls()
Player2Score += Score
print ("Player 2, your score so far is",Player2Score)
#Player1Score = Player2Score
if Player1Score == Player2Score:
print ("It is a tie!")
print ("There will be a final tiebreaker.")
Count -= 1
DiceGame()
elif Player1Score >= Player2Score:
print ("Player 1 wins!")
elif Player1Score <= Player2Score:
print ("Player 2 wins!")
def Rolls():
Roll1 = random.randint(1,6)
Roll2 = random.randint(1,6)
print ("You got a",Roll1)
print ("You got a",Roll2)
Score1 = Roll1 + Roll2
if Score1 == 2 or Score1 == 4 or Score1 == 6 or Score1 == 8 or Score1 == 10 or Score1 == 12:
print ("Your total is even so you get an extra 10 pts.")
Score2 = Score1 + 10
print ("Your score for this round is" ,Score2)
elif Score1 == 3 or Score1 == 5 or Score1 == 7 or Score1 == 9 or Score1 == 11:
print ("Your total is odd so you lose 5 pts.")
Score2 = Score1 - 5
if Score2 <= 0:
print ("Your score has gone below 0pts. It will therefore be reset to 0pts")
Score2 = 0
print ("Your score for this round is" ,Score2)
return Score2
DiceGame()
If you really want to, you can add temporary player scores to test the function, and then remove them again if you see they work. Usually running it would just be good enough, but as you mentioned it would loop forever. This does kinda show that it works though, I guess, but I agree it's not optimal.
def DiceGame(count, p1, p2):
Count = count
Player1Score = p1
Player2Score = p2
...
Then at the bottom of your file call it as DiceGame(5, 1, 1), and in your tiebreaker call it as DiceGame(0, 0, 0). This will force a tie on the first run, and will run it normally the second time.
if Player1Score == Player2Score:
print ("It is a tie!")
print ("There will be a final tiebreaker.")
Count -= 1
DiceGame(0, 0, 0)
... # code inbetween
# end of file
return score2
DiceGame(5, 1, 1)
I'm fairly new to Python and I've made a random number guessing game. The problem I'm running into is I cannot get my program to exit the while loop when I reach 0 lives instead it tells me i have -1 lives or -2 lives etc. I've looked over the code and I'm struggling to see the flaw in my logic/programming. Any help with this would be appreciated!
from random import randint
randomnumber = randint(1, 30)
print("Welcome to the number guessing game!")
game = False
lives = 3
while not game or lives == 0:
playerguess = int(input("Please enter a number between 1 and 30: "))
if playerguess > 30 or playerguess < 1:
print("Please only enter numbers between 1 and 30")
elif playerguess == randomnumber:
print("Correct!")
game = True
elif playerguess == randomnumber - 1 or playerguess == randomnumber + 1:
lives -= 1
print("You were so close! You now have", lives, "lives remaining!")
else:
lives -= 1
print("Not even close! You now have", lives, "lives remaining!")
if game:
print("Congratulations you won with ", lives, "lives remaining!")
else:
print("Sorry you ran out of lives!")
Change to this while not game and lives > 0.
Your current statement while not game or lives == 0, means that the loop can continue if lives are not 0 or not game since you can run out of lives without changing game to True the loop won't exit.
This new condition will only allow to run the game if you have more than 0 lives and not game which will fix the issue.
Congratulations you won with 3 lives remaining!
...
Not even close! You now have 0 lives remaining!
Sorry you ran out of lives!
Your condition is wrong:
while not game and lives > 0:
You want to loop while the game is not complete (not game) and while the number of lives is greater than 0 (lives > 0).
You should improve your while conditions to while not game and lives > 0 or add a break command in your while loop that will only get called whenever you reach lives < 1:
...
while not game:
playerguess = int(input("Please enter a number between 1 and 30: "))
if playerguess > 30 or playerguess < 1:
print("Please only enter numbers between 1 and 30")
elif playerguess == randomnumber:
print("Correct!")
game = True
elif playerguess == randomnumber - 1 or playerguess == randomnumber + 1:
lives -= 1
print("You were so close! You now have", lives, "lives remaining!")
else:
lives -= 1
print("Not even close! You now have", lives, "lives remaining!")
#get out of loop if player died
if lives < 1:
break
if game:
...
I just started to learn Python and tried to make this game by myself for self-training.
I have made the game taking 2 more hours.
But I'd like to make score result(either 3 win or 3 lose) with break.
I don't know how to use while statement with break on this situation.
Hope to help me please.
import random
user_choice = input("select one of rock, paper, scissors. ")
Rock_paper_scissors = ['rock', 'paper', 'scissors']
computer_choice = Rock_paper_scissors[random.randint(0,2)]
if user_choice == computer_choice:
print("Draw.")
elif user_choice == "rock":
if computer_choice == "paper":
computer_score += 1
print("lose.")
else:
user_score += 1
print("win.")
elif user_choice == "scissors":
if computer_choice == "rock":
computer_score += 1
print("lose.")
else:
user_score += 1
print("win.")
elif user_choice == "paper":
if computer_choice == "scissors":
computer_score += 1
print("lose")
else:
user_score += 1
print("win")
Well first youll want to add those score variables at the begging of your code.
computer_score=0
user_score=0
then you want to have a while statement that also encloses the user input
Rock_paper_scissors = ['rock', 'paper', 'scissors']
while True:
user_choice = input("select one of "rock, paper, scissors. ")
computer_choice = Rock_paper_scissors[random.randint(0,2)]
#Your if/elif statements go here
And at the end and an if statement to check if someone has a score of 3 or more
if user_score >= 3:
print('You win')
break
You can loop your procedure for 3 times, stop when one of 2 opponent reach score of 2.
It will look something like this
while (user_score < 3 and computer_score < 3):
<continue playing>
If you want to use break:
while True:
<continue playing>
if user_score == 3 or computer score == 3:
break
Hope this help
The while loop in python works like this:
while condition:
do something...
While the condition is true the loop will keep going, in this case you don't need a break statement, you could simply do:
user_score = 0
computer_score = 0
while (user_score < 3 and computer_score < 3):
game...
If you really want to use a break statement, you could do it like this:
user_score = 0
computer_score = 0
while True:
if (user_score >= 3 or computer_score >= 3):
break
game...
That way the loop will keep going forever, since the condition is True, but the if inside the loop will call a break when a player scores 3 points.
user_score and computer_score are initialized to zero, you always have to initialize your variables.
I am a beginner in python using 2.7.11 and i have made a guessing game. Here is my code so far
def game():
import random
random_number = random.randint(1,100)
tries = 0
low = 0
high = 100
while tries < 8:
if(tries == 0):
guess = input("Guess a random number between {} and {}.".format(low, high))
tries += 1
try:
guess_num = int(guess)
except:
print("That's not a whole number!")
break
if guess_num < low or guess_num > high:
print("That number is not between {} and {}.".format(low, high))
break
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
playAagain = raw_input ("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if playAagain == "y" or "Y":
game()
elif guess_num > random_number:
print("Sorry that number is too high.")
high = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
elif guess_num < random_number:
print("Sorry that number is too low.")
low = guess_num
guess = input("Guess a number between {} and {} .".format(low, high))
else:
print("Sorry, but my number was {}".format(random_number))
print("You are out of tries. Better luck next time.")
game()
How would i incorporate a system that makes it so Each time the user guesses the correct number it includes feedback giving the fewest number of guesses it took to correctly guess the number. Like a high score on how many guesses it took them and to change it only if it was beaten
you can create a static variable like this :
game.highscore = 10
and you update it each time when the user wins the game (check if tries less than highscore)
You could add a best_score parameter to your game function:
def game(best_score=None):
...
elif guess_num == random_number:
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
# update best score
if best_score is None:
best_score = tries
else:
best_score = min(tries, best_score)
print("Best score so far: {} tries".format(best_score))
play_again = raw_input("Excellent! You guessed the number! Would you like to play again (y or n)? ")
if play_again.lower() == "y":
game(best_score) # launch new game with new best score
...
At the start of your code (before defining the function), add the global variable best_score (or whatever you want to call it), and initialize it as None:
best_score = None
During the check on whether the number is the correct guess, you can check the number of tries against the best_score, and update accordingly:
elif guess_num == random_number:
global best_score
# check if best_score needs to be updated
if best_score == None or tries < best_score:
best_score = tries
print("Congratulations! You are correct!")
print("It took you {} tries.".format(tries))
# print out a message about the best score
print("Your best score is {} tries.".format(best_score))