- What it is
- A rock paper scissors game in Python where the whole thing fits on two lines: one for the win, lose or tie logic and one for the game loop.
- Why I made it
- I wanted to see how much game logic I could squeeze into as little code as possible without breaking it.
- What I did
- I turned the rock, paper, scissors triangle into list positions so a little math decides who wins, then used chained conditional expressions and semicolons to cram it all in.
- How it turned out
- It works, and it's a terrible way to write a game, but finding the Python tricks that made it fit was the whole point. You can play it right on this page.
The details
Play it here
Choose a move or press R, P, or S.
Result
Make a choice to start.
- Wins
- 0
- Ties
- 0
- Losses
- 0
The two lines
Rock paper scissors is a triangle, not a ranking: rock beats scissors, scissors beats paper, and paper beats rock. My code puts the choices in the list [paper, rock, scissors], so they're 0, 1 and 2, and each one beats the item one step ahead of it.
For paper and rock, adding one gives the choice they beat: 0 + 1 is rock, and 1 + 1 is scissors. Scissors wraps around, so subtracting two turns its 2 into paper's 0. If neither test matches, the same number means a tie, and anything else is a loss.
Chained conditional expressions pick the result text, and semicolons keep the whole input loop on one line. It's squished on purpose, but the triangle is the simple idea underneath it.
def get_res(str,c_num): return "You Win!!, I chose " + ["paper", "rock", "scissors"][c_num] if(["paper", "rock", "scissors"].index(str) - 2 == c_num or ["paper", "rock", "scissors"].index(str) + 1 == c_num) else "We Tied, I chose " + ["paper", "rock", "scissors"][c_num] if ["paper", "rock", "scissors"].index(str) == c_num else "You Lose, HaHa!, I chose " + ["paper", "rock", "scissors"][c_num]
choice = ""
while choice.lower() != 'q': choice = input("Rock Paper or Scissors (Q) - Quit: " ).lower(); print(get_res(choice, randint(0, 2)) if choice != 'q' else "Thanks for Playing!!")