Friday, May 11, 2012

Python: Rock, Paper, Scissor Game Source Code

I implemented a simple game of rock, paper, scissors game in python as a after school project. The game itself is really simple, not that I need to. But I pay a quick visit to wiki's page, and read through it. The original program has a long list of if statement, but as I was thinking through it, it comes to me quickly, that you actually does not need to have that many control statement, just three is enough. Since there is only three possible outcome.

The logic goes like this:
  1. If you and the computer's outcome (choice) is the same, then you are tie. Regardless of what kind of choice you or your computer made. A tie is a tie.
  2. Then there is 3 possible ways you can win. 
    1. You are Rock, computer is Scissors
    2. You are Paper, computer is Rock
    3. You are Scissors, computer is Paper
  3. If you didn't tie, and you didn't win, your only option is to lose the game. 
You can easily put a while (myResponse is not 'quit') loop, and have this game goes on forever. Below is the source code for the game. I found out I win quite often... for what ever reason.

# Hunter College CSCI133 Python Project
# Rock Paper Scissors Game Source code in Python
# Implemented by George Chan, 5/2/2012
# Email: ygchan89@gmail.com
# A simple game to play rock, paper, scissors with the computer

import random
# Create the list of of choices, which stored at string
gameChoices = ['rock', 'paper', 'scissors']
# Our default ready flag is false
ready = False

print('rock, paper, scissors Game!')
while (not ready):
    myResponse = raw_input('Please enter which option you are going with: ')
    myResponse = myResponse.lower()
    # We will change our flag to true and break out of the loop
    # if and only if the input is equiv to one of our choices
    if (myResponse in gameChoices):
        ready = True

# Randomly pick a choice from the list gameChoices
computerResponse = random.choice(gameChoices)
print('Computer picked:', computerResponse)

# There are three possible condition of the game, either you tie,
# with the computer or you win, else you lose
# Tie condition is when you and computer choice is the same 
if (myResponse == computerResponse):
    print('Tie Game')
# Win condition is the below three possible one
elif (myResponse == 'rock' and computerResponse == 'scissors' or
      myResponse == 'paper' and computerResponse == 'rock' or
      myResponse == 'scissors' and computerResponse == 'paper'):
    print('You win')
# If you didn't tie, didn't win, then you must lose
else:
    print('You lose!')
Sample Output:
rock, paper, scissors Game!
Please enter which option you are going with: rock
('Computer picked:', 'rock')
Tie Game

rock, paper, scissors Game!
Please enter which option you are going with: rock
('Computer picked:', 'scissors')
You win

No comments:

Post a Comment