my rock paper scissors gives me nothing in output (python) - python

I am new to python and as a practice I'm trying to write a rock paper scissors with it.
I triple checked eth but i can't find the problem.
I'm using visual studio code console. the msvcrt is for "getch" and I'm not sure about about the random function syntax
problem: when you give it the input number, It doesn't do or write anything despite the program.
help me pleaaaaase.
import random
import msvcrt
##################################################
player_move = " "
system_move = " "
##################################################
def rand(system_move):
rn = random.randint(1, 3)
if rn == 1:
system_move = "Rock"
elif rn == 2:
system_move = "Paper"
elif rn == 3:
system_move = "Scissors"
else:
rand()
return system_move
##################################################
print("!!! Rock, Paper, Scissors !!!\n\n\n")
###################################################
def playermove(player_move):
print("What do you want to go with?\n1-Rock\n2-paper\n3-scissors\n")
temp = msvcrt.getch()
if temp == '1' or 1:
player_move = 'Rock'
elif temp == '2' or 2:
player_move = 'Paper'
elif temp == '3' or 3:
player_move = 'Scissors'
else:
print(f"invalid input {player_move}. Try again\n")
playermove()
return player_move
###################################################
pm = ' '
sm = ' '
rand(sm)
playermove(pm)
if pm== 'Scissors':
if sm == "Scissors":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Rock":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nYou won!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Paper":
if sm == "Scissors":
print(f"System move: {sm}\nSystem won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Paper":
print(f"System move: {sm}\nIt's a tie!\n")
else:
print("Oops! Something went wrong.\n")
elif pm == "Rock":
if sm == "Scissors":
print(f"System move: {sm}\nYou won!\n")
elif sm == "Rock":
print(f"System move: {sm}\nIt's a tie!\n")
elif sm == "Paper":
print(f"System move: {sm}\nSystem won!\n")
else:
print("Oops! Something went wrong.\n")
print("Press any key to exit...")
xyz = msvcrt.getch()

Well, the reason your code doesn't work is because you are not assigning the return value of your functions to any variable. To fix your code you need to do the following:
sm = rand(sm)
pm = playermove(pm)
In Python, passing an immutable object like string means that you cannot make any changes to it. As you're not using the passed value, your function's signature should actually look like this.
def rand()
def playermove()
After you do this, you'll see there are other things you need to fix in your code.

Try this code. Just replace snake, water, gun by rock, paper, scissors.
print(" \t\t\t Welecome to Snake , Water , Gun game\n\n")
import random
attempts= 1
your_point=0
computer_point=0
while (attempts<=10):
lst=["snake","water","gun"]
ran=random.choice(lst)
print("what do you choose snake, water or gun")
inp=input()
if inp==ran:
print("tie")
print(f"you choosed {inp} and computer guess is {ran}")
print("No body gets point\n")
elif inp=="snake" and ran=="water":
your_point=your_point+1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You won this round")
print("you get 1 point\n")
elif inp=="water" and ran=="snake":
computer_point = computer_point + 1
print(f"you choosed {inp} and computer guess is {ran}")
print("The snake drank water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp=="water" and ran=="gun":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The gun sank in water\n")
print("You won this round")
print("you get 1 point\n")
elif inp == "gun" and ran == "water":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point = computer_point + 1
print("The gun sank in water\n")
print("You Lost this round")
print("computer gets 1 point\n")
elif inp == "gun" and ran == "snake":
print(f"you choosed {inp} and computer guess is {ran}")
your_point = your_point + 1
print("The snake was shoot and he died\n")
print("You Won this round")
print("you get 1 point\n")
elif inp == "snake" and ran == "gun":
print(f"you choosed {inp} and computer guess is {ran}")
computer_point=computer_point+1
print("The snake was shoot and he died\n")
print("You Lost this round")
print("computer gets 1 point\n")
else:
print("invalid")
print(10 - attempts, "no. of guesses left")
attempts = attempts + 1
if attempts>10:
print("game over")
if computer_point > your_point:
print("Computer wins and you loose")
if computer_point < your_point:
print("you win and computer loose")
print(f"your point is {your_point} and computer point is {computer_point}")

Related

Tricks and tips for beginners to shorten and simplify code

I am looking for ways to shorten and simplify my python code. Here is one example of one small rock/paper/scissors game I wrote earlier. The code kinda looks too long to me and I want to try to learn how to shorten my code.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
if game_limit == 5 and comp_wins > user_wins:
print("The game is over, YOU LOST!")
elif game_limit == 5 and comp_wins < user_wins:
print("The game is over, YOU WON!")
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "rock":
print("its a draw")
elif user_input == "rock" and comp_input == "paper":
print("You lose!")
comp_wins += 1
if user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "scissors" and comp_input == "scissors":
print("its a draw")
elif user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
if user_input == "paper" and comp_input == "rock":
print("You win")
user_wins += 1
elif user_input == "paper" and comp_input == "paper":
print("its a draw")
elif user_input == "paper" and comp_input == "scissors":
print("You lose!")
comp_wins += 1
Yes. You could simplify your logic by having compound and/or tests for the player and user. Following is a revised version of your code with some simplified logic.
import random
user_wins = 0
comp_wins = 0
game_limit = 0
options = ["rock","paper","scissors"]
print("Welcome to Rock Paper Scissors, This is a Best of 5")
while True:
if game_limit >= 5: # Tweak
if comp_wins > user_wins:
print("The game is over, YOU LOST!")
break
if comp_wins < user_wins:
print("The game is over, YOU WON!")
break
else:
print("We go to sudden death!")
user_input = input("Type in Rock/Paper/Scissors or Q to quit: ").lower()
if user_input == "q":
break
elif user_input not in options:
print("type in a valid word next time")
continue
game_limit += 1
random_number = random.randint(0,2)
comp_input = options[random_number]
print("Computer picked", comp_input)
if user_input == "rock" and comp_input == "scissors" or user_input == "paper" and comp_input == "rock" or user_input == "scissors" and comp_input == "paper":
print("You win")
user_wins += 1
elif user_input == "rock" and comp_input == "paper" or user_input == "paper" and comp_input == "scissors" or user_input == "scissors" and comp_input == "rock":
print("You lose!")
comp_wins += 1
else:
print("It's a draw")
This way all of the scenarios where the user can win are in one logical test and all of the scenarios where the computer can win are in another logical test. If neither test is true, then the default would have to be a draw.
Also, I tweaked game limit test because if the computer and user have the same score when the game limit is reached, the test result would be false and the game would then continue on and not stop. So there is a bit of additional code to handle a tie after five rounds.
Give that a try.

Always receive 'You Lose' message in RPS against computer

For my exercise, I have to get the computer to play against the user in RPS. However, after both the computer and I input our action, the user will always receive a 'You Lose'.
import random
def get_computer_move():
"""Deterministic 'random' move chooser"""
options = ['rock', 'paper', 'scissors']
return options[random.randint(0, 2)]
def game_result(move1, move2):
"""game_result *exactly* as defined in question one"""
options = ["rock", "paper", "scissors"]
if move1 == move2:
return 0
elif move1 == "paper" and move2 == "rock":
return 1
elif move1 == "rock" and move2 == "scissors":
return 1
elif move1 == "scissors" and move2 == "paper":
return 1
else:
return 2
def main():
"""Runs a single game of PSR"""
print("Let's Play Paper, Scissors, Rock!")
user1 = input("Player one move: ").lower()
computer1 = print("The computer plays " + get_computer_move())
game_result(computer1, user1)
if user1 == computer1:
return print("It's a draw")
elif user1 == "paper" and computer1 == "rock":
return print("You win")
elif user1 == "rock" and computer1 == "scissors":
return print("You win")
elif user1 == "scissors" and computer1 == "paper":
return print("You win")
else:
return print("You lose")
main()
Here is my code although it is quite messy.
What I want to happen is:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
It's a draw
But it will always come out as:
Let's Play Paper, Scissors, Rock!
Player one move: ROCK
The computer plays rock
You lose
Help would be appreciated.
print returns none, you want to save the computers move and then print that separately
computer1 = get_computer_move()
print("The computer plays", computer1)

How to loop in a function, and keep taking inputs in python

So I was making a simple rock paper scissors game, and I wanted to put it as a function. I also wanted it to loop 10 times before deciding if the user won or lost. But the code just doesn't work and keeps giving random errors.
#code for rock paper scissors
import random
l = ["rock","paper","scissors"]
def rps():
q = 0
wincount = 0
while q < 10:
w = random.choice(l)
x = input("Choose rock paper or scissors all lowercase: ")
if w == "rock":
if x == "rock":
print("It's a draw")
if x == "paper":
print("You lost :(")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "paper":
if x == "rock":
print("You lost :(")
if x == "paper":
print("It's a draw")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "scissors":
if x == "rock":
print("You win!")
wincount += 1
if x == "paper":
print("You lost :(")
if x == "scissors":
print("It's a draw")
q += 1
if wincount >= 5:
print("You won the game!")
The error is
PS D:\project percy> & C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe "d:/project percy/cogs/asiufysduifhi.py"
PS D:\project percy> rps()
At line:1 char:5
+ rps()
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordE
xception
+ FullyQualifiedErrorId : ExpectedExpression```
The error seems not because of python. It should be because of Powershell.
PowerShell needs the ampersand to interpret the string as a filename.
As you are already using ampersand so not sure but try to run your command within proper quotes.
Like
& "C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe" "d:/project percy/cogs/asiufysduifhi.py"
Or if above wont works then give a try to this:
& "C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe" d:/project percy/cogs/asiufysduifhi.py
As others have said already, he error does not come from python but rather from powershell. I don't have windows to test but I think the problem is that you are trying to call rps() which is a python function, from the powershell prompt:
PS D:\project percy> & C:/Users/Dell/AppData/Local/Programs/Python/Python39/python.exe "d:/project percy/cogs/asiufysduifhi.py"
Call your python file that defines the function BUT NEVER CALLS IT
PS D:\project percy> rps()
Try to execute a powershell command named rps, which might exist but should be called differently.
Proposed solution
Try to add rps() at the end of your python file:
def rps():
.....
if wincount >= 5:
print("You won the game!")
rps()
The problem is you forgot to pass the list to the function as well as calling the function.
try this:
# code for rock paper scissors
import random
l = ["rock", "paper", "scissors"]
def rps(l):
q = 1
wincount = 0
while q < 11:
w = random.choice(l)
print()
print(q, "time")
x = input(f" Choose rock paper or scissors all lowercase: ")
if w == "rock":
if x == "rock":
print("It's a draw")
if x == "paper":
print("You lost :")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "paper":
if x == "rock":
print("You lost :")
if x == "paper":
print("It's a draw")
if x == "scissors":
print("You win!")
wincount += 1
elif w == "scissors":
if x == "rock":
print("You win!")
wincount += 1
if x == "paper":
print("You lost :")
if x == "scissors":
print("It's a draw")
q += 1
if wincount >= 5:
print("You won the game!")
calling = rps(l)

My input sometimes takes multiple times for it to go in the if statements

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

How to create a Rock, Paper, Scissors program

I'm very new to python and am taking an online class. I'm not very familiar with many functions in python so if you could keep it somewhat basic for me to keep track of, I would really appreciate it. I am trying to make a program that runs Rock, Paper, Scissors with a user but the num_games is not being accepted in the "for i in range". Also, I have run it and found that Scissors can beat Rock (THIS IS ANARCHY!). Can anyone assist me? Thanks in advance!
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1:
return "Rock!"
elif comp_move == 2:
return "Paper!"
else:
return "Scissors!"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print "You are going to play " + str(num_games) + " games! Here we go!"
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print "The computer went with: " + cpu_turn
if user_move == 'Rock' and cpu_turn == 'Scissors':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print "You won! Nice job!"
num_wins +=1
elif user_move == cpu_turn:
print "Oh! You tied"
else:
print "Whoops! You lost!"
return num_wins
print main()
This should be what you want:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper': print("You won! Nice job!"); num_wins +=1
elif user_move == cpu_turn: print("Oh! You tied")
else: print("Whoops! You lost!");
return num_wins
print(main())
Or even Better:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
winning=[('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')]
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if (user_move,cpu_turn) in winning:
print('You won!')
num_wins+=1
elif user_move == cpu_turn:
print('Same')
else:
print('You lost!')
return num_wins
print(main())
And another option that's also good:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
d={}.fromkeys([('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')],'You Won')
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if not user_move == cpu_turn:
print(d.get((user_move,cpu_turn),'You lost!'))
else:
print('Same')
return num_wins
print(main())
Here's what you want:
import random
outcome = random.choice(['Rock', 'Paper', 'Scissors'])
print(outcome)
Have you tried removing the '!' in the comp_turn function? It seems like cpu_turn variable will contain either 'Rock!', 'Scissors!' or 'Paper!' while your if-else condition is looking for either 'Rock', 'Scissors' or 'Paper' without the '!'. So, no matter what the player or cpu chooses, it will go into 'else' in the 'for' loop and the player loses.
This is the edited code:
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1: return "Rock"
elif comp_move == 2: return "Paper"
else: return "Scissors"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print("You won! Nice job!")
num_wins +=1
elif user_move == cpu_turn:
print("Oh! You tied")
else: print("Whoops! You lost!")
return num_wins
print(main())
Do note that the player's input is case sensitive too. Hope this helps!

Categories