Python简介
Python是一种高级的、面向对象的、解释性的编程语言,已经引起了全世界的关注。它语法易于阅读和遵循,非常适合初学者。
Python初学者项目:使用Python的猜词游戏
我们可以考虑的最好的初学者项目是Hangman游戏。这里的主要目标是创建一个'猜词'游戏。
项目要求
- 用户需要能够输入字母猜测
- 对可以使用的猜测次数设置一个限制
- 继续将剩余的次数通知用户
- 使用文本文件作为输入,包含必须猜测的单词
核心概念
- 随机
- 变量
- 布尔型
- 输入输出
- 整数
- 字符串
- 长度
- 打印
代码实现
Hangman.py
from string import ascii_lowercase
from words import get_random_word
def get_num_attempts():
"""获取用户输入的错误尝试次数。"""
while True:
num_attempts = input('How many incorrect attempts do you want? [1-25] ')
try:
num_attempts = int(num_attempts)
if 1 <= num_attempts <= 25:
return num_attempts
else:
print('{0} is not between 1 and 25'.format(num_attempts))
except ValueError:
print('{0} is not an integer between 1 and 25'.format(num_attempts))
def get_min_word_length():
"""获取用户输入的最小单词长度。"""
while True:
min_word_length = input()
:
min_word_length = (min_word_length)
<= min_word_length <= :
min_word_length
:
(.(min_word_length))
ValueError:
(.(min_word_length))
():
(word) != (idxs):
ValueError()
displayed_word = .join([letter idxs[i] i, letter (word)])
displayed_word.strip()
():
(remaining_letters) == :
ValueError()
:
next_letter = ().lower()
(next_letter) != :
(.(next_letter))
next_letter ascii_lowercase:
(.(next_letter))
next_letter remaining_letters:
(.(next_letter))
:
remaining_letters.remove(next_letter)
next_letter
():
()
attempts_remaining = get_num_attempts()
min_word_length = get_min_word_length()
()
word = get_random_word(min_word_length)
()
idxs = [letter ascii_lowercase letter word]
remaining_letters = (ascii_lowercase)
wrong_letters = []
word_solved =
attempts_remaining > word_solved:
(.(get_display_word(word, idxs)))
(.(attempts_remaining))
(.(.join(wrong_letters)))
next_letter = get_next_letter(remaining_letters)
next_letter word:
(.(next_letter))
i ((word)):
word[i] == next_letter:
idxs[i] =
:
(.(next_letter))
attempts_remaining -=
wrong_letters.append(next_letter)
idxs:
word_solved =
()
(.(word))
word_solved:
()
:
()
try_again = ()
try_again.lower() ==
__name__ == :
play_hangman():
()


