Python实现hangman游戏

Introduction

For this problem, you will implement a variation of the classic word game Hangman. 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 file words.txt. 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 the WORDLIST_FILENAME constant (defined near the top of the file) to the complete pathname for the file words.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.

Requirements

  • The computer must select a word at random from the list of available words that was provided in words.txt. The functions for loading the word list and selecting a random word have already been provided for you.
  • The game must be interactive; the flow of the game should go as follows:
    1. At the start of the game, let the user know how many letters the computer’s word contains.
    2. Ask the user to supply one guess (i.e. letter) per round.
    3. The user should receive feedback immediately after each guess about whether their guess appears in the computer’s word.
    4. 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.
  • Some additional rules of the game:
    1. 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).
    2. A user loses a guess only when s/he guesses incorrectly.
    3. 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.
    4. 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.

Sample Output

The output of a winning game should look like this…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Loading word list from file...
55900 words loaded.
Welcome to the game, Hangman!
I am thinking of a word that is 4 letters long.
*************
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: a
Good guess: _ a_ _
*************
You have 8 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: a
Oops! You've already guessed that letter: _ a_ _
*************
You have 8 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: s
Oops! That letter is not in my word: _ a_ _
*************
You have 7 guesses left.
Available letters: bcdefghijklmnopqrtuvwxyz
Please guess a letter: t
Good guess: ta_ t
*************
You have 7 guesses left.
Available letters: bcdefghijklmnopqruvwxyz
Please guess a letter: r
Oops! That letter is not in my word: ta_ t
*************
You have 6 guesses left.
Available letters: bcdefghijklmnopquvwxyz
Please guess a letter: m
Oops! That letter is not in my word: ta_ t
*************
You have 5 guesses left.
Available letters: bcdefghijklnopquvwxyz
Please guess a letter: c
Good guess: tact
*************
Congratulations, you won!
And the output of a losing game should look like this…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Loading word list from file...
55900 words loaded.
Welcome to the game, Hangman!
I am thinking of a word that is 3 letters long.
*************
You have 8 guesses left.
Available letters: abcdefghijklmnopqrstuvwxyz
Please guess a letter: a
Oops! That letter is not in my word: _ _ _
*************
You have 7 guesses left.
Available letters: bcdefghijklmnopqrstuvwxyz
Please guess a letter: b
Oops! That letter is not in my word: _ _ _
*************
You have 6 guesses left.
Available letters: cdefghijklmnopqrstuvwxyz
Please guess a letter: c
Oops! That letter is not in my word: _ _ _
*************
You have 5 guesses left.
Available letters: defghijklmnopqrstuvwxyz
Please guess a letter: d
Oops! That letter is not in my word: _ _ _
*************
You have 4 guesses left.
Available letters: efghijklmnopqrstuvwxyz
Please guess a letter: e
Oops! That letter is not in my word: _ _ _
*************
You have 3 guesses left.
Available letters: fghijklmnopqrstuvwxyz
Please guess a letter: f
Good guess: f_ _
*************
You have 3 guesses left.
Available letters: ghijklmnopqrstuvwxyz
Please guess a letter: g
Oops! That letter is not in my word: f_ _
*************
You have 2 guesses left.
Available letters: hijklmnopqrstuvwxyz
Please guess a letter: h
Oops! That letter is not in my word: f_ _
*************
You have 1 guesses left.
Available letters: ijklmnopqrstuvwxyz
Please guess a letter: i
Good guess: fi_
*************
You have 1 guesses left.
Available letters: jklmnopqrstuvwxyz
Please guess a letter: k
Oops! That letter is not in my word: fi_
*************
Sorry, you ran out of guesses. The word was fit

We’ll start by writing 3 simple functions that will help us easily code the Hangman problem

分别是三个小功能 isWordGuessed、getGuessedWord、getAvailableLetters 函数与 hangman 游戏主程序的实现。

Problem 1 - Is the Word Guessed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
First, implement the function isWordGuessed that takes in two parameters
- a string: secretWord
- a list of letters: lettersGuessed.

This function returns a boolean
- True if secretWord has been guessed (ie, all the letters of secretWord are in lettersGuessed)
- False otherwise.

Example Usage:

secretWord = 'apple'
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']

print(isWordGuessed(secretWord, lettersGuessed))
False

For this function, you may assume that all the letters
in secretWord and lettersGuessed are lowercase.

​ 这部分主要是判断猜测的 secretWord 中的字母是否都在从一开始至今猜测过的字母集中,如果是返回 True 否则 False

isWordGuessed(secretWord, lettersGuessed)

1
2
3
4
#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
1
2
3
4
5
def isWordGuessed(secretWord, lettersGuessed):
for i in range(len(secretWord)):
if secretWord[i] not in lettersGuessed:
return False
return True

Problem 2 - print the guess word

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
implement the function getGuessedWord that takes in two parameters
- a string, secretWord, and
- a list of letters, lettersGuessed.

This function returns a string that is comprised of letters and underscores,
based on what letters in lettersGuessed are in secretWord. This shouldn't be too different from isWordGuessed!

Example Usage:

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

When inserting underscores into your string, it's a good idea
to add at least a space after each one, so it's clear to the
user how many unguessed letters are left in the string
(compare the readability of ____ with _ _ _ _ ).

This is called usability - it's very important,
when programming, to consider the usability of your program.
If users find your program difficult to understand or operate,
they won't use it!

For this problem, you are free to use spacing in any way you wish
We do encourage you to think about usability when designing.

For this function, you may assume that all the letters in
secretWord and lettersGuessed are lowercase.

​ 这部分的主要功能则是将所猜单词猜中的字母在单词中的位置打印出来,未猜出部分用 “_ “ 部分来代替。

1
2
3
4
就是形如
secretWord = 'apple'
lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
输出结果为 '_ pp_ e'

getGuessedWord(secretWord, lettersGuessed)

1
2
3
#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.
1
2
3
4
5
6
7
8
def getGuessedWord(secretWord, lettersGuessed):
list1 = list()
for i in range(len(secretWord)):
if secretWord[i] in lettersGuessed:
list1.append(secretWord[i])
else:
list1.append("_")
return ' '.join(list1)

Problem 3 - print the avaiable letters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
implement the function getAvailableLetters that takes
in one parameter - a list of letters, lettersGuessed.
This function returns a string that is comprised of
lowercase English letters - all lowercase English letters
that are not in lettersGuessed.

Example Usage:

lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
print(getAvailableLetters(lettersGuessed))
abcdfghjlmnoqtuvwxyz

Note that this function should return the letters in alphabetical order,
as in the example above.

For this function, you may assume that all the letters in lettersGuessed
are lowercase.

Hint: You might consider using string.ascii_lowercase,
which is a string comprised of all lowercase letters:

import string
print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

​ 这部分的功能是返回字母表中没有猜过的字母,借用 string 库中的string.ascii_lowercase 功能模块协助实现

getAvailableLetters(lettersGuessed)

1
2
3
#lettersGuessed: list, what letters have been guessed so far
#returns: string, comprised of letters that represents what #letters have not
# yet been guessed.
1
2
3
4
5
def getAvailableLetters(lettersGuessed):
str1 = string.ascii_lowercase
for i in range(len(lettersGuessed)):
str1 = str1.replace(lettersGuessed[i],"")
return str1

Problem 4 - implent the function hangman

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Now you will implement the function hangman, which takes one parameter

the secretWord the user is to guess.
This starts up an interactive game of Hangman between the user and the computer.

Be sure you take advantage of the three helper functions,

isWordGuessed
getGuessedWord
getAvailableLetters,
that you've defined in the previous part.

Hints:

You should start by noticing where we're using the provided functions to load the words and pick a random one.
Consider using lower() to convert user input to lower case. For example:

guess = 'A'
guessInLowerCase = guess.lower()
Consider writing additional helper functions if you need them!

There are four important pieces of information you may wish to store:

secretWord: The word to guess.
lettersGuessed: The letters that have been guessed so far.
mistakesMade: The number of incorrect guesses made so far.
availableLetters: The letters that may still be guessed.
Every time a player guesses a letter, the guessed letter must be removed from availableLetters (and if they guess a letter that is not in availableLetters, you should print a message telling them they've already guessed that - so try again!).

​ 这部分给出了一部分辅助代码,主要是从文件中读取单词并随机选取作为 secretWord,然后就是主要游戏部分的设计了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Hangman game
#

# -----------------------------------
# begin of helper code

import random

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 = open(WORDLIST_FILENAME, 'r')
line = inFile.readline()
wordlist = line.split()
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()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import string
def hangman(secretWord):
print("Welcome to the game, Hanman!")
print("I am thinking of a word that is %d letters long." % len(secretWord))
i = 8
lettersGuessed = list()
while(i):
print("*"*13)
print("You have %d guesses left." % i)
print("Available letters:" + getAvailableLetters(''))
letter = input("Please guess a letter: ")
letter = letter.lower()
if letter in lettersGuessed:
print("Oops! You've already guessed that letter: "+ getGuessedWord(secretWord, lettersGuessed))
else:
lettersGuessed.append(letter)
if isWordGuessed(secretWord, lettersGuessed):
print("Good guess:" + getGuessedWord(secretWord, lettersGuessed))
if "_" not in getGuessedWord(secretWord, lettersGuessed):
print("*"*13)
print("Congratulations, you won!")
break
else:
print("Oops! That letter is not in my word:" + getGuessedWord(secretWord, lettersGuessed))
i -= 1
if i == 0:
print("*"*13)
print("Sorry, you ran out of guesses. The word was %s" % secretWord)
1
2
3
4
5
# When you've completed your hangman function, uncomment these two lines
# and run this file to test!

secretWord = chooseWord(loadWords()).lower()
hangman(secretWord)

​ 我是在一个 while 函数底下用 if-else 实现,如果字母在已猜字母集中则打印,否则将字母添加到已猜字母集中,如果 isWordGuessed 猜中了,打印,此条件下如果 “_ “ 不在 getGuessedWord 中,打印赢了并 break 退出循环,否则打印字母不在单词中,最后判断一下八次循环结束后仍然没猜出来,打印。

words.txt下载