Scoring in Python game does not work - python

I am new to Python, trying to pick up the language outside of my school courses. This Rock Paper Scissors game I am working on functions correctly, although the score output does not show anything. Here is the code...
#!/usr/bin/env python2
# Extra modules used
import random
import time
# Set each move to a specific number
# Once a selection is made by the player,
# it will be equated to that specific variable.
rock = 1
paper = 2
scissors = 3
# Text representation of each move
names = { rock: "Rock", paper: "Paper", scissors: "Scissors" }
# Game Rules
rules = { rock: scissors, paper: rock, scissors: paper }
# Declare variables to be used to track scoring
player_score = 0
computer_score = 0
# Function to print a greeting and start
# a loop to allow the player to continue
#playing as many times as they wish
def start():
print ("Let's play a game of Rock, Paper, Scissors.")
while game():
pass # Allows the loop to stop when player is done
scores() # Call function when done playing
def game():
# Call move function to determine player move
player = move()
# Get computer move as random int between 1 and 3
computer = random.randint(1, 3)
# Send the move through the result function
result(player, computer)
return play_again()
# Function to obtain a move from the player
def move():
while True:
print
player = input("Rock = 1\nPaper = 2\nScissors = 3\nMake a move: ")
# Try to set the player move, or catch the error
try:
# Cast the user input as an integer
player = int(player)
# If entry is valid, set the variable
if player in (1,2,3):
return player
except ValueError:
pass
print ("Oops! I didn't understand that. Please enter 1, 2, or 3.")
# Function to determine the result of the game
# player move and computer move are passed in
def result(player, computer):
# Countdown to result display
print ("1...")
time.sleep(1)
print ("2...")
time.sleep(1)
print("3!")
time.sleep(0.5)
# Display the computer's move
# string.format() gets the text version
# of the move and inserts it where "0"
print ("Computer threw {0}!".format(names[computer]))
#Call the scores set earlier
global player_score, computer_score
# Check the results of the game
if player == computer:
print ("Tie game.")
# Check if the losing move to the player's move
# is equal to the computer's move
elif rules[player] == computer:
print ("Your victory has been assured.")
player_score += 1
else:
print ("The computer laughs as you realize you have been defeated.")
computer_score += 1
# Ask to play again
def play_again():
answer = input("Would you like to play again? y/n: ")
if answer in ("y", "Y", "yes", "Yes", "Of course!"):
return answer
else:
print ("Thank you very much for playing. See you next time!")
def scores():
global player_score, computer_score
print ("HIGH SCORES")
print ("Player: "), player_score
print ("Computer: "), computer_score
# Used to execute in command line or import
# into another Python script. This will prevent
# the code from being executed when being imported.
if __name__ == '__main__':
start()

Your print statements are a little off.
You should be including the arguments inside the print statement
print("Player: ", player_score)
Edit:
To speak a little more to printing. You could also use
print("Player: {}".format(player_score))

You need the variables inside the brackets so:
print ("Player: "), player_score
print ("Computer: "), computer_score
becomes
print ("Player: ", player_score)
print ("Computer: ", computer_score)
Alternatively,
print ("Player: {}".format(player_score))
print ("Computer: {}".format(computer_score))
Format is better to use as there is a whole lot more you can do with it (I'll let you find that out for yourself)!

Related

Why colorama make printing slower in python (Thonny)?

It's my RPG assignment for our school. I made an RPG program about an encounter with a Pirate and conversing with him with a guessing game. When I didn't use Colorama, the program runs normal but when using it, it slows down the program when running. I submitted the got 18 or 20 which is not bad, and I suspected it's how my program runs that's why I didn't get the perfect score.
I'm wondering if you guys can help me how to run the program faster when using Colorama? I just really wanted to learn how to solve this kind of issue.
import random
import time
import colorama
from colorama import Fore, Back, Style
talk_again = 'y'
while talk_again == 'y':
print("\nThere is a pirate coming down the road...")
time.sleep(2)
try:
user_option = int(input("\nWhat would you like to do? \n [1] To greet! \n [2] To play a game of chance \n [3] To walk on \n>>> "))
greetings= ["Hello stranger", "Hi there stranger!","Ahoy stranger!","Hey","*He stops, staring at you & didn't say anything*"]
inventory = ["Sword", "Shield","Dagger","Choker","Healing potion", "Red gem", "Red diamond","Sword", "Armour"]
leaving = ["Argghhh!!!", "Arrgh!Shut up!","Dammit! Arrgghh!!!"]
# lowercase items in inventory list, so we can compare wager input text
lowercase_inventory = [x.lower() for x in inventory]
def speak(text): #This is pirate conversation function colored in red
colorama.init(autoreset=True) # Automatically back to default color again
print(Fore.RED + '\t\t\t\t' + text)
def guess_my_number(): # the guessing number game
colorama.init(autoreset=True)
speak("Great! Let's play game of chance.")
time.sleep(1.5)
speak("I have a magic pen we can play for. What can you wager?")
time.sleep(1.5)
print("This is your inventory:" , lowercase_inventory)
wager = input(">>> ").lower()
# if wager item available in lowercased inventory
if wager.lower() in lowercase_inventory:
speak("That is acceptable!, Let's play the game of chance!")
time.sleep(1.5)
speak("I've thought of number between 1 to 100, you have 10 trys to guess it")
time.sleep(1.5)
speak("If you guess correctly, magic pen will be added to your inventor")
time.sleep(1.5)
speak("Otherwise you will lose " + wager + " from your inventory")
time.sleep(1.5)
speak("Make your guess:")
random_number = random.randint(1,100)
count = 10
main_game = True
# while loop will keep runing either guessed number matches random number or count number reaches 1
while main_game and count > 0:
try:
guess = int(input(">>> "))
except ValueError:
speak("Arrghh! I said guess numbers from 1 to 100 only!! Do you wanna play or not?")
else:
if count == 0:
speak("HA HA HA!! You lose!")
# count decreses by one every time.
lowercase_inventory.remove(wager)
print("Your current inventory:", lowercase_inventory)
break
if guess == random_number:
speak("Darn it!.. You won in " + str(11 - count)+ " guesses") #str(11 - count) means subtract the guesses from 11
lowercase_inventory.append('Magic pen')
print("The magic pen has been added in your inventory.\nYour inventory now: ", lowercase_inventory)
break
elif guess > random_number:
speak("Lower the number kid! Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
elif guess < random_number:
speak("Make it higher!Guess again!")
count-=1 # count decreses by one every time.
speak(str(count)+" "+ "chances left!!")
else:
speak("You don't have this item in your inventory, We can't play!")
except ValueError:
print("\nType 1, 2 and 3 only!")
else:
while True:
if user_option == 1:
print("\nType to greet the pirate:")
input(">>> ")
speak(random.choice(greetings))
elif user_option == 2:
guess_my_number()
elif user_option == 3:
leave_input = input("\nWhat would you like to say on leaving?:\n>>> ")
if leave_input == 'nothing':
speak("*He glances at you, then looks away after he walk passeed you, minding his own business*")
else:
speak(random.choice(leaving))
talk_again = input("\nPlay again?(y/n) " )
if talk_again == 'n':
print("\n Goodbye!")
break
user_option = int(input("\nWhat would you like to do? \n[1] to greet! \n[2] to play a game of chance \n[3] to walk on \n>>> "))

Python 3 Rock Paper Scissors with user input being stored to make it more challenging

I am working on Rock, Paper, Scissors in Python 3. I need help trying to implement where the computer keeps track of the users choices so it can tell what the player favors and have an advantage over the player. I also have the computer choosing random using an integer but I need to make the players choice a lowercase 'r' 'p' 's' and a 'q' to quit so it can check for invalid entry and display message and ask again. I don't want to use integers for the player.
Here is what I have:
import os
import random
import time
#global variable
#0 is a placeholder and will not be used
choices = [0, 'rock', 'paper', 'scissors']
player_wins = 0
computer_wins = 0
tie_count = 0
round_number = 1
keep_playing = True
# sets cls() to clear screen
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# function to display stats
def stats():
print("Current Statistics:")
print("Player Wins: {}".format(player_wins))
print("Computer Wins: {}".format(computer_wins))
print("Tied Games: {}\n".format(tie_count))
# function to check outcome
def game_outcome(player, computer):
#this makes the variables global, else you'll get error
global player_wins, tie_count, computer_wins
if computer == player:
print("It's a tie!\n\n")
tie_count += 1 # incraments tie
# checks all possible win conditions for player. and if met, declares player a winner. If not, declares compute the winner.
elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
print("Player wins\n\n")
player_wins += 1 # incraments player's wins
else:
print("Computer wins!\n\n")
computer_wins += 1 # incraments computer's wins
# clears screen
cls()
print("Let's play Rock Paper Scissors!")
# 3-second time out before clearing and asking for input
time.sleep(3)
while keep_playing == True:
# make computer choice random from defined list. Only selects a range of 1-3 ignoring the "0" placeholder
# this is because the user selects a number, instead of typing the weapon, and that number pulls the weapon from the list
computer = random.choice(choices[1:4])
cls()
# prints starting of round and shows stats
print("+++++++++++++[Starting Round {}]+++++++++++++\n".format(round_number))
stats()
# ask for player input
player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
player = choices[int(player)]
cls()
print("\n\nThe player's choice: [{}]\n".format(player))
print("The computer's choice: [{}]\n\n".format(computer))
game_outcome(player, computer)
round_number += 1
# ask if player wants to play again. If not, stop
play_again = input('Would you like to play again [y/n]? ')
if play_again.lower() == 'n':
break
print("Thanks for playing!")
Try using a dictionary:
# put this with the imports at the top
import sys
# replace `choices` at the top
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
# get computer choice
# replaces `computer = random.choice(choices[1:4])`
computer = random.choice(['rock', 'paper', 'scissors'])
# ask for player input
# replace these two lines of code:
# player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
# player = choices[int(player)]
while True:
try:
player = choices[input("What is your choice?\n(r) Rock\n(p) Paper\n(s) Scissors?\n(q) to quit.\n\nEnter the letter before the weapon of choice: ")]
if player == 'quit':
sys.exit(0)
break
except KeyError:
print('Please try again.')

python code doesn't iterate through whole loop and stuck at raw_input

I'm currently attempting to learn python and have recently purchased a book of beginner exercises etc. One of the challenges is to build a rock, paper, scissors game using the below code. When I use this code though, I get stuck in the move function, in terminal I enter a move and it doesn't move to the 'try' command and just prompts me to enter another number. It looks as though the program is stuck in the while loop and won't move further than raw_input. I've tried a few things but I can't seem to get my head around it. Any help would be greatly appreciated. Thanks!
import random
import time
rock = 1
paper = 2
scissors = 3
names = {rock: "Rock", paper:"Paper", scissors:"Scissors"}
rules = {rock:scissors, paper:rock, scissors:paper}
player_score = 0
computer_score = 0
def start():
print
print "Let's play Rock, Paper, Scissors"
while game():
pass
scores()
def game():
player = move()
computer = random.randint(1, 3)
result(player, computer)
return play_again()
def move():
while True:
print
player = input("Rock = 1\nPaper = 2\nScissors = 3\nMake a Move: ")
try:
player = int(player)
if player in (1,2,3):
return player
except ValueError:
pass
print "Oops! I didn't understand that. Please enter 1, 2, or 3"
def result(player, computer):
print "1..."
time.sleep(1)
print "2..."
time.sleep(1)
print"3!"
time.sleep(0.5)
print "Computer threw {0}!".format(names[computer])
global player_score, computer_score
if player == computer:
print"Tie Game."
else:
if rules[player] == computer:
print "Your victory has been assured!"
player_score += 1
else:
print "The computer is victorious"
computer_score += 1
def play_again():
answer = raw_input("Would you like to play again? y/n")
if answer in ("y", "yes", "Y", "Yes"):
return answer
else:
print "Thank you for playing!"
def scores():
global player_score, computer_score
print "HIGH SCORES"
print "Player: ", player_score
print "Computer: ", computer_score
Update: Seems that people in the comments can run the code fine, but when I run it through terminal I keep getting this. I've now run the same code through my housemates MacBook and the same problem persists.

Can't use functions in Python

I've been working on a project in python for a while now and I can't call the main function. I searched for a while but I can't get it to work. Right now the problem is that I can't call the main function. It used to be that once the program went through the main function once it wouldn't go back to the main function, but now it won't even go into the main function and I can't call it from the shell. Could someone help me? Here's my code.
#!/usr/bin/python
# I only have the above part in case the
# end user does not have python
# Wizard's Quest Copyright (c) 2016 by GrayHat4Life
# This software is open source and may be distributed freely
# Prepare the program
import sys, random
# Set up some variables & begin the story
global health
health = 10
global enemiesKilled
enemiesKilled = 0
print("You are a wizard travelling through the kingdom")
print("Your quest: to save the kingdom by placing the Gem of Karn in its rightful place, the Tower of Souls")
# Main gameplay loop
def main():
# Battle code
# Set up the battle variables
enemyList = ["Goblin", "Witch", "Dark Mage", "Dark Knight", "Theif", "Troll", "Orc"]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# Prepare the battles
print("As you are walking through the Forest of Doom, a " + random.choice(enemyList) + " appears on the path in front of you!")
# This part isn't very usefull, it's only to give the
# player the illusion of free will. It's actually a kind of gambling game :s
input("What spell do you use to attack it? ")
# The attack strengths
attack = random.choice(numbers)
enemyAttack = random.choice(numbers)
# Let the battle begin!
if attack > enemyAttack:
health = health - 1
print("Your attack failed and you've been hit! You narrowly escape the enemy and continue your quest")
main()
elif enemyAttack > attack:
enemiesKilled = enemiesKilled + 1
# This loop gives the user the ability to win. And lose. :D
while True:
if enemiesKilled == 10:
print("You've finally made it to the end of your quest!")
print("You place the Gem of Karn in the soul sphere and save the kingdom!")
sys.exit()
elif health == 0:
print("The damage was too much.")
print("You bleed out in the middle of the forest, alone and friendless.")
print("GAME OVER")
sys.exit()
Thanks!
Python does not have a main function. Define your functions first so the interpreter knows about them. It will then execute the first statement after the last 'return' and following statements after that.
Correct syntax for python:
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str
return;
# Now you can call printme function
printme()
I don't see where you call the main() method initially.
Currently, you are entering a while True: and neither condition enemiesKilled == 10: or health == 0: are true
Your code should follow this structure if you are expecting to execute it
import somestuff
def main():
# do something here
if __name__ == '__main__':
# call the main function
main()
And if you want the while True: piece, then I would recommend something like this instead to stop the infinite loop
if __name__ == '__main__':
# call the main function
while enemiesKilled != 10 or health != 0:
main()
if enemiesKilled == 10:
print("You've finally made it to the end of your quest!")
print("You place the Gem of Karn in the soul sphere and save the kingdom!")
elif health == 0:
print("The damage was too much.")
print("You bleed out in the middle of the forest, alone and friendless.")
print("GAME OVER")

"Variable ___ referenced before assignment."

I've been having a bit of difficulty with my Python programme. It plays Rock Paper Scissors. The code is pretty large so I'll shorten it to a sample programme, but the full code can be viewed at https://github.com/Ph0enix0/doitall/blob/master/computerpungramming/rockpaperscissors.py
(count is the amount of games played)
count = 0
user_wins = 0
comp_wins = 0
def game():
comp_answer = ['rock', 'paper', 'scissors']
user_answer = input('Rock, paper, or scissors?')
if user_answer = 'rock':
count += 1
if comp_answer = 'paper':
print('Paper! I win!)
comp_wins += 1
#The rest of the comparisons are here
while 1 == 1:
game()
If I put the variables in game() they will reset every time. Help?
You need to move the variables inside the function and define scissors_wins:
def game():
'''
The actual game code. The code randomly chooses
rock, paper, or scissors. Then, it checks if the user's choice
beats the computer's. If it does, the user wins, and vice versa.
'''
#User picks rock, paper, or scissors.
user_answer = input('Rock, paper, or scissors? ')
#Tell the code that the game is not finished. Used for while loops.
game_finished = False
count = 0
user_wins = 0
comp_wins = 0
scissors_wins = 0
Your game already has a loop so unless you are doing something in your while 1 == 1 then simply call game()
And yes every time you call the function the variables will be reset to 0.
If you want the win count to persist through many runs use a dict declaring outside the function:
d = {"user":0,"comp":0,"scissor":0}
Then update at the end of each game:
d["user"] += user_wins
Or increase the count of each inside the function instead of using the variables.
You also don't seem to ever break the loop so your code will loop infinitely. I imagine you want to also ask the user more than once for input so move user_answer = input('Rock, paper, or scissors? ') inside the loop.
Something like the following:
d = {"user":0,"comp":0,"scissor":0}
d = {"user":0,"comp":0,"scissor":0}
def game():
'''
The actual game code. The code randomly chooses
rock, paper, or scissors. Then, it checks if the user's choice
beats the computer's. If it does, the user wins, and vice versa.
'''
#Tell the code that the game is not finished. Used for while loops.
game_finished = False
count = 0
user_wins = 0
comp_wins = 0
scissors_wins = 0
#Game isn't finished, so the code continues.
while not game_finished:
user_answer = input('Rock, paper, or scissors? ')
# update dict with totals when loop breaks
The game function can't change the variables outside it (count, user_wins, comp_wins). Have the function return the necessary values.
count = 0
user_wins = 0
comp_wins = 0
def game():
...
return count, user_wins, comp_wins
count, user_wins, comp_wins = game()
You're going to want to change
if comp_answer = 'paper':
to
if comp_answer == 'paper':
That's probably what's throwing the error. Change the = to == in any other places where you're checking an if condition.

Categories