Rock paper scissors menu error - python

Here is code I have so far whenever the menu appears and I press 1 for start a new game it says wrong choice try again.
import random
import pickle
class GameStatus():
def __init__(self, name):
self.tie = 0
self.playerWon = 0
self.pcWon = 0
self.name = name
def get_round(self):
return self.tie + self.playerWon + self.pcWon + 1
# Displays program information, starts main play loop
def main():
print("Welcome to a game of Rock, Paper, Scissors!")
print("What would you like to choose?")
print("")
game_status = welcomemenu()
while True:
play(game_status)
endGameSelect(game_status)
def welcomemenu():
while True:
print("[1]: Start New Game")
print("[2]: Load Game")
print("[3]: Quit")
print("")
menuselect = input("Enter your choice: ")
if menuselect in [1, 2, 3]:
break
else:
print("Wrong choice. select again.")
if menuselect == 1:
name = input("What is your name?: ")
print("Hello %s.") % name
print("Let's play!")
game_status = GameStatus(name)
elif menuselect == 2:
while True:
name = input("What is your name?: ")
try:
player_file = open('%s.rsp' % name, 'r')
except IOError:
print("Sorry there is no game found with name %s") % name
continue
break
print("Welcome back %s.") % name
print("Let's play!")
game_status = pickle.load(player_file)
displayScoreBoard(game_status)
player_file.close()
elif menuselect == 3:
print("Bye!!!")
exit()
return
return game_status
def play(game_status):
playerChoice = int(playerMenu())
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome, game_status)
def playerMenu():
print("Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors\n")
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect)
menuSelect = input("Enter a correct value: ")
return menuSelect
def validateInput(menuSelection):
if menuSelection in [1, 2, 3]:
return True
else:
return False
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# Calculate ties,wins,lose
def evaluateGame(playerChoice, pcChoice):
rsp = ['rock', 'paper', 'scissors']
win_statement = ['Rock breaks scissors', 'Paper covers rock', 'Scissors cut paper']
win_status = (playerChoice - pcChoice) % 3
print("You have chosen %s") % rsp[playerChoice - 1]
what_to_say =("Computer has chose %s") % rsp[pcChoice - 1]
if win_status == 0:
what_to_say +=(" as Well. TIE!")
elif win_status == 1:
what_to_say +=(". %s. You WIN!") % win_statement[playerChoice - 1]
else:
what_to_say +=(". %s. You LOSE!") % win_statement[pcChoice - 1]
print("what_to_say")
return win_status
# Update track of ties, player wins, and computer wins
def updateScoreBoard(outcome, game_status):
if outcome == 0:
game_status.tie += 1
elif outcome == 1:
game_status.playerWon += 1
else:
game_status.pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print(menuSelect,("is not a valid option. Please select 1-3"))
# Print the scores before terminating the program.
def displayScoreBoard(game_status):
print("")
print("Statistics:")
print(("Ties: %d") % game_status.tie)
print(("Player Wins: %d") % game_status.playerWon)
print(("Computer Wins: %d") % game_status.pcWon)
if game_status.pcWon > 0:
print("Win/Loss Ratio: %f") % (float(game_status.playerWon) / game_status.pcWon)
else:
print("Win/Loss Ratio: Always Win.")
print("Rounds: %d") % game_status.get_round()
def endGameSelect(game_status):
print("")
print("[1]: Play again")
print("[2]: Show Statistics")
print("[3]: Save Game")
print("[4]: Quit")
print("")
while True:
menuselect = input("Enter your choice: ")
if menuselect in [1, 2, 3, 4]:
break
else:
print("Wrong input.")
if menuselect == 2:
displayScoreBoard(game_status)
endGameSelect(game_status)
elif menuselect == 3:
f = open("%s.rsp" % game_status.name, 'w')
pickle.dump(game_status, f)
f.close()
print("Your game is saved successfully.")
endGameSelect(game_status)
elif menuselect == 4:
print("Bye!!!")
exit()
main()

When you use input(), you get a string rather than an int.
You should change:
menuselect = input("Enter your choice: ")
to this:
menuselect = int(input("Enter your choice: "))
To get it as an integer, that way it will work with the rest of your script.

Related

New to python and having problems with whiles and ifs

My Problem(s):
The problem now is that whenever I enter a number of times to play, it just ignores it and plays forever. It is also not updating the score even though I have global variables and I am adding to them every time there is a win or loss.
Also, I do not want to ask the player(s) for their names every time they play (only when using the "out of a certain number of points function of the game). Any suggestions/help would be greatly appreciated!
My code is below for reference:
from random import randint
import sys
print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
bestOutOf = int(input("Best out of: (Enter a number 1-10) "))
player1score = 0
player2score = 0
computerscore = 0
class PlayWithFriend:
def __init__(self, player1, player2, name1, name2, player1score, player2score):
self.player1 = player1
self.player2 = player2
self.name1 = name1
self.name2 = name2
self.player1score = player1score
self.player2score = player2score
if player1 == player2:
print("Tie!")
elif player1 == "Rock":
if player2 == "Paper":
print("You Win", name2,"!")
print(player2, "covers", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "smashes", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Paper":
if player2 == "Scissors":
print("You Win", name2,"!")
print(player2, "cut", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "covers", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Scissors":
if player2 == "Rock":
print("You Win", name2,"!")
print(player2, "smashes", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "cut", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("That's not a valid play. Check your spelling!")
class PlayWithComputer:
def __init__(self, player, name, player1score, computerscore):
self.player = player
self.player1score = player1score
self.computerscore = computerscore
self.name = name
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0,2)]
if player == computer:
print("Tie!")
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "smashes", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "covers", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "cut", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("That's not a valid play. Check your spelling!")
if dotheywantotplay == "y":
PlayWith = input("Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ")
while PlayWith in ('computer', 'friend', 'exit'):
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
while player1score + player2score < bestOutOf:
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
elif PlayWith == "computer":
player = input('Enter first players name: ')
while player1score + computerscore < bestOutOf:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
elif PlayWith == "exit":
sys.exit()
else:
print("That's not a valid play. Check your spelling!")
else:
print("I am sad now :-(")
sys.exit()
I went over your code and cleaned it up. I made the formatting, variable names, and processes much more pythonic. You will find it is much easier to use python when you use these best practices, so I recommend you at least look over the code and see what I did. For me, I know this would've been helpful when I started learning python.
from random import choice
def get_result(choice1, choice2):
return {
('paper', 'rock'): dict(win='player 1', action='covers'),
('rock', 'paper'): dict(win='player 2', action='covers'),
('rock', 'scissors'): dict(win='player 1', action='smashes'),
('scissors', 'rock'): dict(win='player 2', action='smashes'),
('scissors', 'paper'): dict(win='player 1', action='cuts'),
('paper', 'scissors'): dict(win='player 2', action='cuts'),
}[(choice1, choice2)] # index this dictionary
def main():
print('Lets play a game!')
if input('Do you want to play Rock-Paper-Scissors? (y or n) ') != 'y':
quit()
num_games = int(input('Best out of: (Enter a number 1-10) '))
num_games = max(min(num_games, 10), 1) # clamp num_games between 1-10
while True: # infinite loop, we can break out or quit when we need
inp = input('Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ')
if inp == 'exit':
quit()
play_with_computer = inp == 'computer'
name1 = input('Enter first players name: ')
name2 = 'computer' if play_with_computer else input('Enter second players name: ')
score = {name1: 0, name2: 0}
for game_number in range(num_games):
choice1 = input(f'{name1}... rock, paper or scissors? ')
choice2 = choice(['rock', 'paper', 'scissors']) if play_with_computer else input(f'{name2}... rock, paper or scissors? ')
if choice1 == choice2:
print('Tie!')
continue
result = get_result(choice1, choice2)
win_name = name1 if result['win'] == 'player 1' else name2
lose_name = name2 if result['win'] == 'player 1' else name1
score[win_name] += 1
print(f'{win_name} {result["action"]} {lose_name}')
print(f'Game {game_number+1}, the score is {score[name1]} {name1}, {score[name2]} {name2}')
print(name1 if score[name1] > score[name2] else name2, 'wins!')
if __name__ == '__main__': # this just means if the file is run
main()
The main thing I did was get rid of your rock paper scissors logic, (which you repeated twice which is never best practice in programming), and replaced it with a get_result function which returns the winner and action of the moves. I also replaced your if statements that test if the game is against the computer, with a bool play_with_computer. This can be used when getting player 2 name and the second choice, which is all that is really different when playing with a computer. The last thing is your game loop while. Since you never really need to execute any code after this (only reason to exit is to quit), I find it to be cleaner to have an infinite loop while True, and just call quit() if the input is 'exit'.
Okay so the mistake is:
while PlayWith != "computer" or "friend" or "exit":
try this thing:
while PlayWith != "computer" or PlayWith != "friend" or PlayWith != "exit":
And sorry if this does not work
which while loops and if statements are you having trouble with?
Upon first glance, the while statement below will never break the moment a player enters a value besides "computer", "friend" or "exit".
Instead, what you can do is put the process of the game within a function, that is continuously called back when the player enters a value besides the ones aforementioned.
while PlayWith != "computer" or "friend" or "exit":
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
i = 0
while i in range(0, bestOutOf):
if i >= bestOutOf:
sys.exit()
if bestOutOf >= 1 and bestOutOf <= 10:
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i += 1
else:
print("Setting default game to: \"best out of three\"")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i = bestOutOf - 3
if PlayWith == "computer":
i = 0
while i in range(0, bestOutOf - 1):
if i >= bestOutOf:
sys.exit()
else:
player = input('Enter first players name: ')
if bestOutOf >= 1 and bestOutOf <= 10:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
else:
personchoice = input("Rock, Paper, Scissors? ")
print("Setting default game to: \"best out of three\"")
PlayWithComputer(personchoice, player, player1score, computerscore)
if PlayWith == "exit":
sys.exit()
elif PlayWith != "exit" or "computer" or "friend":
print("That's not a valid play. Check your spelling!")

Checking If a File Exists and Loading its Contents

In my programming class we are to make a Rock, Paper, Scissors Game that can load previous saves of the game, display the statistics of the game, and allow the user to continue playing if desired. I have a good chunk of the program created, I just need help with the loading of the file as I just get an endless loop of "What is your name?". My code is below and any help would be appreciated!
#Rock, Paper, Scissors Program
#A menu-based RPS program that keeps stats of wins, losses, and
ties
#12/2/18
import sys, os, random, pickle
#Functions
def print_menu():
print("\n1. Start New Game")
print("2. Load Game")
print("3. Quit")
def print_roundmenu():
print("What would you like to do?")
print("\n1. Play Again")
print("2. View Statistics")
print("3. Quit")
def start_game(username, playing):
print("Hello", username + ".", "let's play!")
playAgain = play_game()
if playAgain == True:
playing = True
elif playAgain == False:
playing = False
return playing
def play_game():
roundNo = 1
wins = 0
losses = 0
ties = 0
playing_round = True
while playing_round:
print("Round number", roundNo)
print("1. Rock")
print("2. Paper")
print("3. Scissors")
roundNo += 1
choices = ["Rock", "Paper", "Scissors"]
play = get_choice()
comp_idx = random.randrange(0,2)
comp_play = choices[comp_idx]
print("You chose", play, "the computer chose",
comp_play+".")
if (play == comp_play):
print("It's a tie!")
ties += 1
print_roundmenu()
gameFile.write(str(ties))
elif (play == "Rock" and comp_play == "Scissors" or play == "Paper" and comp_play == "Rock" or play == "Scissors" and comp_play == "Paper"):
print("You win!")
wins += 1
print_roundmenu()
gameFile.write(str(wins))
elif (play == "Scissors" and comp_play == "Rock" or play == "Rock" and comp_play == "Paper" or play == "Paper" and comp_play == "Scissors"):
print("You lose!")
losses += 1
print_roundmenu()
gameFile.write(str(losses))
response = ""
while response != 1 and response != 2 and response != 3:
try:
response = int(input("\nEnter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
continue
elif response == 2:
print(username, ", here are your game play statistics...")
print("Wins: ", wins)
print("Losses: ", losses)
print("Ties: ", ties)
print("Win/Loss Ratio: ", wins, "-", losses)
return False
elif response == 3:
return False
def get_choice():
play = ""
while play != 1 and play != 2 and play != 3:
try:
play = int(input("What will it be? "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if play == 1:
play = "Rock"
if play == 2:
play = "Paper"
if play == 3:
play = "Scissors"
return play
playing = True
print("Welcome to the Rock Paper Scissors Simulator")
print_menu()
response = ""
while playing:
while response != 1 and response != 2 and response != 3:
try:
response = int(input("Enter choice: "))
except ValueError:
print("Please enter either 1, 2, or 3.")
if response == 1:
username = input("What is your name? ")
gameFile = open(username + ".rps", "w+")
playing = start_game(username, playing)
elif response == 2:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
elif response ==3:
playing = False
This code block:
while response == 2:
username = input("What is your name? ")
try:
gameFile = open("username.rps", "wb+")
pickle.dump(username, gameFile)
except IOError:
print(username + ", your game could not be found.")
will repeat infinitely unless you set response to something other than 2. Notice here that all you're doing in this block is (1) asking for username, (2) opening the file, and (3) dumping the file contents with pickle. You're not actually starting the game, like you are in the if response == 1 block. So the same prompt keeps repeating infinitely.
A good thing to do in these situations is to manually step through your code by hand - "what did I do to get here, and what is happening as a result of that?"

How log my score best out of three and use different symbols for the players? Python

I'm making a 2-play Battleship game in python and have been struggling with this for a while now:
I apologise if the question is poorly worded but I was to know how I can make my game log the match score at the end of the three games with something like:
print('Match score is' + score + 'Player' + (whoever) + 'wins!)
I'm not entirely sure how to implement this myself I have a range for games in range(3), but I don't know how to log the final score.
Also, how can I change the symbol for player_two so that I am not using an 'X' for both players? I've tried changing the input_check() but I get more errors than I did before.
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
"lose": 0
}
player_two = {
"name": "Player 2",
"wins": 0,
"lose": 0
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
print("Find and sink the ship!")
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("START")
del board[:]
build_game_board(board)
show_board(board)
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
else:
return player_two
# Allows new game to start
def play_again():
global ship_points
answer = input("Would you like to play again? ")
if answer == "yes" or answer == "y":
ship_points = load_game(game_board)
else:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
show_board(game_board)
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for games in range(3):
for turns in range(6):
if player_turns(turns) == player_one:
# print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The game is a draw")
play_again()
if __name__ == "__main__":
main()
You can use style string formatting to print the log.
print('Match score is %d : %d(Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
For more information about string formatting, check this link.
To change the symbol for Player 2, you can change the following code.
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"

Python Error: ValueError: Non-integer arg 1 for randrange()

I'm getting the above error in my code. It's just a simple text-based game.
Here's the code:
import os
import sys
import random
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.attack = 10
self.gold = 0
self.potions = 0
class Goblin:
def __init__(self, name):
self.name = name
self.maxhealth = 50
self.health = self.maxhealth
self.attack = 5
self.goldgain = 10
GoblinIG = Goblin("Goblin")
class Zombie:
def __init__(self, name):
self.name = name
self.maxhealth = 70
self.health = self.maxhealth
self.attack = 7
self.goldgain = 15
ZombieIG = Zombie("Zombie")
def main():
#os.system("cls")
print("Welcome to my game!")
print("1) Start")
print("2) Load")
print("3) Exit")
option = input("-> ")
if option == "1":
start()
elif option == "2":
pass
elif option == "3":
pass
else:
main()
def start():
#os.system("cls")
print("Hello, what is your name?")
option = input("-> ")
global PlayerIG
PlayerIG = Player(option)
start1()
def start1():
#os.system("cls")
print("Name: %s" % PlayerIG.name)
print("Attack: %s" % PlayerIG.attack)
print("Gold: %i" % PlayerIG.gold)
print("Potions: %i" % PlayerIG.potions)
print("Health: %i/%i" % (PlayerIG.health, PlayerIG.maxhealth))
print("1) Fight")
print("2) Store")
print("3) Save")
print("4) Exit")
option = input("-> ")
if option == "1":
prefight()
elif option == "2":
store()
elif option == "3":
pass
elif option == "4":
sys.exit()
else:
start1()
def prefight():
global enemy
enemynum = random.randint(1,2)
if enemynum == 1:
enemy = GoblinIG
else:
enemy = ZombieIG
fight()
def fight():
print("%s vs %s" % (PlayerIG.name, enemy.name))
print("%s's Health: %s/%s %s Health: %i/%i" % (PlayerIG.name, PlayerIG.health, PlayerIG.maxhealth, enemy.name, enemy.health, enemy.maxhealth))
print("Potions Left: %s\n" % PlayerIG.potions)
print("1) Attack")
#Implement defend system
print("2) Drink Potion")
print("3) Run")
option = input()
if option == "1":
attack()
elif option == "2":
drinkPotion()
elif option == "3":
run()
else:
fight()
def attack():
global PlayerAttack
global EnemyAttack
PlayerAttack = random.randint(PlayerIG.attack / 2, PlayerIG.attack)
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if PlayerAttack == PlayerIG.attack / 2:
print("You missed!")
else:
enemy.health -= PlayerAttack
print("You dealt %i damage!" % PlayerAttack)
option = input(" ")
if enemy.health <= 0:
win()
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input("")
if PlayerIG.health <= 0:
dead()
else:
fight()
def drinkPotion():
if PlayerIG.potions == 0:
print("You don't have any potions!")
else:
PlayerIG.health += 50
if PlayerIG.health >= PlayerIG.maxhealth:
PlayerIG.health = PlayerIG.maxhealth
print("You drank a potion!")
option = input(" ")
fight()
def run():
runnum = random.randint(1,3)
if runnum == 3:
print("You have ran away!")
option = input(" ")
start1()
else:
print("You've failed to run away!")
option = input(" ")
EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
if EnemyAttack == enemy.attack/2:
print("The enemy missed!")
else:
PlayerIG.health -= EnemyAttack
print("The enemy dealt %i damage!" % EnemyAttack)
option = input(" ")
if PlayerIG.health <=0:
dead()
else:
fight()
def win():
enemy.health = enemy.maxhealth
PlayerIG.gold -= enemy.goldgain
print("You have defeated the %s!" % enemy.name)
print("You found %i gold!" % enemy.goldgain)
option = input(" ")
start1()
def dead():
print("You have died!")
option = input(" ")
def store():
pass
main()
I get the error in def run(), in the else: statement. The line that goes like: EnemyAttack = random.randint(enemy.attack / 2, enemy.attack)
Any ideas? Should I elaborate more on my issue? Thanks :)
Use EnemyAttack = random.randint(math.floor(enemy.attack / 2), enemy.attack), or use math.ceil() to round the result of enemy.attack / 2.
randrange() expects whole integers. The error is occurring because the result of enemy.attack / 2 isn't a whole number; it has decimal places whenever enemy.attack is odd. One option is to scale randrange() after it is calculated if you need decimal results.
For example: 0.5*randrange(2*(enemy.attack/2), 2*enemy.attack), which can be simplified into 0.5*randrange(enemy.attack, 2*enemy.attack)

Loop Problems Rock Paper Scissors Game

I am very new to programming.
I have to write a Rock Paper Scissors game for my Intro to Programming class. I have a great start but a few issues I don't know how to solve.
I need three different menus. The main menu should ask to 1. Start new game 2. Load game or 3. Quit. Choose 1 or 2 and you input your name then play begins. You are then asked to select 1. Rock 2. Paper 3. Scissors. My game works great but after choosing Rock paper scissors I want a NEW menu to pop up: What would you like to do? 1. Play Again 2. View Statistics 3. Quit. But I have no idea where to put this. I have tried a few different places but it just by passes it and asks for rock paper scissors again.
Then my second issue is, when user selects 1. State new game needs to ask for their name and use their name to save their games to a file. Then when user chooses 2. Load Game, their name will be used to find a file "name.rps" and load their stats to continue to play (stats, round number, name).
Any help is appreciated.
import random
import pickle
tie = 0
pcWon = 0
playerWon = 0
game_round = (tie + playerWon + pcWon) + 1
# Displays program information, starts main play loop
def main():
print("Welcome to a game of Rock, Paper, Scissors!")
print("What would you like to do?")
print ("")
welcomemenu()
playGame = True
while playGame:
playGame = play()
displayScoreBoard()
prompt = input("Press enter to exit")
def welcomemenu():
print ("[1]: Start New Game")
print ("[2]: Load Game")
print ("[3]: Quit")
print("")
menuselect = int(input("Enter choice: "))
print("")
if menuselect == 1:
name = input("What is your name? ")
print("Hello", name, ".")
print("Let's play!")
elif menuselect == 2:
name = input("What is your name? ")
print("Welcome back", name, ".")
print("Let's play!")
player_file = open('name.rps', 'wb')
pickle.dump(name, player_file)
player_file.close()
elif menuselect == 3:
exit()
return menuselect
# displays the menu for user, if input ==4, playGame in the calling function (main()) is False, terminating the program.
# Generate a random int 1-3, evaluate the user input with the computer input, update globals accordingly, returning True
# to playGame, resulting in the loop in the calling function (main()) to continue.
def play():
playerChoice = int(playerMenu())
if playerChoice == 4:
return 0
else:
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome)
return 1
# prints the menu, the player selects a menu item, the input is validated, if the input is valid, returned the input, if
# the input is not valid, continue to prompt for a valid input
# 1 - rock
# 2 - paper
# 3 - scissors
def playerMenu():
print("Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors")
print("")
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect)
menuSelect = input("Enter a correct value: ")
return menuSelect
# if the user doesn't input a 1-3 then return false, resulting in prompting the user for another value. If the value
# is valid, return True
# takes 1 argument
# menuSelection - value user entered prior
def validateInput(menuSelection):
if menuSelection == "1" or menuSelection == "2" or menuSelection == "3":
return True
else:
return False
# return a random integer 1-3 to determine pc selection
# 1 - rock
# 2 - paper
# 3 - scissors
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# evaluate if the winner is pc or player or tie, return value accordingly
# 0 - tie
# 1 - player won
# -1 - pc won
def evaluateGame(playerChoice, pcChoice):
if playerChoice == 1:
print("You have chosen rock.")
if pcChoice == 1:
#tie
print("Computer has chose rock as well. TIE!")
return 0
elif pcChoice == 2:
#paper covers rock - pc won
print("The computer has chosen paper. Paper covers rock. You LOSE!")
return -1
else:
#rock breaks scissors - player won
print("The computer has chosen scissors. Rock breaks scissors. You WIN!")
return 1
elif playerChoice == 2:
print("You have chosen paper.")
if pcChoice == 1:
#paper covers rock - player won
print("The computer has chosen rock. Paper covers rock. You WIN!")
return 1
elif pcChoice == 2:
#tie
print("The computer has chosen paper as well. TIE!")
return 0
else:
#scissors cut paper - pc won
print("The computer has chosen scissors. Scissors cut paper. You LOSE!")
return -1
else: #plyer choice defaults to 3
print("You have chosen scissors")
if pcChoice == 1:
#rock breaks scissors - pc won
print("The computer has chosen rock. Rock breaks scissors. You LOSE!")
return -1
elif pcChoice == 2:
#scissors cut paper - player won
print("The computer has chosen paper. Scissors cut paper. You WIN!")
return 1
else: #pc defaults to scissors
#tie
print("The computer has chosen scissors as well. TIE!")
return 0
# Update track of ties, player wins, and computer wins
def updateScoreBoard(gameStatus):
global tie, playerWon, pcWon
if gameStatus == 0:
tie +=1
elif gameStatus == 1:
playerWon += 1
else:
pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print(menuSelect, "is not a valid option. Please use 1-3")
# Print the scores before terminating the program.
def displayScoreBoard():
global tie, playerWon, pcWon
print("Statistics:\nTies:", tie, "\nPlayer Wins:", playerWon, "\nComputer Wins:", pcWon)
print("Win/Loss Ratio:", playerWon/pcWon)
print("Rounds:", tie + playerWon + pcWon)
main()
def play():
playerChoice = int(playerMenu())
if playerChoice == 4:
return 0
else:
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome)
return 1
This is the method we want.
So all you need to do is call the new menu method under updateScoreBoard().
Then under the new menu method.
if(playerChoice == 1)
play();
if else(playeChoice == 2)
stats();
else
quit();
Use '%s.rsp' % name, Not 'name.rsp'. open('name.rsp', 'w') will always open 'name.rsp' evn if name = 'foo'.
I made SPOILER for you!
this code work well and helpful for you. but you have to think enough before see this code
BELOW IS SPOILER CODE
import random
import pickle
#I'll use class for easy load, easy dump.
class GameStatus():
def __init__(self, name):
self.tie = 0
self.playerWon = 0
self.pcWon = 0
self.name = name
def get_round(self):
return self.tie + self.playerWon + self.pcWon + 1
# Displays program information, starts main play loop
def main():
print "Welcome to a game of Rock, Paper, Scissors!"
print "What would you like to do?"
print ""
game_status = welcomemenu()
while True:
play(game_status)
endGameSelect(game_status)
#prompt user's choice and return GameStatus instance
def welcomemenu():
#changed a logic to handle unexpected user input.
while True:
print "[1]: Start New Game"
print "[2]: Load Game"
print "[3]: Quit"
print ""
menuselect = input("Enter choice: ")
if menuselect in [1, 2, 3]:
break
else:
print "Wrong choice. select again."
if menuselect == 1:
name = raw_input("What is your name?: ") # raw_input for string
print "Hello %s." % name
print "Let's play!"
game_status = GameStatus(name) #make a new game status
elif menuselect == 2:
while True:
name = raw_input("What is your name?: ")
try:
player_file = open('%s.rsp' % name, 'r')
except IOError:
print "There's no saved file with name %s" % name
continue
break
print "Welcome back %s." % name
print "Let's play!"
game_status = pickle.load(player_file) #load game status. not dump.
displayScoreBoard(game_status)
player_file.close()
elif menuselect == 3:
print "Bye~!"
exit()
return
return game_status
# displays the menu for user, if input == 4, playGame in the calling function (main()) is False, terminating the program.
# Generate a random int 1-3, evaluate the user input with the computer input, update globals accordingly, returning True
# to playGame, resulting in the loop in the calling function (main()) to continue.
def play(game_status):
playerChoice = int(playerMenu())
#this if statement is unnecessary. playerMenu() already checked this.
#if playerChoice == 4:
# return 0
pcChoice = pcGenerate()
outcome = evaluateGame(playerChoice, pcChoice)
updateScoreBoard(outcome, game_status)
# prints the menu, the player selects a menu item, the input is validated, if the input is valid, returned the input, if
# the input is not valid, continue to prompt for a valid input
# 1 - rock
# 2 - paper
# 3 - scissors
def playerMenu():
print "Select a choice: \n [1]: Rock \n [2]: Paper \n [3]: Scissors\n"
menuSelect = input("What will it be? ")
while not validateInput(menuSelect):
invalidChoice(menuSelect) #I think this function is un necessary. just use print.
menuSelect = input("Enter a correct value: ")
return menuSelect
# if the user doesn't input a 1-3 then return false, resulting in prompting the user for another value. If the value
# is valid, return True
# takes 1 argument
# menuSelection - value user entered prior
def validateInput(menuSelection):
if menuSelection in [1, 2, 3]: # more readable.
return True
else:
return False
# return a random integer 1-3 to determine pc selection
# 1 - rock
# 2 - paper
# 3 - scissors
def pcGenerate():
pcChoice = random.randint(1,3)
return pcChoice
# evaluate if the winner is pc or player or tie, return value accordingly
# 0 - tie
# 1 - player won
# 2 - pc won
def evaluateGame(playerChoice, pcChoice):
#more readable.
rsp = ['rock', 'paper', 'scissors']
win_statement = ['Rock breaks scissors', 'Paper covers rock', 'Scissors cut paper']
# if player win, win_status = 1 (ex. rock vs scissors -> (1 - 3 == -2) -> (-2 % 3 == 1))
# if pc win, win_status = 2
# if tie, win_status = 0
win_status = (playerChoice - pcChoice) % 3
print "You have chosen %s" % rsp[playerChoice - 1]
what_to_say = "Computer has chose %s" % rsp[pcChoice - 1]
if win_status == 0:
what_to_say += " as Well. TIE!"
elif win_status == 1:
what_to_say += ". %s. You WIN!" % win_statement[playerChoice - 1]
else:
what_to_say += ". %s. You LOSE!" % win_statement[pcChoice - 1]
print what_to_say
return win_status
# Update track of ties, player wins, and computer wins
def updateScoreBoard(outcome, game_status):
if outcome == 0:
game_status.tie += 1
elif outcome == 1:
game_status.playerWon += 1
else:
game_status.pcWon += 1
# If user input is invalid, let them know.
def invalidChoice(menuSelect):
print menuSelect, "is not a valid option. Please use 1-3"
# Print the scores before terminating the program.
def displayScoreBoard(game_status):
print ""
print "Statistics:"
print "Ties: %d" % game_status.tie
print "Player Wins: %d" % game_status.playerWon
print "Computer Wins: %d" % game_status.pcWon
if game_status.pcWon > 0:
#if you don't use float, '10 / 4' will be '2', not '2.5'.
print "Win/Loss Ratio: %f" % (float(game_status.playerWon) / game_status.pcWon)
else:
print "Win/Loss Ratio: Always Win."
print "Rounds: %d" % game_status.get_round()
def endGameSelect(game_status):
print ""
print "[1]: Play again"
print "[2]: Show Statistics"
print "[3]: Save Game"
print "[4]: Quit"
print ""
while True:
menuselect = input("Enter choice: ")
if menuselect in [1, 2, 3, 4]:
break
else:
print "Wrong input."
if menuselect == 2:
displayScoreBoard(game_status)
endGameSelect(game_status)
elif menuselect == 3:
f = open("%s.rsp" % game_status.name, 'w')
pickle.dump(game_status, f)
f.close()
print "Saved."
endGameSelect(game_status)
elif menuselect == 4:
print "Bye~!"
exit()
main()
def rps(a, b):
game = { "rp" : 1, "rr" : 0, "rs" : -1,
"ps" : 1, "pp" : 0, "pr" : -1,
"sr" : 1, "ss" : 0, "sp" : -1}
return (game[a + b])
# For example:
print (rps("r", "p"))

Categories