I am trying to write a game where Player One picks a number and Player Two has 5 Guesses to guess it. If he manages to do so, he wins, if not, he losses and Player One wins.
So I have the code, but if for example Player one picks the number '3' and Player Two enters the number '3' on any of his goes, it still says Player One wins.
>>>
Player One enter you chosen number: 3
Player Two have a guess: 3
Player One wins.
>>>
This happens also:
>>>
Player One enter you chosen number: 5
Player Two wins.
Also, player two can have as many turns as he likes, but it should only be 5. If he passes that amount, Player One automatically wins. Here is my code: (I don't know here I went wrong.)
def Game():
Guess = 0
NumberOfGuesses = 0
NumberToGuess = int(input("Player One enter you chosen number: "))
while NumberToGuess < 1 or NumberToGuess > 10:
NumberToGuess = int(input("Not a valid choice, please enter another number: "))
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player One wins.")
else:
print("Player Two wins.")
Game()
Your if statement is the wrong way around.
Instead of
if Guess == NumberToGuess:
print("Player One wins.")
else:
print("Player Two wins.")
it should be
if Guess == NumberToGuess:
print("Player Two wins.")
else:
print("Player One wins.")
because player 2 wins if he guesses the number that player 1 has chosen (NumberToGuess).
I cannot reconstruct your second problem where player 2 wins immediately of player 1 enters 5. It works fine for me.
The logic is wrong. If the input is not equal to NumberToGuess then you cannot print Player Two wins.
You must then loop. Then outside the loop check if player one was successful.
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player Two wins.")
if Guess != NumberToGuess:
print("Player One wins.")
"""This game generates random number, then players try to guess the number generated"""
import random
#generate number directly
num = random.randrange(1,5)
#initialize global variables
player1 = "Human"
player2 = "Alien"
player = ""
player1PlayCount = 0
player2PlayCount = 0
maxPlayTimes = 3
#game logic
def Game():
global player1, player2, player, player1PlayCount, player2PlayCount, maxPlayTimes, num
"""enter and assign names to players"""
player1Name = input('Player1 Enter Your Name: ')
player2Name = input('Player2 Enter Your Name: ')
player1 = player1Name
player2 = player2Name
player = player1
print(player1, 'turn')
while ((player1PlayCount and player2PlayCount) != maxPlayTimes):
guessNum = int(input("Guess Number: "))
if guessNum == num:
print(player, "won")
exit()
elif player == player1:
player1PlayCount +=1
player = player2
print(player2, 'turn')
elif player == player2:
player2PlayCount +=1
player = player1
print(player1, 'turn')
else:
print("Both ", player1, " and ", player2, " lose")
exit()
Game()
Related
I am new to python and built this for practice. How come if you guess incorrectly the print function runs repeatedly. Additionally, if you make a correct guess the corresponding print function doesn't run.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
elif guess < rand:
print("Too Low")
If the number is incorrect we need to ask the player to guess again. You can use break to avoid having an infinite loop, here after 5 guesses.
The conversion of the input to integer will throw an error if the entry is not a valid number. It would be good to implement error handling.
import random
print("Welcome to the Guessing Game")
rand = random.randint(1, 9)
count = 0
running = True
guess = int(input("Pick a number from 1 - 9"))
while guess != rand:
count += 1
if guess > rand:
print("Too High")
running = False
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
running = False
break
elif guess < rand:
print("Too Low")
if i >= 5:
break
guess = int(input("Try again\nPick a number from 1 - 9"))
in the first while loop, when player guesses the correct number we need to break.
Also for counting the number of rounds that player played we need a new while loop based on count.
When we use count in our code we should ask player every time that he enters the wrong answer to guess again so i used input in the while
import random
print("Welcome to the Guessing Game:")
rand = random.randint(1, 9)
count = 0
while count!=5:
guess = int(input("Pick a number from 1 - 9:"))
count += 1
if guess > rand:
print("Too High")
elif guess == rand:
print("Winner Winner Chicken Dinner")
print("You won in", count, "tries!")
break
elif guess < rand:
print("Too Low")
print('you lost')
The question is :
Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input), compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game)
player1 = input("Player 1: ")
player2 = input("Player 2: ")
if player1 == "rock" and player2 == "paper":
print("Player 2 is the winner!!")
elif player1 == "rock" and player2 == "scissor":
print("Player 1 is the winner!!")
elif player1 == "paper" and player2 == "scissor":
print("Player 2 is the winner!!")
elif player1 == player2:
print("It's a tie!!")
After asking if the players want to start a new game, how to restart the code?
You could use a while loop, i.e. something like
play = 'Y'
while play=='Y':
# your original code
play = input("Do you want to play again (Y/N): ")
Also I'd suggest you check that the responses from the user are valid (i.e. what if they type potatoe, in your code nothing will print if one or both players don't respond with rock, scissors or paper. You should also look at the lower() command and convert the answer to lower case for this reason.
options = {"rock" : 0, "paper": 1, "scissors": 2} #correct inputs
ratio = options[player1] - options[player2]
if player1 not in options.keys() and player2 not in options.keys():
return 0 #tie, both inputs wrong
if player1 not in options.keys():
return 2 #Player1 input wrong, Player 2 wins
if player2 not in options.keys():
return 1 #Player2 input wrong, Player 1 wins
if ratio == 0:
return 0 #tie
if ratio == 1 or ratio == -2:
return 1 #Player 1 wins
return 2 #Player 2 wins
Hi i am unsure on how to add a second player for this number guessing game whereby after player 1 makes a guess, then player 2 makes a guess. like between every guess. I am only able to make it so that the player 2 guesses after player 1 guesses finish all of his choices(code below) if anyone is able to tell me if what i am looking for is possible or if there is any advice, it would be greatly appreciated. thanks in advance.
def main():
import random
n = random.randint(1, 99)
chances = 5
guess = int(input("Player 1 please enter an integer from 1 to 99, you have 5 chances: "))
while n != "guess":
chances -=1
if chances ==0:
print("out of chances")
break
if guess < n:
print("guess is low")
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guess = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
import random
n1 = random.randint(1, 99)
chances1 = 0
guess1 = int(input("Player 2 please enter an integer from 1 to 99, you have 5 chances "))
while n1 != "guess":
chances1 +=1
if chances1 ==5:
print("out of chances")
break
if guess1 < n1:
print("guess is low")
guess1 = int(input("Enter an integer from 1 to 99: "))
elif guess > n1:
print ("guess is high")
guess1 = int(input("Enter an integer from 1 to 99: "))
else:
print("you guessed it")
break
retry=input("would you like to play again? (please choose either 'yes' or 'no')")
if retry == "yes":
main()
else:
print("Okay. have a nice day! :D ")
main()
to achieve this I would use a while loop and a variable to detect which players turn it is. Like this:
import random
random_number = random.randint(1, 99)
player_chances = 5
current_player = 1
while player_chances > 0:
if current_player == 1:
guess = int(input("Player 1 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 2
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
else:
guess = int(input("Player 2 please enter an integer from 1 to 99, {} chances left. ".format(player_chances)))
player_chances -= 1
current_player = 1
if guess < random_number:
print("->guess is too low")
elif guess > random_number:
print("->guess is too high")
else:
print("CONGRATULATIONS! You guessed it! Player 1 wins!")
break
print("####")
print("Out of chances! The number was {}.".format(random_number))
print("####")
To make this possible in an efficient way I would have created a player class as such:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTrys = 0
self.guess = 0
def getNumberOfTrys(self):
return self.getNumberOfTrys
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTrys+=1
return self.guess
except Exception as error:
print(error)
return None
this class is responsible to create the player with the number of tries,his guess and his name.
the logic will be going through the list of players (you can add as much as you want) and perform the game logic as follows:
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1)
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1)
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear()
break
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Basically, create a list of players then go through each one and apply the game logic (getting input, comparing and checking number of tries)
after a player loses, we should remove him from the list and if a player wins we can clear the list and thus exiting the game.
Here is the full code:
class Player:
def __init__(self,name):
self.name = name
self.getNumberOfTries = 0
self.guess = 0
def getNumberOfTries(self):
return self.getNumberOfTries
def getPlayerName(self):
return self.name
def play(self):
try:
self.guess = int(input("Enter an integer from 1 to 99: "))
self.getNumberOfTries+=1
return self.guess
except Exception as error:
print(error)
return None
import random
p1 = Player("Player 1")
p2 = Player("Player 2")
players = []
players.append(p1) #addding player
players.append(p2)
n1 = random.randint(1, 99)
NUMBER_OF_TRIES = 5
print(n1) #for debug
while players:
for player in players:
print(player.getPlayerName() + " turn, you have " + str(NUMBER_OF_TRIES - player.getNumberOfTries) + " turns left")
guess = player.play()
if guess < n1:
print("guess is low")
elif guess > n1:
print ("guess is high")
else:
print(player.getPlayerName()," you guessed it")
players.clear() # exit game
break #exit loop
if player.getNumberOfTries == NUMBER_OF_TRIES:
print(player.getPlayerName(), " out of chances")
players.remove(player)
Hope I got your question right, and excuse me If there is any errors or typos, I just created something fast that you can be inspired by. I highly suggest you get into OOP, it very simple and it can make your life much easier :)
All the best!
I have made a dice roll game on Python 3 but want to add a betting function.
I have tried a few things but I can only play one game. I want the game to have multiple rounds.
How do I make it a game where the player(s) can bet on multiple rounds until money ends at 0, or possibly keep playing until they want to stop?
import random
import time
print("this is a dice roll game")
def main():
player1 = 0
player1wins = 0
player2 = 0
player2wins = 0
rounds = 1
while rounds != 5:
print("Round" + str(rounds))
time.sleep(1)
player1 = dice_roll()
player2 = dice_roll()
print("Player 1 rolled " + str(player1))
time.sleep(1)
print("Player 2 rolled " + str(player2))
time.sleep(1)
if player1 == player2:
print("The round is a draw")
elif player1 > player2:
player1wins += 1
print("Player 1 wins the round")
else:
player2wins += 1
print("Player 2 wins the round")
rounds = rounds + 1
if player1wins == player2wins:
print("The game ended in a draw")
elif player1wins > player2wins:
print("Player 1 wins the game, Rounds won: " + str(player1wins))
else:
print("Player 2 wins the game, Rounds won: " + str(player2wins))
def dice_roll():
diceroll = random.randint(1,6)
return diceroll
main()
Adding to the comment by John Coleman, you can modify your while loop so that it does not end when the number of rounds is different to 5, something like:
while True:
// Rest of code...
if moneyP1 <= 0 OR moneyP2 <=0:
print("Someone ran out of money")
// Implement deciding who won
break
user_confirmation = raw_input("Keep playing? (YES/NO): ")
if user_confirmation == "NO":
break
I have my game working fine now but I still want to take it further. I want to have a point scoring system included. I want the player to score 5 points if they have 1 live left when they win, 10 if they have 2 and 15 if they have all 3. But I don't want the score to be reset if they play again I just want it to say when the quit the game you have scored " " points. I have tried to do this in many different ways but I can seem to get it work it resets the score every time press y on the play again. I've included my base game code below please try and help. Any other recomendations for this game are very welcome.
**My apologies I don't know if I made this clear enough before. I don't want the score to be stored after the programs closed just until the player presses n when asked to play again **
#imports required modules
import random
#correct number variable created
num = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!\n')
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives = lives -1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()
Use this pattern:
def game(): # Play a single game.
lives = 3
...
return 5 * lives # Return the score of the game.
def ask_again():
print 'Play again?'
answer = ...
return answer == 'y' # Return True iff the user wants to play again.
def main():
score = game()
while ask_again():
score += game()
print score
main()
You should use global variable for storing the amount of scored points.
So I added code for adding points and printing the message:
#imports required modules
import random
#correct number variable created
num = 0
score = 0
#generates number at random
comp_num = random.randint(1,10)
print('I\'m thinking of a number guess what it is...\n')
#main game code
def main():
#generates number at random
comp_num = random.randint(1,10)
#set num as a global variable
global num
global score
#lives created
lives = 3
while lives >= 1:
#player guesses
guess = int(input('Guess: '))
if comp_num == guess:
#if correct says well done
print('\nWell Done! You guessed Correctly!\n')
# add score
if lives == 3:
score += 15
elif lives == 2:
score += 10
elif lives == 1:
score += 5
break
elif comp_num >= guess:
#if guess is too low tells player
#one live taken for incorrect guess
lives -= 1
print('\nToo low!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
elif comp_num <= guess:
#if guess is too high tells player
#one live taken for incorrect guess
lives -= 1
print('\nToo high!\n')
#player is told how many lives they have left
print('You guessed incorrectly. You have',lives,'live(s) remaining.\n')
if lives == 0:
#if player guesses incorrectly they get told the correct awnser
print('The number I was thinking of was...',comp_num,'!\n')
def end():
global score
#asks player if they want to play again
play_again = input('Would you like to play again?[Y/N] ')
while play_again.lower() == 'y':
#if they do game resets and plays again
if play_again.lower() == 'y':
comp_num = random.randint(1,10)
print('\nI\'m thinking of a number guess what it is...\n')
main()
play_again = input('Would you like to play again?[Y/N] ')
if play_again.lower() == 'n':
break
if play_again.lower() == 'n':
#if they don't game ends
print("You scored " + str(score) + " amazing points!")
input('Ok, Press enter to exit')
exit()
#calls main section of game
main()
#calls end of game to give option of playing again and reseting game
end()