I'm trying to write a script for a game where the user has to guess a computer generated value. The aim is for the player number to be reduced until it has a value of 1 at which point it ends.
import random
import time
players = input("Let's play Five's! How many are you?:" )
#print("you are", players, "players?") #test number of players
players = int(players)
if players <=1:
print("Game Over")
else:
while players >= 1:
players = players+1
#Decide possible values than can be chosen
options = [] #Possible options
for i in range(0,players):
x = i * 5
options.append(x)
print("Your choices are", options)
#Playing the game
#Each turn
guess = random.choice(options)
print("Computer has chosen", int(guess))
count_down = 3
while (count_down):
print(count_down)
time.sleep(1)
count_down -= 1
choice = input("Guess:")
choice = int(choice)
if choice not in options: #If choice isn't a multiple of 5
input("Not allowed, choose again:")
elif choice in options and choice != guess: #Valid choice but wrong
print("Wrong") #so player is still in the
else: #game
choice = int(choice)
if choice == guess: #Correct choice so player leaves game
print("You're Out.") # this should reduce the player count
players -=1
I've included the line printing the computer generated value so I can give the correct guess but even if guess correctly it doesn't reduce the player count and so the game continues infinitely
You add a player on the first line of the while loop.
players = players+1
Then you subtract a player on the last line
players -=1
If I understand your code correctly, the number of players won't change.
Related
So this is my random number guessing program I made. It asks the user to input two numbers as the bound, one high and one low, then the program will choose a number between those two. The user then has to try and guess the number chosen by the program. 1) How do I get it to ask the user if they would like to play again and upon inputting 'yes' the program starts over, and inputting 'no' the program ends? 2) How do I create an error trap that tells the user "Hey you didn't enter a number!" and ends the program?
def main(): # Main Module
print("Game Over.")
def introduction():
print("Let's play the 'COLD, COLD, HOT!' game.")
print("Here's how it works. You're going to choose two numbers: one small, one big. Once you do that, I'll choose a random number in between those two.")
print("The goal of this game is to guess the number I'm thinking of. If you guess right, then you're HOT ON THE MONEY. If you keep guessing wrong, than you're ICE COLD. Ready? Then let's play!")
small = int(input("Enter your smaller number: "))
large = int(input("Enter your bigger number: "))
print("\n")
return small, large
def game(answer):
c = int(input('Input the number of guesses you want: '))
counter = 1 # Set the value of the counter outside loop.
while counter <= c:
guess = int(input("Input your guess(number) and press the 'Enter' key: "))
if answer > guess:
print("Your guess is too small; you're ICE COLD!")
counter = counter + 1
elif answer < guess:
print("Your guess is too large; you're still ICE COLD!")
counter = counter + 1
elif answer == guess:
print("Your guess is just right; you're HOT ON THE MONEY!")
counter = c + 0.5
if (answer == guess) and (counter < c + 1):
print("You were burning hot this round!")
else:
print("Wow, you were frozen solid this time around.", "The number I \
was thinking of was: " , answer)
def Mystery_Number(a,b):
import random
Mystery_Number = random.randint(a,b) # Random integer from Python
return Mystery_Number # This function returns a random number
A,B = introduction()
number = Mystery_Number(A,B) # Calling Mystery_Number
game(number) # Number is the argument for the game function
main()
You'd first have to make game return something if they guess right:
def game(answer):
guess = int(input("Please put in your number, then press enter:\n"))
if answer > guess:
print("Too big")
return False
if answer < guess:
print("Too small")
return False
elif answer == guess:
print("Your guess is just right")
return True
Then, you'd update the 'main' function, so that it incorporates the new 'game' function:
def main():
c = int(input("How many guesses would you like?\n"))
for i in range(c):
answer = int(input("Your guess: "))
is_right = game(answer)
if is_right: break
if is_right: return True
else: return False
Then, you'd add a run_game function to run main more than once at a time:
def run_game():
introduction()
not_done = False
while not_done:
game()
again = input('If you would like to play again, please type any character')
not_done = bool(again)
Finally, for error catching, you'd do something like this:
try:
x = int(input())
except:
print('That was not a number')
import sys
sys.exit(0)
So I'm currently having some trouble with working out how to basically create a "count" function work within my Rock, Paper, Scissors game. I'm new to Python and this is my first foray into the use of multiple functions to execute game logic. Here's my code...
import random
from random import choice
cpu_score = 0
player_score = 0
# dictionary from which gestures are pulled
gestures = ["rock","paper","scissors"]
n_rounds = int(input("How many rounds would you like to play? "))
while n_rounds % 2 == 0 or n_rounds <= -1:
print("Number of rounds must be an odd number! Select an odd number!")
n_rounds = input("How many rounds?")
break
print("Lets play",n_rounds,"rounds!")
rounds_to_win = ((n_rounds + 1)//2)
rounds_to_win = round(rounds_to_win)
print("You must win",rounds_to_win,"rounds to beat the game!")
def computer_choice():
"""Movement made by the computer"""
comp = random.choice(gestures)
return comp
def player_gesture():
"""Movement by player"""
player = input("Please select, rock, paper or scissors")
if player not in gestures:
print("That's not an option! Please try again.")
player = input("Please select, rock, paper or scissors")
return player
def who_won_round(comp, player):
'''Who is the winner of the round.'''
winner = 0
if ((player == "rock") and (comp == "paper")) or \
((player == "paper") and (comp == "scissors")) or \
((player == "scissors") and (comp == "rock")):
winner = 1
elif ((comp == "rock") and (player == "paper")) or \
((comp == "paper") and (player == "scissors")) or \
((comp == "scissors") and (player == "rock")):
winner = 2
else:
winner = 0
return winner
def win_counter(winner, cpu_score,player_score):
rounds = 1
if winner == 1:
player_score += 1
print("This is round",rounds)
rounds += 1
return player_score
if winner == 2:
cpu_score += 1
print("This is round",rounds)
rounds += 1
return cpu_score
def count_round(winner, player, comp, cpu_score, player_score):
if winner == 0:
print("It's a tie!")
elif winner == 1:
print("The player chose",player)
print("The computer chose",comp)
print("The computer won the round!")
print("The computer has won",cpu_score,"rounds!")
elif winner == 2:
print("The player chose",player)
print("The computer chose",comp)
print("The player won the round!")
print("The player has won",player_score,"rounds!")
def game_structure():
while rounds_to_win < n_rounds:
comp = computer_choice()
player = player_gesture()
winner = who_won_round(comp,player)
win_count = win_counter(winner, cpu_score,player_score)
count = count_round(winner, player, comp, cpu_score, player_score)
game_structure()
Basically I'm having issues returning the variables in order to keep count of the scores of the "number of rounds" and "cpu_score" and "player_score". I prefer to not declare global variables as I realise they can be messy to use, but I'm not quite sure how to avoid this.
If you must avoid the use of global variables, you should take an object oriented approach. That way you can store the variables in the object.
So basically you do something like this:
newgame = mytictactoe()
while True #infinite loop
input("wanna play?")
if input == yes:
newgame.start
else:
break
From what I see, the cpu_score and player_score are never updated. You only have the newest result in win_count, that is not assigned to cpu_score or player_score at anytime. It could be something like:
win_count = win_counter(winner, cpu_score,player_score)
if winner == 1:
cpu_score = win_count
if winner == 2:
player_score = win_count
rounds_to_win = max(player_score, cpu_score)
count_round(winner, player, comp, cpu_score, player_score)
I did not run it, but this modifications should do the trick. There are better ways of doing it; maybe using a list to keep the scores and use winner as the index, or an object approach as someone else said, but I do not want to change too much the code.
Also, bear in mind that the round variable in win_counter does nothing.
import random
import time
def closest_num(GuessesLog, CompNum):
return GuessesLog[min(range(len(GuessesLog)), key=lambda g: abs(GuessesLog[g] - CompNum))]
GameModeActive = True
while GameModeActive:
Guesses = None
GuessesLog = []
while not isinstance(Guesses, int):
try:
Guesses = int(input("How many guesses do you have?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
CompNum = random.randint(1,99)
print(CompNum)
Players = None
while not isinstance(Players, int):
try:
Players = int(input("How many players are there?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
NumberOfGuesses = []
for i in range(Guesses):
NumberOfGuesses.append(i+1)
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
for Guess in NumberOfGuesses:
if Guess != len(NumberOfGuesses):
print("ITS ROUND {}! GET READY!".format(Guess))
print(" ")
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
print(PlayersForRound)
print(NumberOfPlayers)
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
PlayersForRound
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
if Guess == len(NumberOfGuesses):
print("ITS ROUND {}! THIS IS THE LAST ROUND! GOOD LUCK!".format(Guess))
print(" ")
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
print("The closest guess was ", closest_num(GuessesLog, CompNum))
print(" ")
while True:
Answer = input("Would you like to play again? Y/N: ")
if Answer.lower() not in ('y', 'n'):
print("Please enter either Y for Yes, or N for No.")
else:
break
if Answer == 'y':
GameActiveMode = True
elif Answer == 'n':
GameActiveMode = False
print("Thankyou for playing ;)")
break
holdCall = str(input("Holding the console, press enter to escape."))
In my above code, when there are multiple players and multiple guesses(Rounds) then it works fine unless someone successfully guesses the code. If the code is guessed the code deletes the correct record from the player list. But for some reason fails to iterate over the rest of the list or if the correct guess comes from the second user it skips the next player altogether and moves onto the next round.
I have absolutely no idea why. Anyone have any ideas? Thanks in advance.
For example, if you run this in console and then have 3 guesses with 3 users, on the first player you guess incorrectly. On the second you guess correctly, it skips player 3 and goes straight to round 2. Despite only remove player 2 from the list after a correct guess.
Or if you guess it correctly the first time around it skips to the 3rd player?
You are keeping track of players in the current round using a list of player numbers. So, if you start with three players, PlayersForRound will start as [1,2,3].
You then proceed to loop over this list to give each player their turn by using for Player in PlayersForRound. However, PlayersForRound and NumberOfPlayers are the exact same list (not a copy), so when you remove a player from one, it is removed from both.
Once a player guesses correctly, you remove them from the list you were looping over with NumberOfPlayers.pop(Player-1). For example if the second player guesses correctly, you remove their "index" from the list and the resulting list is now [1,3].
However, because Python is still looping over that same list, player 3 never gets their turn, because their "index" is now in the position where the "index" of player 2 was a moment ago.
You should not modify the list you're looping over, this will result in the weird behaviour you are seeing. If you want to modify that list, you could write a while loop that conditionally increases an index into the list and checks whether it exceeds the length of the list, but there are nicer patterns to follow to achieve the same result.
As for naming, please refer to https://www.python.org/dev/peps/pep-0008/ - specifically, your variables like PlayersForRound should be named players_for_round, but more importantly, you should name the variables so that they mean what they say. NumberOfPlayers suggests that it is an integer, containing the number of players, but instead it is a list of player numbers, etc.
The selected bits of your code below reproduce the problem, without all the fluff:
# this line isn't in your code, but it amounts to the same as entering '3'
Players = 3
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
# this line is not in your code, but amounts to the second player guessing correctly:
if Player == 2:
NumberOfPlayers.pop(Player-1)
if Player == 3:
print('this never happens')
# this is why:
print(PlayersForRound, NumberOfPlayers)
When you pop the list, you intervene in the for loop. Here, you can play with this and see yourself.
players = 3
player_list = []
for p in range(players):
player_list.append(p + 1)
for player in player_list:
print(player)
if player == 2:
print("popped:",player_list.pop(player-1))
Output
1
2
popped: 2
I am creating a Python Dice game called Beat That. I have gotten everything to work so far except for taking the players guess and comparing it to the highest possible number you can make. So let's say you roll a 5 and a 2 the highest number you could make it 52. So far when I enter the correct number it always says incorrect. Any help is appreciated.
In the screenshot below everything works except for the def turn section where it says "The highest number you could've made out of your roll is ...". It prints out the correct number but it marks it as incomplete.
This is the whole code:
import random
import time
from random import randint
play_again = True
#greeting the players to the game
print("Welcome to Beat That, a small game made by Mats Muche.")
#as long as play_again is true this will repeat itself until the user decides to end the game
while play_again:
totalnumber = []
def rollDice(numOfDice):
num = []
for i in range(1,numOfDice+1):
num = randint(1, 6)
print("Rolling the dice... You rolled a",num)
totalnumber.append(num)
time.sleep(1.5)
return num
return totalnumber
#this part checks the players guess to the highest number that can be made
def turn(numOfDice):
roll = rollDice(numOfDice)
totalnumber.sort(reverse = True)
print(*totalnumber , sep="")
guess = int(input("What is the biggest number you can make?"))
if guess == totalnumber:
print("Correct!")
else:
if totalnumber != guess:
print("Incorrect!")
print("The highest number you could've made out of your roll is ", *totalnumber , sep="")
time.sleep(1)
return totalnumber
#main code
#rules
print("*" * 80)
print("Here are the rules!")
time.sleep(1)
print("-Players may take turns rolling a set number of dice.")
time.sleep(1)
print("-The aim of the game is to get the biggest number from your dice roll.")
print("*" * 80)
time.sleep(2)
#amount of dice players want to use
numOfDice = int(input("How many dice would you like to use? "))
#start of game
print("Player 1's turn:")
time.sleep(1)
p1 = turn(numOfDice)
print("*" * 80)
time.sleep(2)
print("Player 2's turn:")
time.sleep(1)
totalnumber = []
p2 = turn(numOfDice)
print("*" * 80)
#seeing who won the game (highest number made wins)
if p1 > p2:
print("Player 1 has won the game! Congrats!")
time.sleep(1)
elif p2 > p1:
print("Player 2 has won the game! Congrats!")
time.sleep(1)
else:
print("It's a tie! Try again.")
print("*" * 80)
#seeing if players want to play again
again = input("Do you want to play again? Press any key except from 'n' to continue. ")
if again[0].lower() == 'n':
play_again = False
#if players say "n" then this message pops up and the game ends
print("End of game. Thank you for playing!")
Thanks for reading :)
As I am a beginner who is in school. I do not really have much knowledge of how to fix something like this issue.
This is the line that is the problem.
print("The highest number you could've made out of your roll is ", *totalnumber , sep="")
The problem would be this line:
def turn(numOfDice):
roll = rollDice(numOfDice)
totalnumber.sort(reverse = True)
print(*totalnumber , sep="")
guess = int(input("What is the biggest number you can make?"))
if guess == totalnumber:
print("Correct!")
Here, totalnumber is a list, not an int. therefore, you can try to make the input similarly a list too. change:
guess = int(input("What is the biggest number you can make?"))
into:
guess = list(map(int, input("What is the biggest number you can make?")))
Which should fix the issue.
I am working on Rock, Paper, Scissors in Python 3. I need help trying to implement where the computer keeps track of the users choices so it can tell what the player favors and have an advantage over the player. I also have the computer choosing random using an integer but I need to make the players choice a lowercase 'r' 'p' 's' and a 'q' to quit so it can check for invalid entry and display message and ask again. I don't want to use integers for the player.
Here is what I have:
import os
import random
import time
#global variable
#0 is a placeholder and will not be used
choices = [0, 'rock', 'paper', 'scissors']
player_wins = 0
computer_wins = 0
tie_count = 0
round_number = 1
keep_playing = True
# sets cls() to clear screen
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# function to display stats
def stats():
print("Current Statistics:")
print("Player Wins: {}".format(player_wins))
print("Computer Wins: {}".format(computer_wins))
print("Tied Games: {}\n".format(tie_count))
# function to check outcome
def game_outcome(player, computer):
#this makes the variables global, else you'll get error
global player_wins, tie_count, computer_wins
if computer == player:
print("It's a tie!\n\n")
tie_count += 1 # incraments tie
# checks all possible win conditions for player. and if met, declares player a winner. If not, declares compute the winner.
elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
print("Player wins\n\n")
player_wins += 1 # incraments player's wins
else:
print("Computer wins!\n\n")
computer_wins += 1 # incraments computer's wins
# clears screen
cls()
print("Let's play Rock Paper Scissors!")
# 3-second time out before clearing and asking for input
time.sleep(3)
while keep_playing == True:
# make computer choice random from defined list. Only selects a range of 1-3 ignoring the "0" placeholder
# this is because the user selects a number, instead of typing the weapon, and that number pulls the weapon from the list
computer = random.choice(choices[1:4])
cls()
# prints starting of round and shows stats
print("+++++++++++++[Starting Round {}]+++++++++++++\n".format(round_number))
stats()
# ask for player input
player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
player = choices[int(player)]
cls()
print("\n\nThe player's choice: [{}]\n".format(player))
print("The computer's choice: [{}]\n\n".format(computer))
game_outcome(player, computer)
round_number += 1
# ask if player wants to play again. If not, stop
play_again = input('Would you like to play again [y/n]? ')
if play_again.lower() == 'n':
break
print("Thanks for playing!")
Try using a dictionary:
# put this with the imports at the top
import sys
# replace `choices` at the top
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
# get computer choice
# replaces `computer = random.choice(choices[1:4])`
computer = random.choice(['rock', 'paper', 'scissors'])
# ask for player input
# replace these two lines of code:
# player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
# player = choices[int(player)]
while True:
try:
player = choices[input("What is your choice?\n(r) Rock\n(p) Paper\n(s) Scissors?\n(q) to quit.\n\nEnter the letter before the weapon of choice: ")]
if player == 'quit':
sys.exit(0)
break
except KeyError:
print('Please try again.')