这道题是EDX上的课程:MITx: 6.00.1x Introduction to Computer Science and Programming Using Python
第三周的作业题,是猜单词游戏,应该大家都玩过,可以参考下维基百科:hangman, 当然也可以看课程作业题的详细说明,会更加清楚:

A WORDGAME: HANGMAN

Note: Do not be intimidated by this problem! It's actually easier than it looks. We will 'scaffold' this problem, guiding you through the creation of helper functions before you implement the actual game.

For this problem, you will implement a variation of the classic wordgame Hangman. For those of you who are unfamiliar with the rules, you may read all about it here. In this problem, the second player will always be the computer, who will be picking a word at random.

In this problem, you will implement a function, called hangman, that will start up and carry out an interactive Hangman game between a player and the computer. Before we get to this function, we'll first implement a few helper functions to get you going.

For this problem, you will need the code files ps3_hangman.py and words.txt. Right-click on each and hit "Save Link As". Be sure to save them in same directory. Open and run the file ps3_hangman.py without making any modifications to it, in order to ensure that everything is set up correctly. By "open and run" we mean do the following:

  • Go to Canopy. From the File menu, choose "Open".
  • Find the file ps3_hangman.py and choose it.
  • The template ps3_hangman.py file should now be open in Canopy. Click on it. From the Run menu, choose "Run File" (or simply hit Ctrl + R).

The code we have given you loads in a list of words from a file. If everything is working okay, after a small delay, you should see the following printed out:


Loading word list from file...
55909 words loaded.

If you see an IOError instead (e.g., "No such file or directory"), you should change the value of theWORDLIST_FILENAME constant (defined near the top of the file) to the complete pathname for the filewords.txt (This will vary based on where you saved the file). Windows users, change the backslashes to forward slashes, like below.

For example, if you saved ps3_hangman.py and words.txt in the directory "C:/Users/Ana/" change the line:

WORDLIST_FILENAME = "words.txt"  to something like

WORDLIST_FILENAME = "C:/Users/Ana/words.txt"

This folder will vary depending on where you saved the files.

The file ps3_hangman.py has a number of already implemented functions you can use while writing up your solution. You can ignore the code between the following comments, though you should read and understand how to use each helper function by reading the docstrings:

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)...
# (end of helper code)
# -----------------------------------

You will want to do all of your coding for this problem within this file as well because you will be writing a program that depends on each function you write.

Requirements

Here are the requirements for your game:

  1. The computer must select a word at random from the list of available words that was provided inwords.txt. The functions for loading the word list and selecting a random word have already been provided for you in ps3_hangman.py.

  2. The game must be interactive; the flow of the game should go as follows:

    • At the start of the game, let the user know how many letters the computer's word contains.

    • Ask the user to supply one guess (i.e. letter) per round.

    • The user should receive feedback immediately after each guess about whether their guess appears in the computer's word.

    • After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed.

  3. Some additional rules of the game:
    • A user is allowed 8 guesses. Make sure to remind the user of how many guesses s/he has left after each round. Assume that players will only ever submit one character at a time (A-Z).

    • A user loses a guess only when s/he guesses incorrectly.

    • If the user guesses the same letter twice, do not take away a guess - instead, print a message letting them know they've already guessed that letter and ask them to try again.

    • The game should end when the user constructs the full word or runs out of guesses. If the player runs out of guesses (s/he "loses"), reveal the word to the user when the game ends.

本题为了防止初学者不会设计整个游戏,所以就把游戏整个都设计好了,只是留了一些function来让我们写

第一个函数是isWordGuessed,用来判断是不是该function已经猜对,这题思路就是遍历secretWord,只要其中的每个字符都出现在lettersGuessed中,即可,代码如下:
def isWordGuessed(secretWord, lettersGuessed):'''secretWord: string, the word the user is guessinglettersGuessed: list, what letters have been guessed so farreturns: boolean, True if all the letters of secretWord are in lettersGuessed;False otherwise'''# FILL IN YOUR CODE HERE...for i in secretWord:if (i in lettersGuessed) == False:return Falsereturn True

第二个函数是打印出现在玩家的猜想,举个例子:

>>> secretWord = 'apple'
>>> lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
>>> print getGuessedWord(secretWord, lettersGuessed)
'_ pp_ e'

思路就是遍历secretWord,如果在letterGuessed中出线过,则打印该字母,否则,打印"-"

代码如下:
def getGuessedWord(secretWord, lettersGuessed):'''secretWord: string, the word the user is guessinglettersGuessed: list, what letters have been guessed so farreturns: string, comprised of letters and underscores that representswhat letters in secretWord have been guessed so far.'''# FILL IN YOUR CODE HERE...guessWord = ""for i in secretWord:if (i in lettersGuessed) == True:guessWord += ielse:guessWord += "_"return guessWord

第三个函数是打印出所有可以猜的字符,即,除了已经猜过的以外,剩下的都可以猜,

这题很直观,代码如下:
def getAvailableLetters(lettersGuessed):'''lettersGuessed: list, what letters have been guessed so farreturns: string, comprised of letters that represents what letters have notyet been guessed.'''# FILL IN YOUR CODE HERE...retStr = ""for i in string.ascii_lowercase:if (i in lettersGuessed) == False:retStr += ireturn retStr

第四个,也是最重要的一个函数,就是将上面几个函数结合起来,进行游戏,根据游戏规则,很容易就能写出,这里就不废话,代码比废话更清楚:

def hangman(secretWord):'''secretWord: string, the secret word to guess.Starts up an interactive game of Hangman.* At the start of the game, let the user know how many letters the secretWord contains.* Ask the user to supply one guess (i.e. letter) per round.* The user should receive feedback immediately after each guess about whether their guess appears in the computers word.* After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed.Follows the other limitations detailed in the problem write-up.'''# FILL IN YOUR CODE HERE...print "Welcome to the game, Hangman!"print "I am thinking of a word that is " + str(len(secretWord)) + " long."print "-------------"chance = 8lettersGuessed = []while (chance > 0 and isWordGuessed(secretWord, lettersGuessed) == False):print "You have " + str(chance) + " guesses left."print "Available letters: ",print getAvailableLetters(lettersGuessed)ch = raw_input("Please guess a letter: ")ch = ch.lower()if ch in lettersGuessed:print "Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed)else:lettersGuessed.append(ch)if ch in secretWord:print "Good guess: " + getGuessedWord(secretWord, lettersGuessed)else:print "Oops! That letter is not in my word: " + getGuessedWord(secretWord, lettersGuessed)chance -= 1print "-------------"if isWordGuessed(secretWord, lettersGuessed):print "Congratulations, you won!"else:print "Sorry, you ran out of guesses. The word was else."
最后上传一下完整的代码吧,这样就是可以直接运行的代码,无聊的话可以玩一玩:
# 6.00 Problem Set 3
#
# Hangman game
## -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)import random
import stringWORDLIST_FILENAME = "words.txt"def loadWords():"""Returns a list of valid words. Words are strings of lowercase letters.Depending on the size of the word list, this function maytake a while to finish."""print "Loading word list from file..."# inFile: fileinFile = open(WORDLIST_FILENAME, 'r', 0)# line: stringline = inFile.readline()# wordlist: list of stringswordlist = string.split(line)print "  ", len(wordlist), "words loaded."return wordlistdef chooseWord(wordlist):"""wordlist (list): list of words (strings)Returns a word from wordlist at random"""return random.choice(wordlist)# end of helper code
# -----------------------------------# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()def isWordGuessed(secretWord, lettersGuessed):'''secretWord: string, the word the user is guessinglettersGuessed: list, what letters have been guessed so farreturns: boolean, True if all the letters of secretWord are in lettersGuessed;False otherwise'''# FILL IN YOUR CODE HERE...for i in secretWord:if (i in lettersGuessed) == False:return Falsereturn Truedef getGuessedWord(secretWord, lettersGuessed):'''secretWord: string, the word the user is guessinglettersGuessed: list, what letters have been guessed so farreturns: string, comprised of letters and underscores that representswhat letters in secretWord have been guessed so far.'''# FILL IN YOUR CODE HERE...guessWord = ""for i in secretWord:if (i in lettersGuessed) == True:guessWord += ielse:guessWord += "_"return guessWorddef getAvailableLetters(lettersGuessed):'''lettersGuessed: list, what letters have been guessed so farreturns: string, comprised of letters that represents what letters have notyet been guessed.'''# FILL IN YOUR CODE HERE...retStr = ""for i in string.ascii_lowercase:if (i in lettersGuessed) == False:retStr += ireturn retStrdef hangman(secretWord):'''secretWord: string, the secret word to guess.Starts up an interactive game of Hangman.* At the start of the game, let the user know how many letters the secretWord contains.* Ask the user to supply one guess (i.e. letter) per round.* The user should receive feedback immediately after each guess about whether their guess appears in the computers word.* After each round, you should also display to the user the partially guessed word so far, as well as letters that the user has not yet guessed.Follows the other limitations detailed in the problem write-up.'''# FILL IN YOUR CODE HERE...print "Welcome to the game, Hangman!"print "I am thinking of a word that is " + str(len(secretWord)) + " long."print "-------------"chance = 8lettersGuessed = []while (chance > 0 and isWordGuessed(secretWord, lettersGuessed) == False):print "You have " + str(chance) + " guesses left."print "Available letters: ",print getAvailableLetters(lettersGuessed)ch = raw_input("Please guess a letter: ")ch = ch.lower()if ch in lettersGuessed:print "Oops! You've already guessed that letter: " + getGuessedWord(secretWord, lettersGuessed)else:lettersGuessed.append(ch)if ch in secretWord:print "Good guess: " + getGuessedWord(secretWord, lettersGuessed)else:print "Oops! That letter is not in my word: " + getGuessedWord(secretWord, lettersGuessed)chance -= 1print "-------------"if isWordGuessed(secretWord, lettersGuessed):print "Congratulations, you won!"else:print "Sorry, you ran out of guesses. The word was else."# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)secretWord = chooseWord(wordlist).lower()
hangman(secretWord)# print isWordGuessed('apple', ['a', 'e', 'i', 'k', 'p', 'r', 's'])
# secretWord = 'apple'
# lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
# print getGuessedWord(secretWord, lettersGuessed)

总结一下:其实作业不难,因为所有的函数功能全都设计好了,只需要我们去实现,所以难点全都避开了,如果不给任何条件,需要完全自己写,难度就会高一个级别,而且函数设计未必合理。。

A WORDGAME: HANGMAN相关推荐

  1. UVa 489 Hangman Judge

    又是一个星期五, 开始发UVa的代码了啊! 比较忙的我没有太多练习题目的时间,所以就简简单单的找了一道水题来做,这道题没什么可以说的,所以就直接附上代码 地址在vjudge.net或UVa上 //yi ...

  2. UVa 489 - Hangman Judge

    把题读明白就行了,水题.注意判断之后及时的退出循环. 1 #include<stdio.h> 2 #include<string.h> 3 4 int main() 5 { 6 ...

  3. UVA - 489 ​​​​​​​Hangman Judge

    Hangman Judge UVA - 489 题目传送门 PS.此题Udebug有毒,即使100组样例全过,但还是WA,心塞. 这是我自己的代码,悲催的WA了 #include <cstdio ...

  4. 489 - Hangman Judge

    Hangman Judge In "Hangman Judge," you are to write a program that judges a series of Hangm ...

  5. [coursera] [design] Hangman

    看了一下网上面经, 基本上说就是automatically地solve hangman 1. 最简单的方法是按照英文字母每个letter出现的频率,一个个猜下来. 游戏在这里:但是实际操作中是限制次数 ...

  6. UVA489 Hangman Judge【模拟】

      In "Hangman Judge," you are to write a program that judges a series of Hangman games. Fo ...

  7. [转载] python猜字谜游戏_Python Hangman猜字游戏

    参考链接: Python中的Hangman游戏 这是经典猜字游戏"Hangman"的Python脚本.要猜的词用一行破折号表示.如果玩家猜出单词中存在的字母,则脚本会将其写入所有正 ...

  8. 简单的HANGMAN游戏

    分析一下简单的hangman游戏,hangman主要两个窗口就是菜单窗口和游戏窗口.这里要用面板以及布局方式将元件排列好,有个基本雏形,这是第一步.这里第一个页面用到girdbaglayout布局方式 ...

  9. hangman游戏c语言,英语游戏 猜词游戏hangman

    HANGMAN英语课堂游戏的设计 广东深圳市电子技术学校 张江宏 一.Hangman游戏的由来 Hangman在西方是一个家喻户晓的猜词游戏.Hang的英文意思是"绞死",而Man ...

最新文章

  1. 不知道如何选择的时候,付诸行动比选择更重要
  2. 超越JAX-RS规范:Apache CXF搜索扩展
  3. html5 视口,html5 – 在媒体查询中更改视口
  4. linux刷脚本需要什么工具吗,利用宝塔Linux一键挂载脚本工具挂载www目录方法
  5. Python-07:Python语法基础-数据类型
  6. [转]百度地图的一些应用方法
  7. mysql 查询polygon_如何通过mysql 判断点是否在指定多边形区域内
  8. 系统集成项目管理工程师计算题(成本管理计算)
  9. AutoCAD LT 2020 for Mac在升级了MacOS 11后打不开了怎么处理?那么教程来了哦
  10. 到底什么是端到端(edge-to-edge)啊?
  11. 来自 Repository 的一丝线索,Domain Model 再重新设计
  12. exe文件关联修复器
  13. 动手画混淆矩阵(Confusion Matrix)(含代码)
  14. 随机梯度下降算法 入门介绍(最通俗易懂)
  15. 美容院的会员等级怎么设置?
  16. EMV技术学习和研究(七)持卡人验证
  17. 计算机里的le是什么符号,在python中传递le或ge符号
  18. 低代码与BPM有什么区别?
  19. 文本相似度匹配-task5
  20. 全球与中国冷凝器扩管器市场深度研究分析报告

热门文章

  1. 【一听就懂的佛法故事】1.什么是禅
  2. python输出文件有省略号_如何解决Python输出是省略号的问题
  3. 博图TIA软件安装完成后各软件作用
  4. 计算矢量图中的线长度和统计信息(QGIS)
  5. contos7改分辨率_centos6.7修改分辨率的問題
  6. 【cuda】cuda与OpenGL互操作
  7. Java 当前时间转农历
  8. 全国电信及网通 DNS 列表
  9. cms什么意思php,现在的cms和php各有什么优势啊?
  10. R语言如何绘制PCA图(四)