I want to develop the Chinese morra game in Python, also known as paper, scissor or rock.
I had fun making this game with Scratch as well. Those who want can therefore consult the guide at the link: Chinese morra with Scratch.
How to play chinese morra in Python
First of all, let’s remember the rules of the game!
In this game there are two players and each can therefore choose an object: scissor (f), stone (s) or paper (c).
Stone is represented with the hand in a fist;
Paper is represented with an open hand;
Scissors, on the other hand, is represented with only the index and middle fingers extended.
So who wins? It’s pretty simple:
- The stone beats the scissor (that is, it breaks it);
- The scissor beats the paper (ie the size);
- Finally the paper beats the stone (that is, it wraps it).
If you choose the same item then the score is even.
Implementation of the chinese morra in Python
First we play the computer and for this we use the randint () method, which generates a random integer in a range specified between the round brackets.
For example randint (0,2) generates a random number between 0 and 2.
Now let’s think about arbitrarily associating:
0 stone;
1 scissor;
2 paper;
Clearly we could have decided otherwise!
So let’s set these conditions, just to make it easier to check later:
if computer==0: computer=‘s’
elif computer==1: computer=‘f’ # f stands for scissor
else: computer=‘p’
We then let the user decide what to choose by entering a value: p, s or f.
user = input (‘Enter p for paper, s for stone and f for scissors:’)
Then we do the checks according to the rules explained above.
Here is a possible implementation of the Chinese morra game in Python:
import random
print ('Hello, today let\'s play Chinese morra')
computer = random.randint (0.2)
if computer == 0: computer = 's'
elif computer == 1: computer = 'f'
else: computer = 'p'
user = input('Enter p for paper, s for stone and f for scissors:')
if user! = 's' and user! = 'f' and user! = 'p':
print('The letter does not match anything')
user elif == computer:
print('parity!')
elif user == 's' and computer == 'f' or user == 'f' and computer == 'p' or user == 'p' and computer == 's':
print('You won!')
else:
print('The computer won!')
N. B. In the case of a tie, instead of
elif user == ‘s’ and computer == ‘s’ or user == ‘p’ and computer == ‘p’ or user == ‘f’ and computer == ‘f’
we could simplify and write:
user elif == computer
When we tackle the lists, I will propose another possible solution to the Chinese morra game in Python.
Some useful links
How to find the maximum of N numbers