Mini-project # 1 - Rock-paper-scissors-lizard-Spock
之前学过learn programming everybody,感觉水水的。。这门课看起来复杂一点。
python真是一门神奇的语言,喜欢
总体而言没什么难度,跟着他的提示走分分钟就可以搞定。。。
用模运算来判断胜负很机智。
突然想到当初北大校赛还是哪里的那道五行题。。。被自己蠢哭> <
注意一下range的范围是左闭右开的,evaluate peer 的时候发现了很多人范围写成(0, 4)了,这真是一个悲剧。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import random 2 # The key idea of this program is to equate the strings 3 # "rock", "paper", "scissors", "lizard", "Spock" to numbers 4 # as follows: 5 # 6 # 0 - rock 7 # 1 - Spock 8 # 2 - paper 9 # 3 - lizard 10 # 4 - scissors 11 12 # helper functions 13 14 def name_to_number(name): 15 # delete the following pass statement and fill in your code below 16 if "rock" == name: 17 return 0; 18 elif "Spock" == name : 19 return 1; 20 elif "paper" == name: 21 return 2; 22 elif "lizard" == name: 23 return 3; 24 elif "scissors" == name: 25 return 4; 26 else: 27 print "wrong name" 28 return -1; 29 30 # convert name to number using if/elif/else 31 # don't forget to return the result! 32 33 34 def number_to_name(number): 35 # delete the following pass statement and fill in your code below 36 if 0 == number: 37 return "rock" 38 elif 1 == number: 39 return "Spock" 40 elif 2 == number: 41 return "paper" 42 elif 3 == number: 43 return "lizard" 44 elif 4 == number: 45 return "scissors" 46 else : 47 print "wrong number" 48 return "" 49 # convert number to a name using if/elif/else 50 # don't forget to return the result! 51 52 53 def rpsls(player_choice): 54 # delete the following pass statement and fill in your code below 55 56 # print a blank line to separate consecutive games 57 print "" 58 # print out the message for the player's choice 59 print "Player chooses", player_choice 60 # convert the player's choice to player_number using the function name_to_number() 61 player_number = name_to_number(player_choice) 62 # compute random guess for comp_number using random.randrange() 63 comp_number = random.randrange(0, 5) 64 # convert comp_number to comp_choice using the function number_to_name() 65 comp_choice = number_to_name(comp_number) 66 # print out the message for computer's choice 67 print "Computer chooses", comp_choice 68 # compute difference of comp_number and player_number modulo five 69 differ = (comp_number - player_number + 5) % 5 70 # use if/elif/else to determine winner, print winner message 71 if player_number == -1: 72 print "error" 73 elif differ == 0: 74 print "Player and computer tie!" 75 elif differ <= 2: 76 print "Computer wins!" 77 else : 78 print "Player wins!" 79 80 # test your code - THESE CALLS MUST BE PRESENT IN YOUR SUBMITTED CODE 81 rpsls("rock") 82 rpsls("Spock") 83 rpsls("paper") 84 rpsls("lizard") 85 rpsls("scissors") 86 87 # always remember to check your completed program against the grading rubric