Tuesday, September 21, 2010

Rock, Paper, Scissors, Pythons....?

Here's assignment for Logic turned Python. We were to describe the logic for an easy childhood game and I chose Rock, Paper, Scissors.


import random
choices = ['Rock','Paper','Scissors']
oppChoice=0
playerChoice=0

def rock(oppChoice):
    if oppChoice == 'Rock':
            print("It's a tie!")
    if oppChoice == 'Paper':
            print("You Lose! Paper covers Rock!")
    if oppChoice == 'Scissors':
            print("You Win! Rock smashes Scissors!")
          
def paper(oppChoice):
    if oppChoice == 'Paper':
            print("It's a tie!")
    if oppChoice == 'Rock':
            print("You Win! Paper covers Rock!")
    if oppChoice == 'Scissors':
            print("You Lose! Scissors cuts Paper!")
           
def scissors(oppChoice):
    if oppChoice == 'Scissors':
            print("It's a tie!")
    if oppChoice == 'Paper':
            print("You lose! Paper covers Rock!")
    if oppChoice == 'Rock':
            print("You Lose! Rock smashes Scissors!")
           
def choice(playerChoice,oppChoice):
    if playerChoice==1:
        rock(oppChoice)
    if playerChoice==2:
        paper(oppChoice)
    if playerChoice==3:
        scissors(oppChoice)
   
def RPSgame():
    oppChoice = random.choice(choices)
    playerChoice = input("Make your selection:\n[1] Rock\n[2] Paper\n[3] Scissors\n...")
    playerChoice=int(playerChoice)
    if playerChoice not in(1,2,3):
        print("Please input 1, 2, or 3 only!")
        RPSgame()
    print('You Chose', choices[playerChoice-1])
    print('Your Opponent Chose...',oppChoice)
    choice(playerChoice,oppChoice)
    playAgain = input("Try again? (Y,N)")
    if playAgain== 'Y' or 'y':
        RPSgame()
    else: return

The first 44 lines are the game's logic, just telling you if you won or lost based on your choice vs. opponent's choice. The "main" code is RPSgame() which, if you ran this code, is all you would have to type to start the game. I tried to account for incorrect input (not using 1,2, or 3 for initial input and disregard for capitalization for "y" to continue playing). The only thing in here we haven't covered thus far on the GeekSpot Blog is the use of lists. I will go into that more in depth later this week when I have more time. In the mean time, I'll leave it at:

Lists are built in brackets: []
Lists are mutable: They can be changed... added to, taken away from...
List elements are numbered starting from 0: choice[0] thus equals Rock.

There is much more to lists, lists can be used for many things and have much potential in your programming. Thanks for stopping by! If anyone has suggestions, comments or concerns about the above code, please feel free to leave a post or shoot me an email.

7 comments: