Zibzo

Rock Paper Scissors Beginners practice

Recommended Posts

Rock Paper Scissors game made simply on Python. Very very simple, great project for beginners. Also an attached .py file

def main():

    import random
    botHand = random.randint(1,3)

        
    userHand = input("Pick rock, paper or scissors ")
    print("You pick " + userHand)
    if(botHand == 1):
        print("Computer picks scissors")
    elif(botHand == 2):
        print("Computer picks rock")
    elif(botHand == 3):
        print("Computer picks paper")
    import time
    time.sleep(2)
    if ((userHand == 'rock' or userHand == 'Rock')and botHand == 1):
        print('You win')
    elif ((userHand == 'rock' or userHand == 'Rock')and botHand == 2):
        print('You tie.')
    elif ((userHand == 'rock' or userHand == 'Rock')and botHand == 3):
        print('You lose.')
    elif ((userHand == 'paper' or userHand == 'Paper')and botHand == 1):
        print('You lose.')
    elif ((userHand == 'paper' or userHand == 'Paper')and botHand == 2):
        print('You win!')
    elif ((userHand == 'paper' or userHand == 'Paper')and botHand == 3):
        print('You tie.')
    elif ((userHand == 'scissors' or userHand == 'Scissors')and botHand == 1):
        print('You tie.')
    elif ((userHand == 'scissors' or userHand == 'Scissors')and botHand == 2):
        print('You lose.')
    elif ((userHand == 'scissors' or userHand == 'Scissors')and botHand == 3):
        print('You win!')
    else:
        print('INVALID input, try again')
        import time
        time.sleep(1)
        main()
while (1==1):
    main()
    import time
    time.sleep(1)
    input('Press enter to start again')

RockPaperScissors.py

EDIT:

For anyone wondering, yes I do know that I do not have to import the time module every single time, and I can import it once at the start. Just wanted to clear that with you guys.

Edited by Zibzo
Clear a repetition of code

Share this post


Link to post
Share on other sites

 I figured out how to break down the codes into three other functions similar to the one shown. But my main function calls these function based on the User's choice. Still overall my program is more lines.

def rock(comp):
    if comp == 1:
        print('I chose Rock')
        return "tie"
    elif comp == 2:
        print("I chose scissors")
        return "you win"
    else:
        print("I chose paper")
        return "you lose"

Share this post


Link to post
Share on other sites

@clyde21 So the line:

while(1==1):

essentially creates an infinite loop. Inside the loop, there is the main() function and then there's an input() as well. The loop won't continue until the input() function is cleared, so that's the reason for input('Press enter to play again'). Normally infinite while loops are considered bad in Python, so a better way to implement this is to include a cycle breakpoint as well. For example:

while (breakPoint != 'x' or breakPoint != 'X'):
    main()
    import time
    time.sleep(1)
    breakPoint = input('Press enter to start again or press x to exit')
	

So this is a very simplistic break point, but basically if x is entered, the while loop stops. That's the reason for the while(breakPoint != x), so if the variable breakPoint doesn't equal the string 'x', the loop will continue.

Hope this helps!

Share this post


Link to post
Share on other sites

Hey folks,

Just wanted to add my code, since I think my solution is interesting.  Played around a bit with the text formatting for fun.

@Zibzo, I wasn't able to get the breakPoint logic working from yours, so I used the logic from a previous video.  Wondering how you'd apply the 'breakPoint' logic in my code - it looks more self-contained.

import time
import random


def win(uStr, rStr):
    """Text for your win"""
    print("You chose",uStr,"! Your challenger chose",str.lower(rStr),"!  YOU WIIIIIIIN!!\n")

def lose(uStr, rStr):
    """Text for your loss"""
    print("You chose",str.lower(uStr),"! Your challenger chose",rStr,"!  YOU looooooooose!!\n")

def tie(uStr, rStr):
    """Text for a tie"""
    print("You chose",uStr,"! Your challenger also chose",rStr,"!  Great minds think alike, but great minds must play agaaaaaiiiin!\n")


def battle(uVar, rVar, uStr, rStr):
    """The actual battle"""
    if(uVar == 0 or uVar > 3):
        print("Not an appropriate hand-gesture!\n")
    elif(uVar == rVar):
        tie(uStr, rStr)
    elif(uVar == rVar + 1 or uVar == rVar - 2):
        win(uStr, rStr)
    elif(uVar == rVar - 1 or uVar == rVar + 2):
        lose(uStr, rStr)
    else:
        print("Not an appropriate hand-gesture!\n")

def main():
    breakPoint = False
    while not breakPoint:
        validInput = False
        while not validInput:
        # Loop user input request
            try:
                uVar = int(input("Choose your weapon! 1 = Rock, 2 = Paper, 3 = Scissors: "))
                rVar = random.randint(1, 3)
                uStr = "ROOOCK" if uVar == 1 else "PAPEEER" if uVar == 2 else "SCISSOOORS"
                rStr = "ROOOCK" if rVar == 1 else "PAPEEER" if rVar == 2 else "SCISSOOORS"
                validInput = True
            except:
                print("Unknown error")
            print("Throw your hand in 3...")
            time.sleep(1)
            print("2..")
            time.sleep(1)
            print("1.")
            time.sleep(1)
            battle(uVar, rVar, uStr, rStr)
        contVar1 = input('Press enter to start again or press x to exit\n')
        if (contVar1 == 'X' or contVar1 == 'x'):
            breakPoint = True
        else:
            breakPoint = False
main()

 

Share this post


Link to post
Share on other sites
Quote

def main():
    import time
    import random


    bothand = random.randint(0,3)
    userHand = input("what do you pick rock, paper, scissors")
    print("You pick " + userHand)

    if bothand == 1:
        print("bot chose rock")
    elif bothand == 2:
        print("bot chose paper")
    elif bothand == 3:
        print("bot chose scissors")

    if ((userHand == 'rock') and  bothand == '1'):
            print ('you tie')
    elif ((userHand == 'rock') and bothand == '2'):
            print ('you lose')
    elif ((userHand == 'rock') and bothand == '3'):
            print ('you win')
    elif ((userHand == 'paper') and bothand == '1'):
            print('you win')
    elif ((userHand == 'paper') and bothand == '2'):
            print("you tie")
    elif ((userHand == 'paper') and bothand == '3'):
            print("you lose")
    elif ((userHand == 'scizzors') and bothand == '1'):
            print("you lose")
    elif ((userHand == 'scizzors') and bothand == '2'):
            print("you win")
    elif ((userHand == 'scizzors') and bothand == '3'):
            print("you tie")
    else:
            print("invalid input")



main()

while (1 == 1):
    main()

 

 

something is wrong with the win lose or tie thing. Could you please help me!! special thanks

Share this post


Link to post
Share on other sites
7 hours ago, Joshua said:

something is wrong with the win lose or tie thing. Could you please help me!! special thanks

I know what you meant for this line to do, but what does it actually do?

bothand = random.randint(0,3)

 

Share this post


Link to post
Share on other sites
On 8/22/2017 at 11:38 PM, Joshua said:

 

something is wrong with the win lose or tie thing. Could you please help me!! special thanks

I fixed your code. you put integer as a word when using the ' symbol. all you had to do was take them off.. lol

 

 

def main():
    import time
    import random


    bothand = random.randint(1,3)
    userHand = input("what do you pick rock, paper, scissors")
    print("You pick " + userHand)

    if bothand == 1:
        print("bot chose rock")
    elif bothand == 2:
        print("bot chose paper")
    elif bothand == 3:
        print("bot chose scissors")

    if ((userHand == 'rock') and  bothand == 1):
            print ('you tie')
    elif ((userHand == 'rock') and bothand == 2):
            print ('you lose')
    elif ((userHand == 'rock') and bothand == 3):
            print ('you win')
    elif ((userHand == 'paper') and bothand == 1):
            print('you win')
    elif ((userHand == 'paper') and bothand == 2):
            print("you tie")
    elif ((userHand == 'paper') and bothand == 3):
            print("you lose")
    elif ((userHand == 'scissors') and bothand == 1):
            print("you lose")
    elif ((userHand == 'scissors') and bothand == 2):
            print("you win")
    elif ((userHand == 'scissors') and bothand == 3):
            print("you tie")
    else:
            print("invalid input")



main()

while (1 == 1):
    main()

Share this post


Link to post
Share on other sites

my upgraded version of the game.

def main():
    import random
    botHand = random.randint(1, 3)
    userHand = input("Pick rock, paper or scissors ")
    print(username,'picked', userHand)
    if (botHand == 1):
        print("Computer picks scissors")
    elif (botHand == 2):
        print("Computer picks rock")
    elif (botHand == 3):
        print("Computer picks paper")
    import time
    time.sleep(1)
    if ((userHand == 'rock' or userHand == 'Rock') and botHand == 1):
        print(username, 'Won!')
    elif ((userHand == 'rock' or userHand == 'Rock') and botHand == 2):
        print('Game Tied!')
    elif ((userHand == 'rock' or userHand == 'Rock') and botHand == 3):
        print(username, 'Lost!')
    elif ((userHand == 'paper' or userHand == 'Paper') and botHand == 1):
        print(username, 'Lost!')
    elif ((userHand == 'paper' or userHand == 'Paper') and botHand == 2):
        print(username, 'Won!')
    elif ((userHand == 'paper' or userHand == 'Paper') and botHand == 3):
        print('Game Tied!')
    elif ((userHand == 'scissors' or userHand == 'Scissors') and botHand == 1):
        print('Game Tied!')
    elif ((userHand == 'scissors' or userHand == 'Scissors') and botHand == 2):
        print(username, 'Lost!')
    elif ((userHand == 'scissors' or userHand == 'Scissors') and botHand == 3):
        print(username, 'Won!')
    else:
        print('You can only pick [ rock ], [ paper ], or [ scissors ]')
        main()
a = 1
username = 'As2C4HaaH21fg3V332Zsd'
while (a < 2 or username == 'As2C4HaaH21fg3V332Zsd'):
    try:
        if (username == 'As2C4HaaH21fg3V332Zsd'):
            username = input("what is your name?")
        if (username != 'As2C4HaaH21fg3V332Zsd'):
            main()
        a = int(input('[Enter 1 For New Round] [Enter 2 For Last Round] [Enter 3 To Exit..]'))
        if (a == 1):
            print('Starting round')
            main()
        elif (a == 2):
            main()
        elif (a == 3):
            exit()
        elif (a != 3):
            a = int(input('Exit Game? [1]-Go Back  [Other]-Exit Game'))
        else:
            main()

    except:
        while (a != 1 and a!= 2 and a != 3):
            try:
                a = int(input('Game Will Now Exit..'))
            finally:
                exit()
                while (a == 1):
                    try:
                        if (a == 1 and username !='none'):
                            main()
                    finally:
                        main()

Share this post


Link to post
Share on other sites

Ok.. sat down and thought about this 'rps' program and came up with a different approach... (… which is the best part of programming, there is no “one way”... you got the 'inputs'... you know what the 'output' requirements are... and everything in the middle is your playground.. ;)

So.. for the Object Oriented Programming version of 'rps' the two areas that I focused on were:
1. User input... when 'we' plug in a value, we know that it's going to look like... when we rely on some 'other' human... there is no telling what the input is going to turn out to be. i.e. (“paper”,”Paper”,”PaPeR”,”   pAaEr   “, etc). So I wanted to change 'whatever' they entered into a single word with an initial capital letter and remove any spaces that may in front, impeded, or trailing.
2. The “runGame” section... was a massive “if, elif, elif, elif, elif...” making multiple 'test' within each stage... the successful result of which will define “self.winner” with the appropriate result.  In 'this' programming example there are 9 conditions to check for... and, you can count on “Murphy” to have the majority of the conditions (not really... but it may feel like it) where “self.playerHand”=”scissors'”... and... “self.botHand”=”3”.  You know why?... because that test is at the bottom of the list and you will have had to previously test “eight times” in vain before you get to the test to give you the correct 'answer' (… lot of CPU cycles...)

To try to address this issue I added code in the runGame section which does the 'sanitation' of the user's input (self.playerHand) ... (probably should have created a 'new' value other than using self.playerHand... but it works). 


Within the __init__ section... I have added a dictionary called “combinations” with each possible 'index' defined along with it's 'result'.

Within the runGame section... I have removed the massive if-elif block and replaced it with a call to the dictionary using the 'index', which is the user input plus botHand appended to it. So if the user enters “rock” and self.botHand=3... then the index will contain the string “Rock3”.  If the user input is valid (rock, paper, scissors in some form) then I will be given the answer by the dictionary... if however, the user input is in the weeds (“xyzzy”), then it will create an exception and branch to “self.winner = 'INVALID input, try again'”

Constructive criticisms always welcome...

class Game:
    def __init__(self, newPlayerName):
        self.playerName = newPlayerName
        self.playerHand = "NA"
        self.botHand = "NA"
        self.winner = "No winner yet"
        self.combinations = {'Rock1':'You win','Rock2':'You tie','Rock3':'You lose',             #rock combos
                          'Paper1':'You lose','Paper2':'You win','Paper3':'You tie',                            #paper combos
                          'Scissors1':'You tie','Scissors2':'You lose','Scissors3':'You win'}            #scissor combs
        print("New instance of game class for " + self.playerName)
        
    def runGame(self):
        self.playerHand = str.title(str.replace(self.playerHand," ",""))    #strip leading/trailing spaces
                                                                                                                     # plus 1st character a Cap
        try:
            self.winner = self.combinations[self.playerHand + str(self.botHand)]   #if input valid, winner set
        except:
            self.winner = 'INVALID input, try again'    #something other than paper, rock, scissors entered
            
def main():
    myGame = Game('Kevin')
    print(myGame.playerName)
    print(myGame.playerHand)
    print(myGame.botHand)
    print(myGame.winner)
    myGame.playerHand = 'paper'
    myGame.botHand = 1 #Scissors
    myGame.runGame()
    print(myGame.winner)
    otherGame = Game('Zibzo')
    otherGame.runGame()
    print(otherGame.winner)
main()
 

Share this post


Link to post
Share on other sites

Here is my version of the game. Please tell me what you think / how I can improve it. I also want to make it so that if you win 2 of 3 times, its says you won the game. I tried doing it but couldn't get it to work.

import random
import time
def main():
    cont = True
    while cont == True:
        def opponentChoice(oppChoice):
            if oppChoice == 0:
                print('Rock')
            elif oppChoice == 1:
                print('Paper')
            elif oppChoice == 2:
                print('Scissors')

        def outcomes(plyrChoice):
            """All the possible combinations"""
            if plyrChoice == 'r' and oppChoice == 0:
                print('Stalemate!')
            elif plyrChoice == 'r' and oppChoice == 1:
                print('You lose!')
            elif plyrChoice == 'r' and oppChoice == 2:
                print('You win!')

            if plyrChoice == 'p' and oppChoice == 0:
                print('You win!')
            elif plyrChoice == 'p' and oppChoice == 1:
                print('Stalemate!')
            elif plyrChoice == 'p' and oppChoice == 2:
                print('You lose!')

            if plyrChoice == 's' and oppChoice == 0:
                print('You lose!')
            elif plyrChoice == 's' and oppChoice == 1:
                print('You win!')
            elif plyrChoice == 's' and oppChoice == 2:
                print('Stalemate!')

        for i in range(3):
            plyrChoice = input('"r" for rock, "p" for paper, or "s" for scissors')
            oppChoice = random.randint(0, 2)
            print('1...')
            time.sleep(0.5)
            print('2...')
            time.sleep(0.5)
            opponentChoice(oppChoice)
            outcomes(plyrChoice)
            time.sleep(1)

        y_n = input('Continue? "y" for yes, "n" for no')
        if y_n != "y":
            break
main()

Share this post


Link to post
Share on other sites

Here's my updated version

import random
import time


def opponentChoice(oppChoice):
    """Determines the opponents move"""
    if oppChoice == 0:
        print('Rock')
    elif oppChoice == 1:
        print('Paper')
    elif oppChoice == 2:
        print('Scissors')


def outcomes(plyrChoice, oppChoice):
    """All the possible outcomes"""
    if plyrChoice == 'r' and oppChoice == 0:
        print('Stalemate!')
    elif plyrChoice == 'r' and oppChoice == 1:
        print('You lose!')
    elif plyrChoice == 'r' and oppChoice == 2:
        print('You win!')

    if plyrChoice == 'p' and oppChoice == 0:
        print('You win!')
    elif plyrChoice == 'p' and oppChoice == 1:
        print('Stalemate!')
    elif plyrChoice == 'p' and oppChoice == 2:
        print('You lose!')

    if plyrChoice == 's' and oppChoice == 0:
        print('You lose!')
    elif plyrChoice == 's' and oppChoice == 1:
        print('You win!')
    elif plyrChoice == 's' and oppChoice == 2:
        print('Stalemate!')


def main():
    """How the game runs"""
    for i in range(3):
        validInput = False
        while not validInput:
            plyrChoice = input('"r" for rock, "p" for paper, or "s" for scissors')
            if plyrChoice == 'r' or plyrChoice == 'p' or plyrChoice == 's':
                validInput = True
            else:
                print('Invalid input. Try again')
                continue
        oppChoice = random.randint(0, 2)
        print('1...')
        time.sleep(0.5)
        print('2...')
        time.sleep(0.5)
        opponentChoice(oppChoice)
        outcomes(plyrChoice, oppChoice)
        time.sleep(1)


def run():
    """Runs the game once and then again if the user enters 'y' or exits for any other value"""
    cont = True
    while cont == True:
        main()
        y_n = input('Continue? "y" for yes, "n" for no')
        if y_n != "y":
            return


run()

Share this post


Link to post
Share on other sites

Hi guys here's my version of the code it was a really fun challenge if anyone has some tips or improvements id really appreciate any advice. 

 

import random
import time


cpu = (random.randint(0, 2))


def computer():
    # determine computer's move
    if (cpu == 0):
        print('Computer picked rock')
    elif (cpu == 1):
        print('Computer picked Paper')
    else:
        print('Computer picked scissors')


def rps():
    # print rock, paper, scissors
    print('rock')
    time.sleep(1)
    print('paper')
    time.sleep(1)
    print('scissors')
    time.sleep(1)


def wl(human):
    # determine a win, loss or tie
    if (human == 'rock' and cpu == 0) or (human == 'paper' and cpu == 1) or (human == 'scissors' and cpu == 2):
        print('You tie.')
    elif (human == 'rock' and cpu == 1) or (human == 'paper' and cpu == 2) or (human == 'scissors' and cpu == 0):
        print('You lose.')
    elif (human == 'rock' and cpu == 2) or (human == 'paper' and cpu == 0) or (human == 'scissors' and cpu == 1):
        print('You Win.')
    else:
        print('INVALID input, try again')


def game():
    # run the game 
    print('rock, paper, scissors.')
    human = input('Make your selection: ')
    time.sleep(1)
    print('You picked: ' + human)
    time.sleep(1)
    rps()
    time.sleep(0.5)
    computer()
    wl(human)

def main():
    # main program loop with exit
    cont = False
    while not cont:
        game()
        playAgain = input('Play again(y/n)? ')
        if (playAgain != 'y'):
            cont = True
            break
        else:
            continue

main()

 

Share this post


Link to post
Share on other sites

This is what I came up with...  It's a little dirty still, and I seem to have taken a slightly different approach than some others, but it seems to be working:

 

 

#Import Time and Random
import time
import random

print("Let's play 'Rock! Paper! Scissor!'")
print("")

def main():
    PlayAgain = True
    while PlayAgain:
        # Declare variable for computers choice
        opponent = random.choice(['Rock', 'Paper', 'Scissor'])
        #Player chooses rock, paper, or scissors to compete against computer
        #Get user input
        validInput = False
        while not validInput:
            try:
                Player = int(input("Press 1 for 'Rock', 2 for 'Paper', or 3 for 'Scissor': "))
                validInput = True
            except:
                print("Invalid input. Try Again")

        #Determine outcome of game
        if(Player == 1 and opponent == 'Rock'):
            print("You chose: Rock")
            print("Your opponent chose: " + opponent)
            print("You and your opponent both chose rock. Tie!")
        elif(Player == 1 and opponent == 'Paper'):
            print("You chose: Rock")
            print("Your opponent chose: " + opponent)
            print("Paper covers rock! You lose!")
        elif(Player == 1 and opponent == 'Scissor'):
            print("You chose: Rock")
            print("Your opponent chose: " + opponent)
            print("Rock breaks scissor! You win!")
        elif(Player == 2 and opponent == 'Rock'):
            print("You chose: Paper")
            print("Your opponent chose: " + opponent)
            print("Paper covers rock! You win!")
        elif(Player == 2 and opponent == 'Paper'):
            print("You chose: Paper")
            print("Your opponent chose: " + opponent)
            print("You and your opponent both chose paper. Tie!")
        elif(Player == 2 and opponent == 'Scissor'):
            print("You chose: Paper")
            print("Your opponent chose: " + opponent)
            print("Scissor cuts paper! You lose!")
        elif(Player == 3 and opponent == 'Rock'):
            print("You chose: Scissor")
            print("Your opponent chose: " + opponent)
            print("Rock breaks scissor! You lose!")
        elif(Player == 3 and opponent == 'Paper'):
            print("You chose: Scissor")
            print("Your opponent chose: " + opponent)
            print("Scissor cuts paper! You win!")
        elif(Player == 3 and opponent == 'Scissor'):
            print("You chose: Scissor")
            print("Your opponent chose: " + opponent)
            print("You and your opponent both chose scissor. Tie!")
        else:
            print("Invalid entry, please try again")



        #Play again Y/N
        again = input("Would you like to play again (Y/N): ")
        print("")
        if(again != 'Y' and again != 'y'):
            PlayAgain = True

            break
        else:
            continue
        print("Thanks for playing 'Rock, Paper, Scissor!'")



main()

 

Share this post


Link to post
Share on other sites

Never done programming before. I became interested in Python and started watching kjdElectronics tutorials.

I would appreciate any comments or suggestions !!!

 

import random
import time

# computer random input is assigned the object
def computer(comp_input):
    time.sleep(1)
    if(comp_input == 1):
        print('computer selected - rock')
    elif(comp_input == 2):
        print('computer selected - paper')
    elif(comp_input == 3):
        print('computer selected - scissors')

# processing the result of computer and user input
def operation(comp_input,user_input):
    if ((comp_input == 1 and user_input == 'rock') or (comp_input == 2 and user_input == 'paper') or (comp_input == 3 and user_input == 'scissors')):
        computer(comp_input)
        time.sleep(1)
        print('its a TIE !!')
    elif ((comp_input == 2 and user_input == 'rock') or (comp_input == 3 and user_input == 'paper') or (comp_input == 1 and user_input == 'scissors')):
        computer(comp_input)
        time.sleep(1)
        print('LOSER !!')
    elif ((comp_input == 3 and user_input == 'rock') or (comp_input == 1 and user_input == 'paper') or (comp_input == 2 and user_input == 'scissors')):
        computer(comp_input)
        time.sleep(1)
        print('WINNER !!')
    else:
        print('invalid input. try again')
        time.sleep(1)
        main()

# select rock, paper or scissors
def main():
    restart = True
    while restart:
        comp_input = random.randint(1, 3)
        user_input = input('select one.. rock, paper or scissors: ')
        operation(comp_input,user_input)
        time.sleep(1)
        again = input('do you want to play another game? (y/n): ')
        if(again == 'y'):
            restart = True
        else:
            time.sleep(1)
            print('i will miss you. bye !')
            time.sleep(1)
            restart = False

main()

 

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...