A WORDGAME: HANGMAN

这道题是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 guessing
	lettersGuessed: list, what letters have been guessed so far
	returns: 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 False
	return 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 guessing
	lettersGuessed: list, what letters have been guessed so far
	returns: string, comprised of letters and underscores that represents
	  what letters in secretWord have been guessed so far.
	'''
	# FILL IN YOUR CODE HERE...
	guessWord = ""
	for i in secretWord:
		if (i in lettersGuessed) == True:
			guessWord += i
		else:
			guessWord += "_"
	return guessWord

第三个函数是打印出所有可以猜的字符,即,除了已经猜过的以外,剩下的都可以猜,
这题很直观,代码如下:
def getAvailableLetters(lettersGuessed):
	'''
	lettersGuessed: list, what letters have been guessed so far
	returns: string, comprised of letters that represents what letters have not
	  yet been guessed.
	'''
	# FILL IN YOUR CODE HERE...
	retStr = ""
	for i in string.ascii_lowercase:
		if (i in lettersGuessed) == False:
			retStr += i
	return 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 = 8
	lettersGuessed = []
	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 -= 1
		print "-------------"
	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 string

WORDLIST_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 may
	take a while to finish.
	"""
	print "Loading word list from file..."
	# inFile: file
	inFile = open(WORDLIST_FILENAME, 'r', 0)
	# line: string
	line = inFile.readline()
	# wordlist: list of strings
	wordlist = string.split(line)
	print "  ", len(wordlist), "words loaded."
	return wordlist


def 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 guessing
	lettersGuessed: list, what letters have been guessed so far
	returns: 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 False
	return True


def getGuessedWord(secretWord, lettersGuessed):
	'''
	secretWord: string, the word the user is guessing
	lettersGuessed: list, what letters have been guessed so far
	returns: string, comprised of letters and underscores that represents
	  what letters in secretWord have been guessed so far.
	'''
	# FILL IN YOUR CODE HERE...
	guessWord = ""
	for i in secretWord:
		if (i in lettersGuessed) == True:
			guessWord += i
		else:
			guessWord += "_"
	return guessWord


def getAvailableLetters(lettersGuessed):
	'''
	lettersGuessed: list, what letters have been guessed so far
	returns: string, comprised of letters that represents what letters have not
	  yet been guessed.
	'''
	# FILL IN YOUR CODE HERE...
	retStr = ""
	for i in string.ascii_lowercase:
		if (i in lettersGuessed) == False:
			retStr += i
	return 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 = 8
	lettersGuessed = []
	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 -= 1
		print "-------------"
	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)

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


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TypingGame 一款基于 MFC 实现的简单的打字游戏程序。1.  双击运行程序,弹出主界面:2.点击菜单项“用户”,即可进行登录和注册操作。若您未注册过用户,可进行注册之后登录。现已注册UserName用户为例,进行演示。点击登录即弹出登录窗口如下:点击注册即弹出注册窗口如下:(或者直接点击注册按钮)输入用户姓名:UserName;用户昵称:UserName;用户密码:UserName;如下:点击确定即可完成注册。以UserName用户登录,即可在主界面右上角看见如下信息:3.对游戏进行设置:,在游戏选项中可以对“游戏难度”,“图片类别”,“背景音乐”进行设置。Ø  游戏难度:点击游戏难度按钮,弹出一下对话框:可在下拉列表框中对相应的“单词量”,“拼写难度”,“出词频率”,“移动速率”进行设置。其中,单词量分为50,100,150三项。拼写难度目前是四级的随机单词。出词频率分为单倍和双倍。移动速度分为快,中,慢速。点击设置即可。Ø  图片类别:点击图片类别按钮,弹出一下对话框:供选择的图片目前有气球和小鱼两种,点击单选按钮选择即可。Ø  背景音乐:点击背景音乐按钮,弹出一下对话框:在组框里选择相应的音乐,点击“选择音乐”按钮即可。设置好的游戏选项将显示在:。4.点击,弹出以下窗口:显示当前系统中,得分最高的前五名用户。5.,帮助菜单项分为两部分,一个是游戏规则,一个是关于游戏。Ø  游戏规则:Ø  关于游戏:6. 此处显示了当前的游戏状态,是开始还是停止。7.点击这两个按钮,开始游戏或者退出游戏。8.以下是游戏过程中的某幅截图:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值