An Introduction to Interactive Programming in Python (Part 1) -- Week 2_3 练习
Mini-project description - Rock-paper-scissors-lizard-Spock
Rock-paper-scissors is a hand game that is played by two people. The players count to three in unison and simultaneously "throw” one of three hand signals that correspond to rock, paper or scissors. The winner is determined by the rules:
Rock smashes scissors
Scissors cuts paper
Paper covers rock
Rock-paper-scissors is a surprisingly popular game that many people play seriously (see the Wikipedia article for details). Due to the fact that a tie happens around 1/3 of the time, several variants of Rock-Paper-Scissors exist that include more choices to make ties less likely.
Rock-paper-scissors-lizard-Spock (RPSLS) is a variant of Rock-paper-scissors that allows five choices. Each choice wins against two other choices, loses against two other choices and ties against itself. Much of RPSLS's popularity is that it has been featured in 3 episodes of the TV series "The Big Bang Theory". The Wikipedia entry for RPSLS gives the complete description of the details of the game.
In our first mini-project, we will build a Python function rpsls(name)
that takes as input the string name, which is one of "rock", "paper", "scissors", "lizard", or "Spock". The function then simulates playing a round of Rock-paper-scissors-lizard-Spock by generating its own random choice from these alternatives and then determining the winner using a simple rule that we will next describe.
While Rock-paper-scissor-lizard-Spock has a set of ten rules that logically determine who wins a round of RPSLS, coding up these rules would require a large number \((5*5=25)\) of if/elif/else
clauses in your mini-project code. A simpler method for determining the winner is to assign each of the five choices a number:
- 0 — rock
- 1 — Spock
- 2 — paper
- 3 — lizard
- 4 — scissors
In this expanded list, each choice wins against the preceding two choices and loses against the following two choices (if rock and scissors are thought of as being adjacent using modular arithmetic).
In all of the mini-projects for this class, we will provide a walk through of the steps involved in building your project to aid its development. A template for your mini-project is available here. Please work from this template.
Mini-project development process
Build a helper function
name_to_number(name)
that converts the string name into a number between 0 and 4 as described above. This function should use a sequence of if/elif/else clauses. You can use conditions of the form name == 'paper', etc. to distinguish the cases. To make debugging your code easier, we suggest including a final else clause that catches cases when name does not match any of the five correct input strings and prints an appropriate error message. You can test your implementation ofname_to_number()
using thisname_to_number
testing template. (Also available in the Code Clinic tips thread).Next, you should build a second helper function
number_to_name(number)
that converts a number in the range 0 to 4 into its corresponding name as a string. Again, we suggest including a final else clause that catches cases when number is not in the correct range. You can test your implementation ofnumber_to_name()
using thisnumber_to_name
testing template.Implement the first part of the main function
rpsls(player_choice)
. Print out a blank line (to separate consecutive games) followed by a line with an appropriate message describing the player's choice. Then compute the numberplayer_number
between 0 and 4 corresponding to the player's choice by calling the helper functionname_to_number()
usingplayer_choice
.Implement the second part of
rpsls()
that generates the computer's guess and prints out an appropriate message for that guess. In particular, compute a random numbercomp_number
between 0 and 4 that corresponds to the computer's guess using the functionrandom.randrange()
. We suggest experimenting with randrange in a separate CodeSkulptor window before deciding on how to call it to make sure that you do not accidently generate numbers in the wrong range. Then compute the namecomp_choice
corresponding to the computer's number using the functionnumber_to_name()
and print an appropriate message with the computer's choice to the console.Implement the last part of
rpsls()
that determines and prints out the winner. Specifically, compute the difference between comp_number andplayer_number
taken modulo five. Then write anif/elif/else
statement whose conditions test the various possible values of this difference and then prints an appropriate message concerning the winner. If you have trouble deriving the conditions for the clauses of thisif/elif/else
statement, we suggest reviewing the "RPSLS" video which describes a simple test for determine the winner of RPSLS.
This will be the only mini-project in the class that is not an interactive game. Since we have not yet learned enough to allow you to play the game interactively, you will simply call your rpsls function repeatedly in the program with different player choices. You will see that we have provided five such calls at the bottom of the template. Running your program repeatedly should generate different computer guesses and different winners each time. While you are testing, feel free to modify those calls, but make sure they are restored when you hand in your mini-project, as your peer assessors will expect them to be there.
The output of running your program should have the following form:
Player chooses rock
Computer chooses scissors
Player wins!
Player chooses Spock
Computer chooses lizard
Computer wins!
Player chooses paper
Computer chooses lizard
Computer wins!
Player chooses lizard
Computer chooses scissors
Computer wins!
Player chooses scissors
Computer chooses Spock
Computer wins!
Note that, for this initial mini-project, we will focus only on testing whether your implementation of rpsls()
works correctly on valid input. For more helpful tips on implementing this mini-project, please visit the Code Clinic Tips page for this mini-project.
# python 2.7
import random
names = ["rock", "Spock", "paper", "lizard", "scissors"]
# 辅助函数:名字转数字
def name_to_number(name):
global names
return names.index(name)
# 辅助函数:数字转名字
def number_to_name(number):
global names
return names[number]
# 石头、布、剪刀、蜥蜴、斯波克
# Rock-paper-scissors-lizard-Spock
# 石头 < 斯波克 < 布 < 蜥蜴 < 剪刀
def rpsls(player_choice):
print
player_number = name_to_number(player_choice)
print 'Player chooses %s.' % player_choice
comp_number = random.randrange(5)
comp_choice = number_to_name(comp_number)
print 'Computer chooses %s.' % comp_choice
res = (player_number - comp_number) % 5
if res in [1,2]:
print 'Player wins!'
elif res in [3,4]:
print 'Computer wins!'
elif res == 0:
print 'None wins!'
# test!
print name_to_number("rock")
print name_to_number("paper")
print name_to_number("scissors")
print name_to_number("lizard")
print name_to_number("Spock")
print number_to_name(0)
print number_to_name(1)
print number_to_name(2)
print number_to_name(3)
print number_to_name(4)
rpsls("rock")
rpsls("paper")
rpsls("scissors")
rpsls("lizard")
rpsls("Spock")
An Introduction to Interactive Programming in Python (Part 1) -- Week 2_3 练习的更多相关文章
- An Introduction to Interactive Programming in Python
这是在coursera上面的一门学习pyhton的基础课程,由RICE的四位老师主讲.生动有趣,一共是9周的课程,每一周都会有一个小游戏,经历一遍,对编程会产生很大的兴趣. 所有的程序全部在老师开发的 ...
- Mini-project # 1 - Rock-paper-scissors-___An Introduction to Interactive Programming in Python"RICE"
Mini-project description - Rock-paper-scissors-lizard-Spock Rock-paper-scissors is a hand game that ...
- An Introduction to Interactive Programming in Python (Part 1) -- Week 2_2 练习
#Practice Exercises for Logic and Conditionals # Solve each of the practice exercises below. # 1.Wri ...
- An Introduction to Interactive Programming in Python (Part 1) -- Week 2_1 练习
# Practice Exercises for Functions # Solve each of the practice exercises below. # 1.Write a Python ...
- 【python】An Introduction to Interactive Programming in Python(week two)
This is a note for https://class.coursera.org/interactivepython-005 In week two, I have learned: 1.e ...
- Quiz 6b Question 8————An Introduction to Interactive Programming in Python
Question 8 We can use loops to simulate natural processes over time. Write a program that calcula ...
- Quiz 6b Question 7————An Introduction to Interactive Programming in Python
Question 7 Convert the following English description into code. Initialize n to be 1000. Initiali ...
- Quiz 6a Question 7————An Introduction to Interactive Programming in Python
First, complete the following class definition: class BankAccount: def __init__(self, initial_bal ...
- Mini-project # 4 - "Pong"___An Introduction to Interactive Programming in Python"RICE"
Mini-project #4 - "Pong" In this project, we will build a version of Pong, one of the firs ...
随机推荐
- 《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <五> NSDicionary + NSMutableDictionary
int main(int argc, const char * argv[]) { @autoreleasepool { //字典, 存储的内存不是连续的 用key和value进行对应(键值) //k ...
- 多线程技术 NSThread & NSOperation & GCD
多线程:在iOS开发中,用到多线程的处理问题的时候有很多,比如异步下载数据时刷新界面等等. 引入多线程来处理问题的关键就是,基于多线程可以使界面更加流畅,防止界面假死. 界面假死:比如你单击一个按钮来 ...
- socket服务器开发中的SO_REUSEADDR选项与让人心烦的TIME_WAIT
1 发现问题 我在开发一个socket服务器程序并反复调试的时候,发现了一个让人无比心烦的情况:每次kill掉该服务器进程并重新启动的时候,都会出现bind错误:error:98,Address al ...
- linux 2>&1
2>&1就是用来将标准错误2重定向到标准输出1中的.此处1前面的&就是为了让bash将1解释成标准输出而不是文件1.至于最后一个&,则是让bash在后台执行 例如:/us ...
- Node创建TCP聊天
//创建新的tcp服务器var net = require('net');var chatServer = net.createServer()chatServer.on('connection',f ...
- Python Backup Files
近来书写 Python 脚本进行替换以前的 shell 脚本,发现 Python 优于 shell 的最直观的一点Python 结构明了,可读性高(本人认为)在此做一些记录 本次记录利用 Python ...
- 关于点击ztree的节点将页面生成到easyui的新增选项卡(easyui-tabs)时,总是在浏览器中生成一个新的页面的问题
最近的项目中用到了easyui,还有ztree菜单.在这里将我遇到的一些问题写出来算是做个笔记吧. 这是我头一次在博客园里分享代码,我的处女作,写的不好的地方还望各位见谅! 由于很久没有写过前台的东西 ...
- MySQL中EXPLAIN的解释
EXPLAIN是查看MySQL优化器如何决定执行查询的主要方法,这个功能具有局限性,以为它并总是会说出真相,但是却可以获得最好信息. 学会解释EXPLAIN,你就会了解MySQL优化器是如何工作,你才 ...
- Linux学习之二——档案与目录的属性和权限
一.属性和权限的基本概念 Linux一般将档案可存取的身份分为三个类别,分别是 owner/group/others,这三种身份各有 read/write/execute 等权限. 所有的系统上的账号 ...
- atomic, spinlock and mutex性能比较
我非常好奇于不同同步原理的性能,于是对atomic, spinlock和mutex做了如下实验来比较: 1. 无同步的情况 #include <future> #include <i ...