while loop argument not take into account - python

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.

Related

How can I clean this code ? (rock paper scissors)

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")

Stuck inside the while loop

I was writing code for Rock Paper Scissors game in Python. This is kinda tournament style (3 rounds)
But it just keeps playing after the 3rd round is over.
def play():
player = input("Please type 'r' for Rock, 'p' for Paper and 's' Scissors: \n").lower()
while (player != 'r') and (player != 'p') and (player != 's'):
player = input("That is not an valid option. Please try again:\n").lower()
computer = random.choice(['r', 'p', 's'])
commands = {
"r" : "Rock",
"p" : "Paper",
"s" : "Scissors"
}
if player == computer:
print("It's a draw! Game Over.")
return("Draw")
elif user_win(player, computer):
print(f"You won! The computer used {commands[computer]} against your {commands[player]} and lost.")
return("Won")
print(f"You lost! The computer used {commands[computer]} against your {commands[player]} and won.")
return("Lost")
def user_win(player, computer):
# r > s, s > p and p > r
if (player == 'r' and computer == 's') or (player == 's' and computer == 'p') or (player == 'p' and computer == 'r'):
return True
print("Hello, Player! Choose your weapon.")
count, user, comp = 0, 0, 0
while count < 3:
count =+ 1
outcome = play()
if outcome == 'Won':
user =+ 1
elif outcome == 'Lost':
comp =+ 1
if user > comp:
print(f"You win. You: {user} Computer: {comp}")
elif comp > user:
print(f"You lost. You: {user} Computer: {comp}")
else:
print(f"Its a draw. You: {user} Computer: {comp}")
This is the full code. Below is the part which have problem (if i understood it right)
while count < 3:
count =+ 1
outcome = play()
if outcome == 'Won':
user =+ 1
elif outcome == 'Lost':
comp =+ 1
Ps: This is my first time posting on stackoverflow so sorry if i posted in wrong way.
The error is count =+ 1. Try count += 1, that should work.
(As a little background: count =+ 1 will simply assign a value of 1 to the variable count. After that, count never chnages, so it can never reach 3, and you're stuck in an infinite loop. The increment you want is count += 1.)
When you do
count =+1, it just assigns the value +1 to variable count, which is less than the required exit value of 3. You can try to log the value of count across iterations for a better understanding.
Fix:
Change the =+ to += for what I suppose is your requirement, ie to increment value by 1 on each iteration. Read through What is the difference between '+=' and '=+'?

Error in rock paper scissors game with Python

I'm trying to create a rock paper scissors game for a class assignment with Python, but I can't get the result out.
The game is supposed to start with the 1) user's input, 2) show what computer randomly chose, 3) the result (You win, You lose, or Tie with how you won or lost), 4) then ask if you want to Play again, and 5) finally escape.
I did succeed on the first 2 parts, but I can't figure out why 3, 4, 5 is not printing...
The result after showing what the computer played(2), it says 'None' then it loops back to (1) getting the input from the user.
Below is the code. Please advise me on how to fix them. Thank you so much!!
import random
while True :
player = input("Enter a number (0 for rock, 1 for paper, 2 for scissors) >>")
RPS = [0,1,2]
computer = random.choics(RPS)
RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
print("The computer played", RPC_dict.get(computer))
def game(player, computer):
RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
if player == computer:
print("Tie!")
elif player == 0:
if computer == 1:
print("You lose!", RPS_dict.get(computer), 'covers', RPS_dict.get(player))
else:
print("You win!", RPS_dict.get(player), 'cut', RPS_dict.get(computer))
elif player == 1:
if computer == 2:
print("You lose!", RPS_dict.get(computer), 'cut', RPS_dict.get(player))
else:
print("You win!", RPS_dict.get(player), 'covers', RPS_dict.get(computer))
game(player, computer)
print(game(player, computer))
again = input("Play again? 0 for no, 1 for yes\n")
Your function should be outside your while loop and you don't need to call it within a print statement...
import random
def game(player, computer):
if player == computer:
print('game tied')
else:
if (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2):
print('you win')
else:
print('computer wins')
def choice(x):
y = None
if x == 1:
y = 'rock'
elif x == 2:
y = 'paper'
elif x == 3:
y = 'scissors'
return y
playing = True
while playing == True:
player_input = int(input("Enter 1 for rock, 2 for paper, 3 for scissors"))
print('You chose:'+ choice(player_input))
computer_input = random.choice([1,2,3])
print('Computer chose:'+ choice(computer_input))
game(player_input, computer_input)
restart = int(input("Enter 1 to play again or 2 to quit"))
if restart == 2:
playing = False

how to loop rock paper scissors

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()

Python rock paper scissors score counter

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.

Categories

Resources