import random
print('Ви граєте у гру \'Камінь, ножниці, папір\' !')
choices = ['Камінь' , 'Папір' , 'Ножниці']
user_choice = input('Виберіть : Камінь, Ножниці або Папір : \nВаш вибір : ')
computer_choice = random.choice(choices)
print('Комп\'ютер вибрав : ' + computer_choice)
computer_score = 0
user_score = 0
game = False
while game == False:
if user_choice == 'Камінь' and computer_choice == 'Папір':
computer_score += 1
print('Ви програли !')
elif user_choice == 'Камінь' and computer_choice == 'Ножниці':
user_score += 1
print('Ви перемогли !')
elif user_choice == 'Папір' and computer_choice == 'Ножниці':
computer_score += 1
print('Ви програли !')
elif user_choice == 'Папір' and computer_choice == 'Камінь':
user_score += 1
print('Ви перемогли !')
elif user_choice == 'Ножниці' and computer_choice == 'Камінь':
computer_score += 1
print('Ви програли !')
elif user_choice == 'Ножниці' and computer_choice == 'Папір':
user_score += 1
print('Ви перемогли !')
elif user_choice == computer_choice:
print('Нічия !')
else:
print('Неправильне введення. Перевірте написання слова.')
break
print('Користувач : ' + str(user_score)+ ' |----| ' + 'Комп\'ютер : ' + str(computer_score))
So I have a problem, I just wrote whis program 'Rock Paper Scissors' (and I know its simple and you might even laugh at me, but Im just starting out) and I don`t know how to make it play few times. I run it choose one of the items and I get a score and program closes. how to loop it maybe ?
You can use the following structure (translated into English for others):
import random
choices = ['Rock' , 'Paper' , 'Scissors']
computer_score = 0
user_score = 0
game = True
while game:
user_choice = input('Choose : Rock, Scissors, or Paper : \nYour choice : ')
computer_choice = random.choice(choices)
print('Computer chose : ' + computer_choice)
if user_choice == 'Rock' and computer_choice == 'Paper':
computer_score += 1
print('You lost !')
elif user_choice == 'Rock' and computer_choice == 'Scissors':
user_score += 1
print('You won !')
# Other choices...
game = (input('Play again? (y/n)\n') == 'y')
print('User : ' + str(user_score)+ ' |----| ' + 'Computer : ' + str(computer_score))
game is now by default True which can change if the user decides they don't want to play and input n after a given game. They keep playing by inputting y instead. The user and computer choices are now moved inside the while loop (to have a set of choices per game). The score is cumulative and displays at the end, once the user decided not to play again (though that's just a matter of how you want your game to work).
Note that you need to remove the break statement from the while loop (assuming the indentation in the OP was wrong and the break was part of the while). The only components of your original code between the first if for choices and the check if user wants to keep on playing should be the other choices (including the else for an unknown choice).
I would probably use recursion, but you need to add a case when the recursion should top, otherwise you will eventually run out of memory.
def start() :
~~~~~~~~~~~ bla bla bla ~~~~~~
start()
start()
Related
I made rock paper scissors game with score counter. Although it works well, I realized that the code is too heavy.
import random
game = 3
userScore = 0
computerScore = 0
while game != 0:
print(f"game left : {game}")
user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
computer = random.choice(['r', 'p', 's'])
if user != computer:
if user == 'p' and computer == 'r' or user == 's' and computer == 'p' or user == 'r' and computer == 's':
userScore += 1
else:
computerScore += 1
else:
userScore += 0
computerScore += 0
print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")
game -= 1
if userScore > computerScore:
print("You Won")
elif computerScore > userScore:
print("You Lost")
else:
print("Drawn")
I am trying to clean up this code so that it is more readable and soft.
A few changes you can make to the main loop that make it a little simpler:
# use 'for' and 'range' to iterate over a sequence of numbers
for game in range(3, 0, -1):
print(f"game left : {game}")
user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
# an iterable of single-character strings can be swapped for a single string
computer = random.choice('rps')
if user != computer:
# use 'in' to concisely test a bunch of different possibilities
if user + computer in ('pr', 'sp', 'rs'):
userScore += 1
else:
computerScore += 1
# eliminate 'else' that doesn't do anything
print(f"you({userScore}) : {user} & computer({computerScore}) : {computer}\n")
import random
game = 3
userScore = 0
computerScore = 0
while game > 0:
print(f"game left : {game}")
user = input("'r' for rock, 'p' for paper and 's' for scissors : ")
computer = random.choice('rps')
if user in 'rps':
if user != computer:
if user + computer in ('pr', 'sp', 'rs'):
userScore += 1
else:
computerScore += 1
print(f"you({userScore}): {user} | computer({computerScore}): {computer}\n")
game -= 1
else:
print(f"'{user}' is not valid, try again")
if userScore > computerScore:
print("You Won")
elif computerScore > userScore:
print("You Lost")
else:
print("Drawn")
I am trying to create a little Rock paper scissors game as I am a beginner but I am having issues with my if and elif statements.
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def player_choice():
input('Rock, Paper or Scissors? ')
return player_choice
def computer_choice():
print(random.choice(options))
return computer_choice
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
while player_score or computer_score < 10:
player_choice()
computer_choice()
if player_choice == 'rock' and computer_choice == 'rock':
print('Tie')
elif player_choice == 'rock' and computer_choice == 'paper':
print('Computer wins')
computer_score = computer_score + 1
print(ps)
print(cs)
elif player_choice == 'rock' and computer_choice == 'scissors':
print('You win')
player_score = player_score + 1
print(ps)
print(cs)
It seems as though the entire if/ elif block is ignored and nothing prints or is incremented. No error pops up, it is just simply ignored.
There are a couple of problems with your code, and I am going to try and address all of them.
The first one has to do with the naming of your variables. You name your functions computer_choice and player_choice, and then check if they equal "rock" or other strings. This is only going to return False because computer_choice is a function, not a string. I would recommend changing the names of your functions to get_computer_choice() and get_player_choice()
Secondly, ps = print('player score: ', player_score). I don't know what you are trying to do there. ps will be None, because print() doesn't return anything.
Third, your functions return themselves.
def my_func():
return my_func
Will return a function. What you want to do for both of your choice functions is this:
def get_player_choice():
player_choice = input('Rock, Paper or Scissors? ')
return player_choice
def get_computer_choice():
computer_choice = random.choice(options) # Set computer_choice to computers choice
print(computer_choice)
return computer_choice
Fourth, under your while loop, you are calling the functions, but aren't doing anything with the returns. Change
while player_score or computer_score < 10:
player_choice()
computer_choice()
to
while player_score or computer_score < 10:
player_choice = get_player_choice()
computer_choice = get_computer_choice()
Finally, the if ... else statements need to be indented under the while loop, otherwise they never get executed.
Please check the 13th line of your code. I couldn't understand what ps = print(...) means.
There were several issues with your code.
def player_choice():
input('Rock, Paper or Scissors? ')
return player_choice
player_choice is not initialised. Input takes the user input, but the result is not stored anywhere.
def get_player_choice():
choice = input("Rock, Paper or Scissors? ")
return choice
Same procedure for computer_choice.
Then there is:
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
I assume you tried to construct a string containing the scores. I suggest
def print_score():
print('player score: ', player_score)
print('computer_score: ',computer_score)
instead. You can then call the function whenever you want to see the score.
And finally, the indent was not right for the if-else statements. It should have been in the while loop. Now it just asks the user for input and generates a choice for the computer in an endless loop.
Here are all changes I suggested combined:
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def get_player_choice():
player_choice= input('Rock, Paper or Scissors? ')
return player_choice
def get_computer_choice():
computer_choice = random.choice(options)
print(computer_choice)
return computer_choice
def print_score():
print('player score: ', player_score)
print('computer_score: ',computer_score)
while player_score < 10 and computer_score < 10:
player_choice = get_player_choice()
computer_choice = get_computer_choice()
if player_choice == 'rock' and computer_choice == 'rock':
print('Tie')
elif player_choice == 'rock' and computer_choice == 'paper':
print('Computer wins')
computer_score = computer_score + 1
print_score()
elif player_choice == 'rock' and computer_choice == 'scissors':
print('You win')
player_score = player_score + 1
print_score()
A few notes:
1. I changed the name of your functions to avoid a later error when calling them.
2. As suggested in another answers you must pass a variable to store the result from the functions.
3. It was missing indentation
4. Some of your conditions were not right. Such as the while condition: if ((player_score<10) or (computer_score < 10)), even if someone reaches the score of 10, the game will keep going. We don't want that, so it must be the and condition.
Here is the solution:
import random
player_score = 0
computer_score = 0
options = ['rock', 'paper', 'scissors']
def choice_player():
result_player = str((input('rock, paper or scissors? ')))
return (result_player)
def choice_computer():
result_computer = random.choice(options)
return (result_computer)
#---------------------------------------------
ps = print('player score: ', player_score)
cs = print('computer_score: ',computer_score)
while ((player_score<10) and (computer_score < 10)):
player_choice = choice_player()
computer_choice = choice_computer()
if ((player_choice == 'rock') and (computer_choice == 'rock')):
print('Tie')
elif ((player_choice == 'rock') and (computer_choice == 'paper')):
print('Computer wins')
computer_score = computer_score + 1
print('player score: ', player_score)
print('computer_score: ',computer_score)
elif ((player_choice == 'rock') and (computer_choice == 'scissors')):
print('You win')
player_score = player_score + 1
print('player score: ', player_score)
print('computer_score: ',computer_score)
I made the game rock, paper or scissors. I want to implement a game counter, but I can't figure out how to make it work. It is stopped at 1. I want to play more games and the counter to show me the numbers of played games.
import random
stop = False
while (not stop):
games_count = 0
you = input('Player 1: Please type your choice: rock, paper or scissors: ')
oponent = ['rock', 'paper', 'scissors']
choice = random.choice(oponent)
games_count += 1
print('the oponent choice is: ', choice)
if choice == you:
print('DRAW GAME')
elif choice == 'rock' and you == 'paper':
print('YOU LOST')
elif choice == 'rock' and you == 'scissors':
print('YOU WON')
elif choice == 'paper' and you == 'rock':
print('YOU WON')
elif choice == 'paper' and you == 'scissors':
print('YOU LOST')
elif choice == 'scissors' and you == 'rock':
print('YOU LOST')
elif choice == 'scissors' and you == 'paper':
print('YOU WON')
else:
print('Wrong answer, please type rock, paper or scissors in your next attempt!')
answer = input('Do you want to start a new game? (y for yes, any for no): ')
if answer == 'y':
print('New game will start')
print('jocuri terminate: ',games_count)
elif answer == 'no':
stop = True
print('GAME OVER')
else:
print('Wrong answer, please type Yes or No in your next attempt!')
stop = True
Your counter is reinitialized to 0 at each iteration because it is inside your loop.
while not stop:
games_count = 0
...
Instead, initialize it outside the loop.
games_count = 0
while not stop:
...
As a sidenote, you might want to look to other implementations of rock-paper-scissor that do not rely on a big list of if-statement.
I have just begin to learn to program with Python and I try to make a rock-paper-scissor game to train myself.
I have a problem at the end of the the code with the while loop
It doesn't take account of my computer_score so if I have to create a variable and add an argument to not finish with an infinite loop
user_choice = "Rock"
user_score = 0
computer_score = 0
def fight(user_choice):
if user_choice == "Rock":
scissor = 1
rock = 2
paper = 3
user_choice = rock
computer_choice = randint(1, 3)
print computer_choice
if user_choice == computer_choice:
print 'DRAW!'
elif user_choice > computer_choice:
print 'User win, consciousness can\'t be beaten, you win'
global user_score
user_score += 1
elif user_choice < computer_choice:
print 'Computer win, singularity has been reach'
global computer_score
computer_score += 1
i = 0
while (computer_score < 3 or i < 30):
fight(user_choice)
i = i + 1
There may be the case that randint(1, 3) always returns 1. So computer never wins. This way your while loop continues infinitely.
I am working on a rock paper scissors game. Everything seems to be working well except the win/loss/tie counter. I have looked at some of the other games people have posted on here and I still cannot get mine to work. I feel like I am soooooo close but I just can't get it! thanks for any help guys. this is my first time posting in here so I am sorry if I messed up the formatting.
I edited the code but still cannot get the program to recognize the counter without using global variables. at one point of my editing I managed to get it to count everything as a tie... i dont know how and I lost it somewhere along my editing. lol. -thanks again everyone!
here is what I get when I run the program:
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 1
Computer chose PAPER .
You chose ROCK .
You lose!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 2
Computer chose PAPER .
You chose PAPER .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. y
Prepare to battle in a game of paper, rock, scissors!
Please input the correct number according
to the object you want to choose.
Select rock(1), paper(2), or scissors(3): 3
Computer chose SCISSORS .
You chose SCISSORS .
It's a tie!
Play again? Enter 'y' for yes or 'n' for no. n
Your total wins are 0 .
Your total losses are 0 .
Your total ties are 0 .
#import the library function "random" so that you can use it for computer
#choice
import random
#define main
def main():
#assign win, lose, and tie to zero for tallying
win = 0
lose = 0
tie = 0
#control loop with 'y' variable
play_again = 'y'
#start the game
while play_again == 'y':
#make a welcome message and give directions
print('Prepare to battle in a game of paper, rock, scissors!')
print('Please input the correct number according')
print('to the object you want to choose.')
#Get the player and computers choices and
#assign them to variables
computer_choice = get_computer_choice()
player_choice = get_player_choice()
#print choices
print('Computer chose', computer_choice, '.')
print('You chose', player_choice, '.')
#determine who won
winner_result(computer_choice, player_choice)
#ask the user if they want to play again
play_again = input("Play again? Enter 'y' for yes or 'n' for no. ")
#print results
print('Your total wins are', win, '.')
print('Your total losses are', lose, '.')
print('Your total ties are', tie, '.')
#define computer choice
def get_computer_choice():
#use imported random function from library
choice = random.randint(1,3)
#assign what the computer chose to rock, paper, or scissors
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#define player choice
def get_player_choice():
#assign input to variable by prompting user
choice = int(input("Select rock(1), paper(2), or scissors(3): "))
#Detect invalid entry
while choice != 1 and choice != 2 and choice != 3:
print('The valid numbers are rock(type in 1), paper(type in 2),')
print('or scissors(type in 3).')
choice = int(input('Enter a valid number please: '))
#assign what the player chose based on entry
if choice == 1:
choice = 'ROCK'
elif choice == 2:
choice = 'PAPER'
else:
choice = 'SCISSORS'
#return value
return choice
#determine the winner from the variables
def winner_result(computer_choice, player_choice):
#if its a tie, add 1 to tie variable and display message
if computer_choice == player_choice:
result = 'tie'
print("It's a tie!")
#if its a win, add to win tally and display message
elif computer_choice == 'SCISSORS' and player_choice == 'ROCK':
result = 'win'
print('ROCK crushes SCISSORS! You win!')
elif computer_choice == 'PAPER' and player_choice == 'SCISSORS':
result = 'win'
print('SCISSORS cut PAPER! You win!')
elif computer_choice == 'ROCK' and player_choice == 'PAPER':
result = 'win'
print('PAPER covers ROCK! You win!')
#if it does not match any of the win criteria then add 1 to lose and
#display lose message
else:
result = 'lose'
print('You lose!')
def result(winner_result,player_choice, computer_choice):
# accumulate the appropriate winner of game total
if result == 'win':
win += 1
elif result == 'lose':
lose += 1
else:
tie += 1
return result
main()
Your winner_result function returns before it increments the win counters. If you remove all the return statements from it, the counters should be updated. The return statements aren't needed anyway because the if/elif/else structure ensures that only one of the possible outcomes will be executed.
As Junuxx says in a comment, you also need to assign values to the winner_result variable properly, i.e. winner_result = 'win' instead of winner_result == 'win'. I'd also rename the winner_result variable or the function, because it's confusing to have both use the same name.
And the win/lose/tie variables are currently local, which means that main and winner_result will have their own copies of these variables, so main's values will always be zero. What you can do is make them global variables: Assign them to zero in the global scope (outside any function), and add the line global win, lose, tie inside the function winner_result.
Obviously been a few years since this question was answered but it came up while I was looking the same info. Here's my code if anyone is interested.
#! usr/bin/python3
import random
def game():
computer_count = 0
user_count = 0
while True:
base_choice = ['scissors', 'paper', 'rock']
computer_choice = random.choice(base_choice)
user_choice = input('(scissors, paper, rock) Type your choice: ').strip().lower()
print()
computer_wins = 'The computer wins!'
you_win = 'You win!'
print(f'You played {user_choice}, the computer played {computer_choice}')
if user_choice == 'scissors' and computer_choice == 'rock' or \
user_choice == 'paper' and computer_choice == 'scissors' or \
user_choice == 'rock' and computer_choice == 'paper':
print(computer_wins)
computer_count += 1
elif user_choice == 'rock' and computer_choice == 'scissors' or \
user_choice == 'scissors' and computer_choice == 'paper' or \
user_choice == 'paper' and computer_choice == 'rock':
print(you_win)
user_count += 1
else:
if user_choice == computer_choice:
print('Its a draw!')
computer_count += 1
user_count += 1
print(f'Computer: {computer_count} - You: {user_count}')
print()
game()
I was trying to do the same project, and I have found a solution that works well for me.
from random import randint
win_count = 0
lose_count = 0
tie_count = 0
# create a list of play options
t = ["Rock", "Paper", "Scissors"]
# assign a random play to the computer
computer = t[randint(0, 2)]
# set player to false
player = False
print()
print("To stop playing type stop at any time.")
print()
while player == False:
# set player to True
player = input("Rock, Paper or Scissors? ")
if player.lower() == "stop":
print()
print(
f"Thanks for playing! Your final record was {win_count}-{lose_count}-{tie_count}")
print()
break
if player.title() == computer:
print()
print("Tie!")
tie_count += 1
print()
elif player.title() == "Rock":
if computer == "Paper":
print()
print(f"You lose. {computer} covers {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} smashes {computer}.")
win_count += 1
print()
elif player.title() == "Paper":
if computer == "Scissors":
print()
print(f"You lose. {computer} cuts {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win!, {player.title()} covers {computer}.")
win_count += 1
print()
elif player.title() == ("Scissors"):
if computer == "Rock":
print()
print(f"You lose. {computer} smashes {player.title()}.")
lose_count += 1
print()
else:
print()
print(f"You win! {player.title()} cuts {computer}.")
win_count += 1
print()
else:
print()
print("Sorry, we couldn't understand that.")
print()
# player was set to True, but we want it to be false to continue loop
print(f"Your record is {win_count}-{lose_count}-{tie_count}")
print()
player = False
computer = t[randint(0, 2)]
This works (kinda)
there are many issues with the code at the top of the page.
Firstly, Scoring doesn't work.
Secondly, nothing is indented meaning that nothing inside of the other def functions will work.
Thirdly, The other def functions are referred to in the first def main statement which causes Python to show an invalid syntax due to Python not knowing the other functions as they were referred to before they were introduced to python.