我正在构建一个Hangman游戏作为我的第一个python项目。当我构建它时,游戏目前正在终端中运行。我没有使用PyGame。这里有更多相关的代码。
five_letters = ['birds', 'hands', 'trees']
difficulty = 'easy'
def get_word(foo):
"""Based on difficulty generate a game_word, then turn it into a list to be returned"""
if foo == 'easy':
foo = random.choice(five_letters)
foo = list(foo)
if foo == 'medium':
foo = random.choice(ten_letters)
foo = list(foo)
if foo == 'hard':
foo = random.choice(fifteen_letters)
foo = list(foo)
return foo
game_word = get_word(difficulty)
我想要列出并执行以下操作:
我将字符串作为列表返回,以便我可以在列表中找到正确猜测的值,将其放在输出中的正确位置。
例如
game_word = 'birds'
player_guess = 's'
我想输出
_ _ _ _ s
但也许我说这一切都错了。我觉得我可以缩短选择随机字符串的函数部分,然后将其转换为列表。
答案 0 :(得分:2)
您可以使用:
from random import choice
foo = [choice(a_list)]
答案 1 :(得分:0)
我也开始使用Python 3.x开始我的旅程了,这是我刚刚制作的快速代码(如果你遇到问题,可以用它作为参考):
from random import choice as chc
def hangman(diff):
#Fill in the words for every difficulty type:
easy = ['this', 'that']
medium = ['bicycle', 'bathroom']
hard = ['superlongword', 'othersuperlongw']
if diff == 'easy':
word = chc(easy)
elif diff == 'medium':
word = chc(medium)
elif diff == 'hard':
word = chc(hard)
else:
raise ValueError('Bad difficulty choosen. Terminating.')
shadow = ['_' for item in word] #list which is showing the progress
shad_str = ''
for item in shadow:
shad_str += item
print('Choosen word is {} characters long and looks like this:\n{}'.format(len(shad_str), shad_str))
while '_' in shadow:
letter = input('Type in next char: ')
if len(letter) == 1: #anti-cheat - always have to give 1 char
if letter in word:
for i in range(len(word)): #makes it work correctly even when the letter shows up more than one time
if(letter == word[i]):
shadow[i] = letter
temp = ''
for item in shadow:
temp += item
print(temp)
else:
print("This letter isn't in the choosen word! Try again.")
else:
print('No cheating! Only one character allowed!')
else:
shad_str = ''
for item in shadow:
shad_str += item
print('The game has ended. The word was "{}".'.format(shad_str))
我确定检查的全部内容都可以在一个功能中完成(这就是为什么只是为了简单的模式),所以你可以调用& #39;打'功能3次,具体取决于您选择的难度模式 编辑:那是不需要的,我只是注意到你可以用3 ifs来决定差异。如果用户选择正确的难度,现在游戏每次都有效。