Related
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!")
I'm trying to get this RPG program to work, but I can't figure it out. I run it and well, you will see when you run the program. For some reason when I run this it stops at 1,2,3,4 after every move I make. Am I not returning anything? What am I doing wrong here, and how can I improve my organization and code in the future?
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == input('1'):
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == input('2'):
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == input('3'):
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == input('4'):
Loop = False
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
The problem is you are using input() in if statement. Whenever interpreter tries to check if condition is true or not it executes the input() which demands an input even when you didn't expect it. In one of the methods your input was in wrong order so I fixed that too. So correct code should be :-
import math
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
class enemy:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball']
Loop = True
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = enemy(30, 30, 5, 0, 10)
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run \n')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
elif choice == '2':
spellchoice = input('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
elif choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
Loop = False
def enemy_battle(character, enemy):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
elif a <= 50:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1 == True:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
You didn't need two classes here clearly. But I suppose you might be thinking of adding some more features in future I guess. You can study more about oop and inheritance and figure out a smarter solution in general. I think you should focus on basics. Also try not to name the temporary variable same as that of class. It is a very hastly written code imo. But I fixed it's working.
Looks interesting, send me a copy after you finish will ya?
so basically you use too much input()
you have to enter a value for every input() function
you need to organize your code, maybe look at how others write their code
this is a quick fix, but it doesn't mean that this is the standard, you still have a lot to learn
import random
class character:
def __init__(self, hp, max_hp, att, exp, int):
self.hp = hp
self.max_hp = max_hp
self.att = att
self.exp = exp
self.int = int
charspells = ['Fireball','iceblock']
Loop = True
items = []
mainc = character(100, 100, 10, 0, 10)
tai_lopez = character(30, 30, 5, 0, 10) # enemy
def fireball(character, enemy):
enemy.hp -= character.int
print('You did, ',character.int ,'to the enemy')
print('Enemy.hp', enemy.hp)
return enemy.hp
def character_battle(character, enemy):
choice = input('What would you like to do?\n 1. Attack \n 2. Spells \n 3. Items \n 4. Run')
if choice == '1':
print('You attack the enemy!')
enemy.hp -= character.att
print('You dealt', character.att, 'to the enemy!')
print('Enemy hp =', enemy.hp)
if choice == '2':
print('Which spell do you wish to call?')
print('1.', charspells[0],'\n' '2.', charspells[1], '\n' 'q', 'exit')
spellchoice = input()
if spellchoice == ('1'):
print('You used fireball!')
fireball(character, enemy)
elif spellchoice == ('2'):
if charspells[1] != 'Lightning bolt':
print('It doesnt exist, sorry')
# ill add more spell fucntions later
if spellchoice == ('3'):
print('You went back to the menu')
if choice == '3':
if items == []:
print('You have no items')
if items == ['potions']:
print ('response')
#placeholder ill add the fucntion later
elif choice == '4':
print("You cowardly run away")
exit()
def enemy_battle(enemy, character):
a = random.randint(0,50)
if a <= 35:
print('The enemy attacks you!')
character.hp -= enemy.att
print('Your hp =', character.hp)
else:
print('The enemy uses mind attacks bruh')
character.hp -= enemy.int
print('Your hp =', character.hp)
def battle_loop(character, enemy):
Loop1 = True
while Loop1:
while enemy.hp > 0 and character.hp > 0:
character_battle(character, enemy)
enemy_battle(character, enemy)
if enemy.hp <= 0:
print('You Won')
Loop1 = False
if character.hp <= 0:
print('You lost')
exit()
battle_loop(mainc, tai_lopez)
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.
I'm remastering the bot by my self and I'm stuck! This is a code which prompts the user to select how many cards they get from the options of
7, 9, 11, and 15
def Cards():
print("Card Amounts")
print("\nChoices")
print(7)
print(9)
print(11)
print(15)
PlayerInput3()
def PlayerInput3():
global PlayersCards
PlayerInput = int(raw_input())
if(PlayerInput == 7):
PlayersCards == range(1,7)
print("Lets get started")
Game()
But when they choose how many cards they want it does stay into affect after the definition is over. I want the Players card range to continue in a different defined area. Here:
def Game():
global roundNumber, MyDeck, PlayersCards
import random
Select = PlayersCards
roundNumber = roundNumber + 1
print("Round %d!") % (roundNumber)
if(roundNumber == 1) or (roundNumber < 15):
PlayersCards = random.randint(1, 50)
MyDeck.append(PlayersCards)
print("Here are your cards")
print(MyDeck)
print("Select a card")
But It wont continue on past the
def Cards():
How Can I make it so that the PlayersCard == range(1,7) Continues on regardless of what definition it is in?
I think this code works as you require:
def instructions():
print("You will be playing with an ai and whoever lays down the highest number wins that round.")
print("The points you get are determined by how much higher your card was from your opponents card.")
print("The person with the most points wins!")
def getUserInput():
global roundNumber, My_Deck, PlayerPoints, AIPoints
My_Deck = []
roundNumber = 0
AIPoints = 0
PlayerPoints = 0
print ("\nDo you want to play?: ")
print("\nChoices")
print("1. Yes")
print("2. No\n")
Choice = input()
if(Choice == 'Yes') or (Choice == 'yes'):
print("\nOkay, lets get started!")
startGame()
elif(Choice in ['No', 'no']):
print("Okay, bye!")
quit()
else:
print("That is not a Choice!")
print("Choose 'Yes' or 'No'")
getUserInput()
def startGame():
global roundNumber, My_Deck, PlayerPoints, AIPoints
print("\nAIPoints = %d PlayerPoints = %d" % (AIPoints, PlayerPoints))
roundNumber = roundNumber + 1
print("\nRound %d!" % (roundNumber))
cardChoosen = None
import random
if(roundNumber == 1):
print("\nHere are your 9 cards.\n")
for Cards in range(9):
Cards = random.randint(1, 100)
My_Deck.append(Cards)
while True:
print("Select one of your cards: "),
print(My_Deck)
Select = int(input())
try:
if (Select in My_Deck):
My_Deck.remove(Select)
print("You choose", Select)
print("Your deck now is:")
print(My_Deck)
cardChoosen = Select
break
else:
print("You don't have that card in your deck!")
except ValueError as e:
print(e)
elif(roundNumber == 10):
if(PlayerPoints > AIPoints):
print("\nCongratulations you won with a score of %d compared to the AI's %d" % (PlayerPoints, AIPoints))
getUserInput()
elif(PlayerPoints < AIPoints):
print("\nUnfortunately you lost with a score of %d compared to the AI's %d" % (PlayerPoints, AIPoints))
getUserInput()
else:
print("\nWow this is basicaly impossible you tied with the AI with you both ahving a score of %d and %d... " % (PlayerPoints, AIPoints))
getUserInput()
else:
print("\nHere are your %d cards.\n" % (9 - roundNumber + 1))
while True:
print("Select one of your cards: "),
print(My_Deck)
Select = int(input())
try:
if (Select in My_Deck):
My_Deck.remove(Select)
print("You choose", Select)
print("Your deck now is:")
print(My_Deck)
cardChoosen = Select
break
else:
print("You don't have that card in your deck!")
except ValueError as e:
print(e)
AINumber = random.randint(1, 100)
if(cardChoosen > AINumber):
print("\nYou won! Your number %d was higher than the AI's number %d" % (cardChoosen, AINumber))
print("\nYou scored %d points" % (cardChoosen - AINumber))
PlayerPoints = PlayerPoints + (cardChoosen - AINumber)
startGame()
elif(cardChoosen < AINumber):
print("\nYou Lost! Your number %d was lower than the AI's number %d" % (cardChoosen, AINumber))
print("\nAI scored %d points" % (AINumber - cardChoosen))
AIPoints = AIPoints + (AINumber - cardChoosen)
startGame()
else:
print("\nYou tied with the AI! Your number %d was the same as the AI's number %d" % (cardChoosen, AINumber))
print("\nNobody scored points!")
startGame()
My_Deck = []
roundNumber = 0
AIPoints = 0
PlayerPoints = 0
instructions()
getUserInput()
Here is my code:
from random import*
from myro import*
from math import*
def computerChoice():
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
return choice
def userGuess():
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
userNameWins = 0
computerWins = 0
draws = 0
if(userChoice == "R" and choice == "paper"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
speak( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
speak("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
speak("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
speak("you win")
userNameWins = userNameWins + 1
else:
speak("Draw")
draws = draws + 1
return userNameWins, computerWins, draws
def printResults(userNameWins, computerWins, draws)
# insert code for print statement
def main():
for x in range (5):
speak("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults (userNameWins, computerWins, draws)
I get an error when I try to define some variables and I don't know why.
I need a function that properly prints the results returned by calculate()
The part you're asking for is trivial. Since you didn't give us the desired output format, I'll guess at it, and hopefully you can fix it to match the way you want it to look:
def printResults(userNameWins, computerWins, draws)
print('user won {} times, computer won {} times, and players drew {} times'
.format(userNameWins, computerWins, draws))
However, your code isn't going to work, for at least two reasons.
First, you call this:
calculate(userChoice,choice)
… which returns the 3 values you want, but you never store them anywhere. In particular, you don't store them, or anything else, in variables named userNameWins, computerWins, and draws. So, this like will get a NameError:
printResults (userNameWins, computerWins, draws)
Second, you're looping 5 times over a function that, each time, returns a full set of values, but you're only calling printResults once, not 5 times. I'm not sure what you're intending here, but most likely, either you need to move printResults into the loop, or you need to add code that sums up the results across all the loops.
sorry about the wait but hopefully this solution is of help to you.
from random import randint
#from myro import *
choice = None
userChoice = None
userNameWins = 0
computerWins = 0
draws = 0
def computerChoice():
global choice
computer = randint(0,2)
if (computer == 0):
choice = "rock"
elif(computer == 1):
choice = "paper"
else:
choice = "scissors"
print "Scribbler selected " + choice
return choice
def userGuess():
global userChoice
print " R = Rock"
print " P = Paper"
print " S = Scissors"
userChoice = raw_input("Enter R, P, or S: ")
return userChoice
def calculate(userChoice, choice):
global userNameWins
global computerWins
global draws
if(userChoice == "R" and choice == "paper"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice== "R" and choice == "scissors"):
print( "you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "rock"):
print("you win")
userNameWins = userNameWins + 1
elif(userChoice== "P" and choice == "scissors"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "rock"):
print("scribbler wins")
computerWins = computerWins + 1
elif(userChoice == "S" and choice == "paper"):
print("you win")
userNameWins = userNameWins + 1
else:
print("Draw")
draws = draws + 1
def printResults():
print "You won " + str(userNameWins) + " times"
print "Scribbler won " + str(computerWins) + " times"
print "There were " + str(draws) + " draws"
if (userNameWins > computerWins):
print "You win overall"
elif (userNameWins < computerWins):
print "Scribbler wins overall"
else:
print "It was a dead heat"
def main():
global userChoice
global choice
for x in range (5):
print ("Rock Papers Scissors ")
userChoice = userGuess()
choice = computerChoice()
calculate(userChoice,choice)
printResults ()
main()
I didn't have myro installed so I used print instead to display the results. Before you weren't saving the variables for the results anywhere so I made a global variable so that it can store the variables. Also I completed the printResults function.