Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
So I am trying to make a cowboy game (double 07) in python. I have the first elif statement working just fine but the other two aren't working. There are more to come but I want to sort the errors out so I don't continue doing them.
import sys
import os
import time
import random
import colorama
from colorama import Fore
import random
#cool typing effect
from sys import stdout as s
from time import sleep as j
def w(print):
for i in print:
j(.03)
s.write(i)
s.flush()
next = input()
def noinput(print):
for i in print:
j(.03)
s.write(i)
s.flush()
#main code for the game hub
def guess_the_number():
os.system('clear')
num = random.randint(1, 50)
guess = "none"
while guess != num:
guess = input(Fore.CYAN + "Choose a number: ")
guess = int(guess)
if guess == num:
w(Fore.GREEN + "You guessed the correct number!")
os.system('clear')
else:
w(Fore.RED + "Sorry try again")
print(Fore.WHITE + "------------")
if guess > num:
w("your number is too large")
os.system('clear')
else:
w("your number is too small")
os.system('clear')
def rock_paper_scissors():
os.system('clear')
user_action = input(Fore.BLUE + "Pick your item (rock, paper, scissors): ")
w(Fore.WHITE + "you chose: " + user_action)
computer_choice = ["scissors", "paper", "rock"]
computer_choice = random.choice(computer_choice)
w(Fore.WHITE + "computer chose: " + computer_choice)
if user_action == computer_choice:
w(Fore.BLUE + f"Both players chose {user_action} its a tie!")
elif user_action == "rock":
if computer_choice == "scissors":
w(Fore.GREEN + "Player wins! Rock destroys Scissors.")
else:
w(Fore.RED + "Paper covers Rock! Computer wins.")
elif user_action == "paper":
if computer_choice == "rock":
w(Fore.GREEN + "Player wins! Paper covers Rock.")
else:
w(Fore.RED + "Scissors cut Paper! Computer wins.")
elif user_action == "scissors":
if computer_choice == "paper":
w(Fore.GREEN + "Player wins! Scissors cut Paper.")
else:
w(Fore.RED + "Rock destroys Scissors! Computer wins.")
os.system('clear')
play_again = input(Fore.CYAN + "Play again? y/n: ")
if play_again == ("y"):
os.system('clear')
rock_paper_scissors()
else:
os.system('clear')
choices()
The error is in this game
def cowboy_game():
os.system('clear')
#----cowboy game code-------
user_action = input("pick your move: ")
os.system('clear')
computer_choice = ["shoot", "reload", "guard"]
computer_choice = random.choice(computer_choice)
w("player chose: " + str(user_action))
w("computer chose: " + str(computer_choice))
#random if statement so elif will work since python is retarded in that way
fgf = print("")
if fgf == ("f"):
print("")
elif user_action == "shoot":
if computer_choice == "shoot":
print(Fore.WHITE + "Both Players killed each other. ")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
It prints the statement above
elif user_action == "shoot":
if computer_choice == "reload":
print(Fore.WHITE + "Player killed enemy.")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
elif user_action == "shoot":
if computer_choice == "guard":
print(Fore.WHITE + "Enemy blocked the bullet. No damage.")
cowboy_game()
os.system('clear')
It doesn't print at all for those statments
w(Fore.WHITE + "Welcome to my game hub! Pick a number to start ")
os.system('clear')
print("----------")
def choices():
print(Fore.CYAN + "1) Rock Paper Scissors")
print(Fore.WHITE + "----------")
print(Fore.CYAN + "2) Guess the number")
print(Fore.WHITE + "----------")
print(Fore.CYAN + "3) Cowboy game")
print(Fore.WHITE + "---------")
choices()
choice = input("Choice: ")
if choice == ('1'):
os.system('clear')
w("Everyone knows how to play this. Have fun!")
rock_paper_scissors()
if choice == ('2'):
os.system('clear')
w("Welcome to Guess the Number! Try and guess the number to play")
guess_the_number()
if choice == ('3'):
os.system('clear')
w("--(Welcome to cowboy! Instructions in the next line)--")
os.system('clear')
w("To shoot you need to reload first. choices: reload, guard, or shoot. What these do
are self explanatory lol")
w(Fore.CYAN + "press enter to start the game")
os.system('clear')
w(Fore.BLUE + "have fun! :)")
os.system('clear')
cowboy_game()
I cannot find anything online to help with this so I'm going to leave it up to the users on this site.
Your conditions for the Elif statements are the same.
try:
elif user_action == "shoot":
if computer_choice == "shoot":
print(Fore.WHITE + "Both Players killed each other. ")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
elif computer_choice == "reload":
print(Fore.WHITE + "Player killed enemy.")
time.sleep(0.5)
play_again = input("Play again? y/n: ")
if play_again == ("y"):
cowboy_game()
os.system('clear')
if play_again == ("n"):
choices()
os.system('clear')
elif computer_choice == "guard":
print(Fore.WHITE + "Enemy blocked the bullet. No damage.")
cowboy_game()
os.system('clear')
elif user_action == "reload":
(rest of your edge cases)
Related
WHile I was attempting a simple rock, paper scissors, I ran into this proble. When I execute the file and input the user_input, it says to me that the variable computer_choice doesn’t exist, even though it does exist. I would appreciate if someone could help me, thank you.
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
random_number = random.randint (0, 2)
computer_choice = options[random_number]
print ("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors" :
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper" :
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_pick == "rock" :
print("You Won!")
user_wins += 1
continue
else:
print("You Lost!")
computer_wins += 1
continue
print("You won", user_wins,"times and the computer won", computer_wins, "times.")
print("Goodbye")
You have to be careful with indentation when using python:
import random
user_wins = 0
computer_wins = 0
options = ["rock", "paper", "scissors"]
while True:
user_input = input("Type Rock/Paper/Scissors or Q to quit. ").lower()
if user_input == "q":
break
if user_input not in options:
continue
# not at this level
# at this level
random_number = random.randint(0, 2)
computer_choice = options[random_number]
print("The computer picked:", computer_choice + ".")
if user_input == "rock" and computer_choice == "scissors":
print("You Won!")
user_wins += 1
continue
elif user_input == "scissors" and computer_choice == "paper":
print("You Won!")
user_wins += 1
continue
elif user_input == "paper" and computer_choice == "rock": #not computer_pick
print("You Won!")
user_wins += 1
continue
Also you wrote computer_pick in line 31, probably you mean computer_choice
I'm trying to make "Rock, Paper, Scissors" as my second program. I keep encountering an error,
"Traceback (most recent call last):
File "/home/cabox/workspace/main.py", line 118, in <module>
File "/home/cabox/workspace/main.py", line 48, in Rock_Paper_Scissors
else:
NameError: name 'rps_choice' is not defined"
And here's the code.
import time
import random
def Rock_Paper_Scissors():
print("Welcome to the \"Rock, Paper, Scissors\" game!")
time.sleep(2)
def rps_input():
while True:
rps_choice = input("Say \"Rock\", \"Paper\", or \"Scissors\" to get started: ")
if rps_choice.upper() == "ROCK":
print("Great! You chose", rps_choice.upper(), end='')
print("! The computer picked...")
return rps_choice.upper()
if rps_choice.upper() == "PAPER":
print("Great! You chose", rps_choice.upper(), end='')
print("! The computer picked...")
return rps_choice.upper()
if rps_choice.upper() == "SCISSORS":
print("Great! You chose", rps_choice.upper(), end='')
print("! The computer picked...")
return rps_choice.upper()
else:
print("Sorry, please say \"Rock\", \"Paper\", or \"Scissors.\"")
time.sleep(2)
print("\n")
rps_input()
time.sleep(2)
rps_list = ["ROCK","PAPER","SCISSORS"]
rps_random = random.choice(rps_list)
print(rps_random, end='')
print("!")
time.sleep(2)
if rps_choice == rps_random:
print("You both picked the same. Please try again.")
rps_input()
else:
if rps_choice == "ROCK":
if rps_random == "PAPER":
print("The computer's paper beats your rock.")
time.sleep(2)
print("You LOSE.")
if rps_random == "SCISSORS":
print("Your rock beats the computer's scissors!")
time.sleep(2)
print("You WIN.")
if rps_choice == "PAPER":
if rps_random == "ROCK":
print("Your paper beats the computer's rock!")
time.sleep(2)
print("You WIN.")
if rps_random == "SCISSORS":
print("The computer's scissors beats your paper.")
time.sleep(2)
print("You LOSE.")
else:
if rps_random == "ROCK":
print("The computer's rock beats your scissors.")
time.sleep(2)
print("You LOSE.")
if rps_random == "PAPER":
print("Your scissors beat the computer's paper.")
time.sleep(2)
print("You WIN.")
time.sleep(2)
def RPS_Reset_Quit():
rq = input("Restart or quit? (R/Q): ")
if rq.lower() == "r":
print("\n")
Rock_Paper_Scissors()
if rq.lower() == "q":
print("Quiting...")
time.sleep(2)
quit()
else:
print("Sorry, please say either R or Q.")
time.sleep(2)
RPS_Reset_Quit()
RPS_Reset_Quit()
Rock_Paper_Scissors()
As you can maybe see, my variable, rps_choice, is not defined, even though it was defined and returned from the rps_input() function. I really have no clue as to why this is happening.
You meant to capture the returned value in rps_choice:
rps_choice = rps_input()
Also, I see you have rps_input() called on two different lines. Both these lines will need updating.
Because you defined it inside the function rps_input() so it belongs only to that function. Imagine it as a hierarchy, the variables from downer scopes can access the variables from upper scopes but it doesn't go the other way.
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}")
I'm new to programming. I have written code for the rock paper scissors game but there is one bug that I can't seem to fix. When the game closes, the user is asked if he wants to play again. If the user answers yes the first time, then plays again then answers no the second time, the computer for some reason asks the user again if he wanted to play again. The user must enter no in this case. This is because although the user answers no, the answer gets reset to yes and goes over again. How can this be fixed?
# This code shall simulate a game of rock-paper-scissors.
from random import randint
from time import sleep
print "Welcome to the game of Rock, Paper, Scissors."
sleep(1)
def theGame():
playerNumber = 4
while playerNumber == 4:
computerPick = randint(0,2)
sleep(1)
playerChoice = raw_input("Pick Rock, Paper, or Scissors. Choose wisely.: ").lower()
sleep(1)
if playerChoice == "rock":
playerNumber = 0
elif playerChoice == "paper":
playerNumber = 1
elif playerChoice == "scissors":
playerNumber = 2
else:
playerNumber = 4
sleep(1)
print "You cookoo for coco puffs."
print "You picked " + playerChoice + "!"
sleep(1)
print "Computer is thinking..."
sleep(1)
if computerPick == 0:
print "The Computer chooses rock!"
elif computerPick == 1:
print "The Computer chooses paper!"
else:
print "The Computer chooses scissors!"
sleep(1)
if playerNumber == computerPick:
print "it's a tie!"
else:
if playerNumber < computerPick:
if playerNumber == 0 and computerPick == 2:
print "You win!"
else:
print "You lose!"
elif playerNumber > computerPick:
if playerNumber == 2 and computerPick == 0:
print "You lose!"
else:
print "You win!"
replay()
def replay():
sleep(1)
playAgain = "rerun"
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
elif playAgain == "no":
sleep(1)
print "Have a good day."
sleep(1)
print "Computer shutting down..."
sleep(1)
else:
sleep(1)
print "What you said was just not in the books man."
sleep(1)
theGame()
This is because of the way the call stack is created.
The First time you play and enter yes to play again, you are creating another function call to theGame(). Once that function call is done, your program will continue with the while loop and ask if they want to play again regardless if they entered no because that input was for the second call to theGame().
To fix it, add a break or set playAgain to no right after you call theGame() when they enter yes
while playAgain != "no":
playAgain = raw_input("Would you like to play again?: ").lower()
if playAgain == "yes":
sleep(1)
print "Alright then brotha."
sleep(1)
theGame()
break ## or playAgain = "no"
You should break out of the loop after calling theGame. Imagine you decided to play again 15 times. Then there are 15 replay loops on the stack, waiting to ask you if you want to play again. Since playAgain is "yes" in each of these loops, each is going to ask you again, since playAgain is not "no"
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!