Python Forum
I need help with a python Rock Paper Scissors game urgently.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I need help with a python Rock Paper Scissors game urgently.
#1
Hello, I'm learning Python at college but it's an online course and I've never met the instructor or a class mate yet. Everything is read your book and turn in a lab each week. All online so I have no one to actually speak to for help. I have a Rock Paper Scissors game that is due on Dec 3 that has certain criteria that I'm having a hard time with. Can someone help me? The game has to accept input from the user as lowercase 'r' 's' 'p' or 'q' for quit. Anything else needs to error and go back to choose r p s. The game needs to display info such as round # and wins, loses and ties and increment as such. The game also needs to keep a list or dictionary of players choices made so it can learn and predict what you favor to make it harder. I have most of it but I need help on the dictionary part and maybe error checking . Here is my code so far:
import os
import random
import time
import sys

#globalA variable
#0 is a placeholder and will not be used
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
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(['rock', 'paper', 'scissors'])

    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(r) Rock\n(p) Paper\n(s) Scissors?\n\nEnter the letter before the weapon of choice:")
    player = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}

    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

    stats()

# ask if player wants to play again. If not, stop
    play_again = input("Press 'enter' to continue or 'q' to quit. ")
    if play_again.lower() == 'q':
        cls()
        break
stats()
print("Thanks for playing!\n")
Reply
#2
Stop using global. You want to be clear about what is going on in your functions. You do that with parameters and return values. See the function tutorial on how to do that.

I think you need [player] at the end of line 71, otherwise you're just overwriting the user's input from line 70.

To enforce the correct input, use a while loop something like this:

while True:
    move = input('What is your move? ')
    if move in ('r', 'p', 's', 'q'):
        break
    print('That is not a valid move.')
To keep track of the player's moves, use a dictionary (history = {'rock': 0, 'paper': 0, 'scissors': 0}). Then you can update the move count with history[player] += 1.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thank you for your reply Ichabod. I ended up going a different way with my code as I found other things I forgot to implement. I did however go back and try to fix the code I had posted with what you suggested. Either I don't understand where the code goes or I don't understand how it works. I'm betting on a little bit of both. Anyway, I still didn't get it to work but, I greatly appreciate you offering to help me. Thank you for that.
Reply
#4
I have a few comments about style, to maybe help your future sanity...

(Dec-02-2018, 09:36 PM)Riff_Raff Wrote: # function to display stats
def stats():
What's the point of that comment? Unless the code is complicated, your comments should explain why you're doing something, not what you're doing. Just looking at the name of the function tells you that this handles stats, for example, so having a comment saying it's a function that handles stats is a bad comment, as it doesn't contribute anything to the reader's understanding of what's happening. If anything, the comment serves as a red flag that most comments should just be ignored, since they'll just be meaningless anyway.

(Dec-02-2018, 09:36 PM)Riff_Raff Wrote: # clears screen
cls()
If you need a comment to remind yourself that the function cls() will clear the screen, then you need to rename the function to better explain what it actually does. For example, if the function were named clear_screen(), you wouldn't ever need a comment explaining what the function did or why you were calling it.

I promise I'm not making things up, this is known as self-documenting code.


(Dec-02-2018, 09:36 PM)Riff_Raff Wrote: elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
This is different from style, but that line horrifies me. Look at all the stuff packed into that one line! Woah.
The easy way to make that easier to read would be to have a dict of moves, and what they beat. Here's an example:
>>> winning_moves = {
... "scissors": "paper",
... "paper": "rock",
... "rock": "scissors"
... }
>>> player = "rock"
>>> computer = "scissors"
>>> if winning_moves[player] == computer:
...   print("player wins")
... elif winning_moves[computer] == player:
...   print("computer wins")
... else:
...   print("tie round")
...
player wins
Or, if you wanted to get crazy with it, you could create classes and make it look real spiffy:
>>> class Move:
...   def __init__(self, choice):
...     self.choice = choice
...   def __gt__(self, other):
...     opponent = other.choice
...     value = self.choice
...     if value == "scissors" and opponent == "paper":
...       return True
...     if value == "paper" and opponent == "rock":
...       return True
...     if value == "rock" and opponent == "scissors":
...       return True
...     return False
...   def __lt__(self, other):
...     if self.choice == other.choice:
...       return False
...     return not self > other
...
>>> player = Move("rock")
>>> computer = Move("scissors")
>>> player > computer
True
>>> player < computer
False
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I attempted to make a rock paper scissors bot for homework Intellectual11 3 2,922 Jun-24-2021, 08:00 PM
Last Post: deanhystad
  important work. need help urgently please hola123 9 3,671 Feb-11-2021, 06:52 PM
Last Post: hola123
Question Rock, paper, scissors spelling error banidjamali 6 3,220 Jan-19-2021, 02:51 PM
Last Post: banidjamali
  Rock, Paper, Scissors Game kramon19 2 5,358 Jan-10-2020, 08:18 AM
Last Post: perfringo
  Rock, Paper, Scissors Advanced that saves, loads, and keeps statistics EvanCahill 0 5,211 Jul-21-2018, 07:32 PM
Last Post: EvanCahill
  Rock Paper Scissors Warmlawpk441 4 5,042 Oct-11-2017, 10:55 AM
Last Post: gruntfutuk
  Rock paper scissors game samiraheen 3 6,370 Oct-03-2017, 07:07 PM
Last Post: buran
  The Python Book altered rock paper scissors Python_Noob 0 2,920 Sep-18-2017, 06:13 AM
Last Post: Python_Noob
  HELP---problems with rock paper scissors games kalt91 2 4,127 Sep-15-2017, 04:51 PM
Last Post: micseydel
  Rock, Paper, Scissors game help.. hentera 3 5,060 May-19-2017, 10:56 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020