Python中的猜词游戏
Python是一种强大的多用途编程语言,被许多大型行业使用。它提供简单易用的语法,是初学计算机编程的理想语言。Python是一种高级编程语言。该语言的核心设计理念是可读性的代码和语法,使程序员能够用几行代码表达概念。
在接下来的教程中,我们将学习如何使用Python编程语言创建”猜词游戏”或”猜单词”。
但在开始之前,让我们先了解一下这个游戏和一些规则。我们还将学习如何逐步在Python中实现这个游戏。
了解猜词游戏
这是一种经典的猜词游戏,由两个或更多玩家之间进行。一个玩家给出一个词或词组,其他玩家需要在给定的次数内猜对。这个游戏简单、易得,富有教育意义,只需要一张纸和正确拼写的能力。我们也可以和计算机一起玩这个游戏。每猜错一次,生命或次数就会减少,一个”悬挂人”将逐渐出现。目标是在悬挂人死亡之前解决谜题并猜出正确的单词/短语。
这个经典游戏已经非常受欢迎,一些提示、技巧和策略被用来赢得游戏,就像大多数游戏一样。
这个经典游戏已经非常受欢迎,一些提示、技巧和策略被用来赢得游戏,就像大多数游戏一样。
理解游戏规则
在将这个游戏部署为代码解决方案之前,我们必须熟悉它的规则-这个游戏是如何工作的?然后我们可以将这个游戏高效地转换为一段代码。
游戏规则:
规则1: 一个人设定一个单词或单词列表。
规则2: 玩家对可能开始或包含在单词或单词列表中的字母进行初始猜测。
规则3: 如果字母在单词/单词列表中存在,玩家得到一个点并继续猜测一个字母。
规则4: 如果字母不在单词中,玩家失去一次/点数,并且绞刑游戏的一部分出现。
规则5: 错误猜测的字母逐个显示出来,直到整个图像都被绘制出来。
规则6: 同样,对于每个正确猜测的字母,字母会被放置在屏幕上,直到单词被完成并且玩家获胜。
现在让我们了解一下在Python中逐步实现绞刑游戏的方法。
Python中绞刑游戏的实现
我们在这个项目中使用的概念非常简单。我们在Python中没有创建任何物理屏幕绘图,所以这个版本的绞刑游戏将倒数剩余的生命数量。
现在让我们通过下面描述的步骤来理解实现过程:
步骤1: 导入 随机 模块
步骤2: 定义一个函数来欢迎用户/玩家。
步骤3: 在这个函数中创建一个变量来获取用户/玩家的名字,并使用一个字符串方法来将用户的名字转换为句子格式。
步骤4: 创建一个决策过程来检查用户只输入字母,而不是数字作为名字。
现在让我们考虑下面的代码片段来演示上述步骤的实现。
文件:hangmanGame.py
# importing the random module
import random
# defining the greetings() function
def greetings():
# defining the username variable
username = input("""
==================================================
> Welcome to the Hangman Game! Enter your name: <
""").capitalize()
# using a decision making process to accept only alphabets as name
if username.isalpha() == True:
print("""
>> Hello,""", username + """!""", """We are glad to have you here! <<
You will be playing against the computer today. The computer will
randomly choose a word and you will try to guess the correct word
You can always invite the friends for a fun time together
==================================================================
Good Luck! Have fun playing
""")
else:
print('Please enter a valid name using alphabets only')
username = input('Enter a game name here: ')
print('Hello, ' + username + '! Please go through the rules of the game below:')
解释:
在上述代码段中,我们导入了 random 模块。然后我们定义了 greetings() 函数。我们定义了一个变量作为 username ,在该函数中它接受用户的输入字符串,包含他们的名字。然后我们使用了 if-else 条件语句来只接受字母作为名字。
步骤5: 定义另一个函数” playAgain() “。
步骤6: 添加一个决策过程。
考虑以下代码段,展示了上述步骤的实现。
文件:hangmanGame.py
# defining the playAgain() function
def playAgain():
"""
This function asks user/player if they wish to replay the hangman game
"""
userResponse = input('Would you like to play again? Y or N').lower()
# creating a decision making process
if userResponse == 'y':
gameRun()
else:
print('Hope you had fun playing this game. See you next time!')
解释:
在上面的代码片段中,我们定义了一个名为 playAgain() 的函数。我们在这个函数中询问用户是否要再玩一次,并将他们的回答存储在 userResponse 变量中。然后我们使用 if-else 条件语句来创建一个决策过程。
步骤7: 定义另一个函数” getWord() “,用于为用户生成随机词来猜测。
让我们考虑下面的代码片段,演示了上述步骤的实现。
文件:hangman.py
# defining the getWord() function
def getWord():
"""
This function produces the word the user will attempt guessing
"""
listOfWords = ['Apple', 'Banana', 'Papaya', 'Mango', 'Kiwi', 'Orange', 'Pineapple', 'Grapes', 'Cherry', 'Watermelon']
return random.choice(listOfWords).lower()
解释:
在上面的代码片段中,我们定义了一个名为 getWord() 的函数。在这个函数内部,我们定义了一个包含一些单词的列表。然后我们使用 random 模块从列表中随机选择一个单词并返回它。
步骤8: 在函数内定义另一个名为 gameRun() 的函数。
步骤9: 在 gameRun() 函数内调用 greetings() 函数,以开始游戏。
步骤10: 在函数内定义一个 alphabet 变量。
步骤11: 将一个 randomWord 变量(用于猜测的单词)设置为调用 getWord() 函数选择的随机单词。
步骤12: 初始化一个空列表来存储猜测的字母。
步骤13: 将 attempts 变量初始化为存储用户尝试次数的值。
步骤14: 将初始猜测设置为 False 。
步骤15: 打印一个空行。
步骤16: 为用户打印一个猜测提示,提示单词中包含的字母数。
让我们考虑下面的代码片段,演示了步骤 8-16 的实现。
文件:hangmanGame.py
# defining the gameRun() function
def gameRun():
# calling the greeting() function
greetings()
# defining the 'alphabet' variable
alphabet = ('abcdefghijklmnopqrstuvwxyz')
# getting a random word from the getWord() function
randomWord = getWord()
# initiating an empty list for guessed letter
guessedLetters = []
# initiating the 'attempts' variable for the number of attempts by the user
attempts = 6
# setting initial guess to False
guess = False
# empty line
print()
# printing a guess hint for the user for number of letters consisted in the word
print('The Word consists of', len(randomWord), 'letters.')
print(len(randomWord) * '_')
解释:
在上面的代码片段中,我们定义了一个名为gameRun()的函数。在这个函数中,我们调用了greetings()函数。然后,我们定义了一个变量alphabet。我们调用了getWord()函数,并将返回值存储在一个名为randomWord的变量中。然后,我们创建了一个空列表来存储猜测的字母,以及一个变量来表示猜测的总次数。然后,我们将guess的初始值设置为False。最后,我们打印了一个提示,告诉用户要猜测的单词中包含的字母数。
步骤17: 在gameRun()函数内部进行了一个while循环,并根据玩家决定是输入一个字母还是整个单词进行了逻辑判断。
步骤18: 还创建了判断条件,检查用户输入的值是否错误,以及用户输入的字母是否等于要猜测的单词的总字母数。
步骤19: 每次用户猜测错误时,减少猜测次数(attempts)。
步骤20: 在gameRun()函数结束时,如果玩家希望继续游戏,则调用playAgain()函数。
现在让我们看一下下面的代码片段,展示了这些步骤(17-20)的实现。
文件: hangmanGame.py
while guess == False and attempts > 0:
print('You have ' + str(attempts) + ' attempts')
userGuess = input('Guess a letter in the word or enter the full word: ').lower()
# user inputs a letter
if len(userGuess) == 1:
if userGuess not in alphabet:
print('You are yet to enter a letter. Consider checking your entry and make sure you enter an alphabet not a number.')
elif userGuess in guessedLetters:
print('You have already guessed that letter before. Try again!')
elif userGuess not in randomWord:
print('Oops! that letter is not a part of a word.')
guessedLetters.append(userGuess)
attempts -= 1
elif userGuess in randomWord:
print('Awesome! This letter is present in the word!')
guessedLetters.append(userGuess)
else:
print('Invalid Input! You might have entered the wrong entry.')
# user inputs the full word
elif len(userGuess) == len(randomWord):
if userGuess == randomWord:
print('Awesome! You guessed the word correctly!')
guess = True
else:
print('Oops! that was not the word we were looking for.')
attempts -= 1
# user inputs letter and it is not equal to the total
# number of letters in the word to guess
else:
print('The length of the guess is not the same as the length of the word.')
attempts -= 1
the_status = ''
if guess == False:
for letter in randomWord:
if letter in guessedLetters:
the_status += letter
else:
the_status += '_'
print(the_status)
if the_status == randomWord:
print('Awesome! You guessed the word correctly!')
guess = True
elif attempts == 0:
print('Unfortunately! You ran out of guesses and you couldn\'t guessed the word.')
# initiating the playAgain() function if user wishes to continue
playAgain()
解释:
在以上代码片段中,我们使用了 while 循环。在这个循环中,我们使用了 if-elif-else 条件语句来检查玩家猜测的输入是单个字母还是完整的单词。我们还检查了玩家输入的值是否错误。我们还检查了用户输入的字母是否等于要猜测的单词的总字母数。每次用户猜测错误时,我们都会扣除 attempts 的数量。最后,如果玩家想要继续游戏,我们会在 gameRun() 函数中启动 playAgain() 函数。
步骤21: 调用 gameRun() 函数来执行程序。
让我们考虑下面的代码片段,演示了上述步骤的实现。
文件:hangmanGame.py
# executing the program
gameRun()
解释:
在上面的代码片段中,我们调用了 gameRun() 函数以执行程序。
‘ 猜词游戏 ‘程序的编码最终完成。现在我们可以保存文件并运行程序,看看它是否正常工作。
要运行该程序,我们可以在命令行或终端中输入以下命令:
命令:
$ python hangmanGame.py
但在我们看到输出之前,这里是一个完整的项目代码。
完整的项目代码
下面的程序文件是一个完整的名为“Hangman Game”的项目代码。
文件:hangmanGame.py
# importing the random module
import random
# defining the greetings() function
def greetings():
# defining the username variable
username = input("""
==================================================
> Welcome to the Hangman Game! Enter your name: <
""").capitalize()
# using a decision making process to accept only alphabets as name
if username.isalpha() == True:
print("""
>> Hello,""", username + """!""", """We are glad to have you here! <<
You will be playing against the computer today. The computer will
randomly choose a word and you will try to guess the correct word
You can always invite the friends for a fun time together
==================================================================
Good Luck! Have fun playing
""")
else:
print('Please enter a valid name using alphabets only')
username = input('Enter a game name here: ')
print('Hello, ' + username + '! Please go through the rules of the game below:')
# defining the playAgain() function
def playAgain():
"""
This function asks user/player if they wish to replay the hangman game
"""
userResponse = input('Would you like to play again? Y or N: ').lower()
# creating a decision making process
if userResponse == 'y':
gameRun()
else:
print('Hope you had fun playing this game. See you next time!')
# defining the getWord() function
def getWord():
"""
This function produces the word the user will attempt guessing
"""
listOfWords = ['Apple', 'Banana', 'Papaya', 'Mango', 'Kiwi', 'Orange', 'Pineapple', 'Grapes', 'Cherry', 'Watermelon']
return random.choice(listOfWords).lower()
# defining the gameRun() function
def gameRun():
# calling the greeting() function
greetings()
# defining the 'alphabet' variable
alphabet = ('abcdefghijklmnopqrstuvwxyz')
# getting a random word from the getWord() function
randomWord = getWord()
# initiating an empty list for guessed letter
guessedLetters = []
# initiating the 'attempts' variable for the number of attempts by the user
attempts = 6
# setting initial guess to False
guess = False
# empty line
print()
# printing a guess hint for the user for number of letters consisted in the word
print('The Word consists of', len(randomWord), 'letters.')
print(len(randomWord) * '_')
while guess == False and attempts > 0:
print('You have ' + str(attempts) + ' attempts')
userGuess = input('Guess a letter in the word or enter the full word: ').lower()
# user inputs a letter
if len(userGuess) == 1:
if userGuess not in alphabet:
print('You are yet to enter a letter. Consider checking your entry and make sure you enter an alphabet not a number.')
elif userGuess in guessedLetters:
print('You have already guessed that letter before. Try again!')
elif userGuess not in randomWord:
print('Oops! that letter is not a part of a word.')
guessedLetters.append(userGuess)
attempts -= 1
elif userGuess in randomWord:
print('Awesome! This letter is present in the word!')
guessedLetters.append(userGuess)
else:
print('Invalid Input! You might have entered the wrong entry.')
# user inputs the full word
elif len(userGuess) == len(randomWord):
if userGuess == randomWord:
print('Awesome! You guessed the word correctly!')
guess = True
else:
print('Oops! that was not the word we were looking for.')
attempts -= 1
# user inputs letter and it is not equal to the total
# number of letters in the word to guess
else:
print('The length of the guess is not the same as the length of the word.')
attempts -= 1
the_status = ''
if guess == False:
for letter in randomWord:
if letter in guessedLetters:
the_status += letter
else:
the_status += '_'
print(the_status)
if the_status == randomWord:
print('Awesome! You guessed the word correctly!')
guess = True
elif attempts == 0:
print('Unfortunately! You ran out of guesses and you couldn\'t guessed the word.')
# initiating the playAgain() function if user wishes to continue
playAgain()
# executing the program
gameRun()
输出:
==================================================
> Welcome to the Hangman Game! Enter your name: <
Tyler
>> Hello, Tyler! We are glad to have you here! <<
You will be playing against the computer today. The computer will
randomly choose a word and you will try to guess the correct word
You can always invite the friends for a fun time together
==================================================================
Good Luck! Have fun playing
The Word consists of 6 letters.
______
You have 6 attempts
Guess a letter in the word or enter the full word: e
Awesome! This letter is present in the word!
____e_
You have 6 attempts
Guess a letter in the word or enter the full word: l
Oops! that letter is not a part of a word.
____e_
You have 5 attempts
Guess a letter in the word or enter the full word: p
Awesome! This letter is present in the word!
___pe_
You have 5 attempts
Guess a letter in the word or enter the full word: c
Oops! that letter is not a part of a word.
___pe_
You have 4 attempts
Guess a letter in the word or enter the full word: a
Awesome! This letter is present in the word!
__ape_
You have 4 attempts
Guess a letter in the word or enter the full word: g
Awesome! This letter is present in the word!
g_ape_
You have 4 attempts
Guess a letter in the word or enter the full word: r
Awesome! This letter is present in the word!
grape_
You have 4 attempts
Guess a letter in the word or enter the full word: s
Awesome! This letter is present in the word!
grapes
Awesome! You guessed the word correctly!
Would you like to play again? Y or N: n
Hope you had fun playing this game. See you next time!