Random Number stone scissors cloth game
This problem is due to a problem in Ptyhon core programming:
Random Numbers. design a "rock, paper, scissors" game, sometimes called "Rochambeau," a game you may have played as a kid. here are the rules. at the same time, using specified hand motions, both you and your opponent have to pick from one of the following: rock, paper, or scissors. the winner is determined by these rules, which form some-what of a fun paradox:
(A) the paper covers the rock,
(B) the rock breaks the scissors,
(C) the scissors cut the paper. In your computerized version,
The user enters his/her guess, the computer randomly chooses, and your program shocould indicate a winner or draw/tie. Note: The most algorithmic solutions use the fewest number of if statements.
The last sentence mentioned that the best algorithm should use as few if statements as possible.
So when solving this problem, I am thinking about how to sum up the relationship between the three options. The user has three options, and the computer has three options. If they are compared with each other, they should be compared nine times. However, the computer cannot identify the winner of the three options. Therefore, it is necessary to convert the stone scissors cloth into symbols that can be recognized by computers, and then use efficient algorithms to solve this problem.
(1) The function should have two parameters: user and computer respectively.
(2) map options to numbers respectively, so that the computer can determine the result by comparing the number size.
(3) determine the absolute value of the number corresponding to the two options, and then use min () and max () to implement it easily.
Ptyhon code:
# -*- coding: utf-8 -*-import randomdef Rochambeau(num1, num2): num1 = int(num1) dic = {1:'stone', 2:'shears', 3:'cloth'} re = {num1:'user', num2:'computer'} if num1 == num2: return 'the same choose:' + dic[num1] elif abs(num1 - num2) == 1: return 'your choice is: ' + dic[num1] + '\n' \ + 'computer\'s choice is:' + dic[num2] + '\n' \ 'the winner is ' + re[min(num1, num2)] else: return 'your choice is: ' + dic[num1] + '\n' \ + 'computer//s choice is:' + dic[num2] + '\n' \ 'the winner is ' + re[max(num1, num2)] print Rochambeau(raw_input("""Enter the number of choice: 1 -> stone 2 -> shears 3 -> cloth"""), random.randint(1, 3))
Note: Both dic And re dictionaries have their respective functions. I am not very good at English, so the element naming is somewhat casual. I still hope to understand the code and gradually improve it later.