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.
Related
I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass
Trying to make a rock paper scissor game with a player versing the computer to refresh knowledge on coding however I can't seem to find what's causing the issue in my while loop. I have it set to finish when either the computer or person reaches a score of 3 but stops whenever the total scores equal 8. Full code is listed below
import random
rock = "rock"
paper = "paper"
scissors = "scissors"
humanscore = int(0)
compscore = int(0)
limit = int(3)
comp = ["paper", "rock", "scissors"]
while humanscore <= limit or compscore <= limit:
human = str(input("Choose rock, paper, or scissors, first to 3 wins! "))
answer = random.choice(comp)
if human == answer:
print("Tie, Computer chose, ", answer)
if answer == rock:
if human == paper:
humanscore += 1
print("You Win!")
elif human == scissors:
compscore += 1
print("Computer Won! Try again")
if answer == paper:
if human == rock:
compscore += 1
print("Computer Won! Try again")
elif human == scissors:
humanscore + 1
print("You Win!")
if answer == scissors:
if human == paper:
compscore += 1
print("Computer Won! Try again")
elif human == rock:
humanscore += 1
print("You Win!")
print("\n Computer Chose: ", answer, "computer score: ", compscore, "Human Score:", humanscore)
As already said in comments, the problem is with the or in your break condition. As long as one of the scores is below or equal 3, it keeps running.
For instance, if humanscore = 3 and comp score = 2, both parts of the condition are true meaning it continues.
As soon as humanscore = 4 and compscore = 4, both humanscore <= 3 and compscore <= 3 evaluate to false, meaning it stops => total score is 8.
Hence, the while should be like follows (also it should be < instead of <=, because you want to stop as soon as one has 3 points):
while humanscore < limit and compscore < limit:
Once you've sorted out the loop - which if you only want to keep going while the scores are both below limit is corrected as per schilli's answer - you might like to consider a data structure suggestion:
Make a dict that records what choice beats a given choice:
whatBeats = {rock:paper, paper:scissors, scissors:rock}
# then later after choices are made...
if answer == whatBeats[human]:
# computer win
elif human == whatBeats[answer]:
# human win
else:
# draw
(Many decades ago I wrote a sorting program before I had learned about any indexed structure - like arrays - and your current method puts me in mind of that sort of effort).
I am new to coding so I am trying to create a Rock Paper Scissors Game. I have almost completed the game, but when the user and computer input the same number, I want the program to repeat until either one of the player wins. How can I do this? Any help is appreciated. Here is my code.
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(input("You have one chance of beating me. Input a number. "))
print('')
import random
computer = random.randint(1,3)
if user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("Fine. Bye.")
You could put the whole if-elif-block in a while-loop that will repeat until you have a winner. In order to determine if there is a winner, use a boolean variable.
winner = False
while not winner:
if ...... ## Your if-elif-block
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
## Your remaining if-elif-block
You only put the command winner=True in the command blocks of the conditions that have a winner. So, the loop will continue until you hit one of these conditions.
You could also choose to use a more advanced winner variable (0 for draw, 1 for player, 2 for computer) to use the value in a goodbye-message.
One way would be to use a while loop, breaking when a condition is satisfied.
while True:
if (condition):
print("")
break
...
The while statement repeats the loop until one of the conditions is satisfied. The break statement causes the program to exit the loop and move on to the next executable statement.
(to learn more google anything in quotes :)
using a "while loop" to create a "game loop". I learned this trick from making small games in python. Also, you want to learn to use "classes" as the logic and the code can be improved using "OOP concepts".T code has been tested and works.
import random
#Create a "function" that meets the requirements of a "game loop"
def gameloop():
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
#Create a "while loop" to host the logic of the game.
#Each If statement will enable one "rule" of the game logic.
#game logic could be redesigned as an "Event".
#You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(
input("You have one chance of beating me. Input a number. "))
print('')
computer = random.randint(1, 3)
if user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
winner = True
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
elif user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("game....over?")
gameloop()
I took the time to do an OOP Class example too! it could be optimized in many ways. However, I hope it shows you the next level of study! I also hope it helps you look into all the crazy design patterns and Game Programming Techniques you can apply as you learn.
import random
# we can create a player class to be used as an "interface" as we design the games logic
# this will let us scale the features be build in our game
# in this case i will leave it to you to add Wins to the scoreboard to help you learn
class player:
# your games requerment wants your players to make a choice from 1-3
choice = 0
# your games may requerment a player to be defined as the winner
win = 0
# your games may requerment a player to be defined as the losser
loss = 0
class game:
# by using classes and OOP we can scale the data and logic of your game
# here we create instances of the class player and define new objects based on your "requerments"
# your "requerments" where to have one Computer as a player, and one user as a player
computer = player()
user = player()
# this "function" will create a Scoreboard feature that can be called in the 'game loop' or in a future "event" of the game.
# Like a "Game Stats stage" at the end of the game
def Scoreboard(self, computer, user):
Computer = computer.loss
User = user.loss
print("+============= FINAL RESULTS: SCOREBOARD!! ======+ ")
print(" ")
print("Computer losses: ", Computer)
print("Player losses: ", User)
print(" ")
# Create a "function" that meets the requirements of a "game loop"
def main_loop(self, computer, user):
gameinput = input("Want to play Rock Paper Scissors? (Y/N) ")
if gameinput == "Y":
# Create a "while loop" to host the logic of the game.
# Each If statement will enable one "rule" of the game logic.
# game logic could be redesigned as an "Event".
# You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
# we create 'Player1' as the user
Player1 = user
# we change the 'Player1' 'choice' to the user input
Player1.choice = int(
input("You have one chance of beating me. Input a number. "))
print('')
# we pull in to the game the computer player and call them 'Player1'
Player2 = computer
# we change the 'Player2' 'choice' to a random number
Player2.choice = random.randint(1, 3)
if user.choice == 1 and computer.choice == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
user.loss += 1
elif user.choice == 1 and computer.choice == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
computer.loss += 1
elif user.choice == 2 and computer.choice == 1:
print("You win! You played Paper and I played Rock!")
winner = True
computer.loss += 1
elif user.choice == 2 and computer.choice == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
user.loss += 1
elif user.choice == 3 and computer.choice == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
user.loss += 1
elif user.choice == 3 and computer.choice == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
computer.loss += 1
elif user.choice == 1 and computer.choice == 1:
print("Must play again! We both played Rock!")
elif user.choice == 2 and computer.choice == 2:
print("Must play again! We both played Paper!")
elif user.choice == 3 and computer.choice == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
# by returning "self" you call the same 'instances' of game that you will define below
return self.Scoreboard(user, computer)
else:
print("game....over?")
# define Instance of game as "test_game"
test_game = game()
# run game loop
test_game.main_loop()
I am attempting to make a basic rock, paper, scissors game. When I input either rock, paper, or scissors, I sometimes have to enter the same thing multiple times for it to continue to the if statements. See code below:
# Rock, Paper, Scissors
player_total = 0
computer_total = 0
def get_computer_hand():
choice = randint(1, 3)
if choice == 1:
return "scissors"
elif choice == 2:
return "paper"
else:
return "rock"
def ask_user():
global player_total
global computer_total
player = input("Enter your hand (stop to stop): ")
if player == "stop":
print("Computer had ", computer_total, "points, you had ", player_total, " points.")
exit(0)
computer = get_computer_hand()
if player == "rock":
if computer == "paper":
return "win"
elif computer == "scissors":
return "lose"
else:
return "tie"
elif player == "paper":
if computer == "paper":
return "tie"
elif computer == "scissors":
return "lose"
else:
return "win"
elif player == "scissors":
if computer == "scissors":
return "tie"
elif computer == "paper":
return "win"
else:
return "lose"
def count_winner():
global player_total
global computer_total
player_total = 0
computer_total = 0
while True:
outcome = ask_user()
if outcome == "win":
print("You won that one.")
player_total += 1
elif outcome == "lose":
print("Computer won that one.")
computer_total += 1
count_winner()
I expect it to work the first time and to continue as usual, but I can't seem to figure out why it just asks "Enter your hand (stop to stop): " instead sometimes when I enter either rock, paper, or scissors.
This is happening because there is a tie happening between the computer and the user. This could be fixed by adding the end with the code of
else outcome == "tie":
print("You have tied with the Computer!")
computer_total += 1
player_total += 1
This would add a point to both sides and if you don't want that just delete the last two lines of my code
Need help on stopping the score from resetting every game,
this is my code so far and its not working.
This is part of a function that checks who's the winner etc.
def winner ():
global Win
if alist [0] == player1 and alist[1] == player1 and alist[2] ==player1:#top line horizontal
Win = 'player1'
return True
elif alist[3] == player1 and alist[4] == player1 and alist[5] ==player1:#middleline horizontal
Win = 'player1'
return True
this statement determines the score and whether to start another game.
if winner():
if Win == 'player1':
print("player1 is winner")
p1score = p1score+1
elif Win == 'player2':
print("player2 is winner")
p2score = p2score+1
print('Player1s score =', p1score,'Player2s score =', p2score)
print("Would you like to play again(yes or no)")
restart = input("")
if restart == 'yes':
return gamemode()
Ok so at the end of the game the score displays correctly, but when another game is played it resets?
def playervscomputer():
global Player1Score
Player1Score = 0
global ComputerScore
ComputerScore = 0
players = [name, 'computer']
global turn
turn = random.randint(0,1)
while True:
print('its\s %s\'s turn' % players[turn])
if winner1():
#Check if people have won
if Win == 'player1':
print("player1 is winner")
Player1Score = Player1Score+1
print("player1s score is", Player1Score, 'Computer Score=', ComputerScore)
print("would you like to play again?(yes or no)")
restart = input("")
if restart =='yes':
return main()
else:
print("Thanks for playing")
elif Win == 'Computer':
print("Computer is winner")
ComputerScore = ComputerScore+1
print('Player1s score =', Player1Score,'Computers score =', ComputerScore)
Any ideas or any help on it keeping the scores after a few games have been played.
Thanks
Looks like you're not fully understanding scope. Try changing p1score and p2score to global variables (like you did with Win).
This YouTube video helped me understand the difference between global and local variables, maybe it will help you.
https://www.youtube.com/watch?v=A054Ged9suI
A simple programm, that uses a function to increment two independent variables (in a list):
score = [0,0]
def increment(Player):
global score
if Player == 1:
score[0]+=1
elif Player ==2:
score[1]+=1
else:
print('Input not defined')
def main():
global score
print(score)
increment(1)
increment(2)
increment(2)
print(score)