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
  1. 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 of name_to_number() using this name_to_number testing template. (Also available in the Code Clinic tips thread).
  2. 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 of number_to_name() using this number_to_name testing template.
  3. 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 number player_number between 0 and 4 corresponding to the player's choice by calling the helper function name_to_number() using player_choice.
  4. 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 number comp_number between 0 and 4 that corresponds to the computer's guess using the function random.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 name comp_choice corresponding to the computer's number using the function number_to_name() and print an appropriate message with the computer's choice to the console.
  5. Implement the last part of rpsls() that determines and prints out the winner. Specifically, compute the difference between comp_number and player_number taken modulo five. Then write an if/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 this if/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")
时间: 2024-09-26 06:12:58

An Introduction to Interactive Programming in Python (Part 1) -- Week 2_3 练习的相关文章

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 function miles_to_feet that takes a parameter miles and # returns the number of feet in miles miles. def miles_to_feet(miles): feet = miles * 5280 ret

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.Write a Python function is_even that takes as input the parameter number (an integer) and # returns True if number is even and False if number is odd. #

An Introduction to Asynchronous Programming and Twisted (1)

之前看的时候, 总觉得思路不是很清晰, 其实Dave在这个模型问题上没有说清楚, 参考同步和异步, 阻塞和非阻塞, Reactor和Proactor 对于阻塞一定是同步的, 但是反之不一定, 对于多线程本质上也是阻塞的方式, 只不过是多个线程一起阻塞, 适用于CPU密集型的任务, 因为事情总要人做的, 无论什么模型都不能让做事情的实际时间变少.  对于非阻塞, 节省的是等待的时间, 所以适用于I/O密集型任务, 因为I/O往往需要等待  Dave谈的异步就是广义的异步, 其实是非阻塞同步  而T

An Introduction to Asynchronous Programming and Twisted (3)

Part 11: Your Poetry is Served A Twisted Poetry Server Now that we've learned so much about writing clients with Twisted, let's turn around and re-implement our poetry server with Twisted too. And thanks to the generality of Twisted's abstractions, i

An Introduction to Asynchronous Programming and Twisted (2)

Part 6: And Then We Took It Higher Part5中的client2.0, 在封装性上已经做的不错, 用户只需要了解和修改PoetryProtocol, PoetryClientFactory就可以完成一个应用. 其实此处, protocol的逻辑就是接受数据, 接受完以后通知factory处理, 这段逻辑已经可以作为common的框架代码, 用户无需改动. 真正需要用户每次根据上下文修改的是, 当数据接受完后的处理逻辑poem_finished(print? sa

再读《Parallel Programming with Python》并作笔记

并发编程,在哪个语言里都属于高端应用,一定得会了才好意思说懂了这门语言. 在工作中用得并不是很多,忘了一些内容,就慢慢看,慢慢补上. 今天一天看了近三分之一(我看外文越来越快了??:)), 实践一下多线程的threading模块. #coding: utf-8 import logging, threading from Queue import Queue logger = logging.getLogger() logger.setLevel(logging.DEBUG) formatter

Machine and Deep Learning with Python

Machine and Deep Learning with Python Education Tutorials and courses Supervised learning superstitions cheat sheet Introduction to Deep Learning with Python How to implement a neural network How to build and run your first deep learning network Neur

Python图形用户界面

tkinter是Python中可用于构建GUI的众多工具集之一. tkinter模块 # 可以使用import tkinter as tk并通过tk.thing去引用其中的内容 from tkinter import * window = Tk() window.mainloop() 以上代码可以显示一个空白的根窗口.可以将其看成是应用程序的最外层容器,创建其他插件(widget)的时候就需要用到它.如果关闭屏幕上的窗口,则相应的窗口对象就会被销毁.所有的应用程序都只有一个主窗口:此外,还可以通

Awesome Python

    Awesome Python      A curated list of awesome Python frameworks, libraries, software and resources. Inspired by awesome-php. Awesome Python Environment Management Package Management Package Repositories Distribution Build Tools Interactive Interp