文字饼干游戏Python,为什么即使它存在于文件中也不计算我的话?



我正在玩一个单词饼干游戏。我有一个包含42.9万个英语单词的文件,但当我键入单词时,它不计算它们——不知道为什么。下面是Python 中的代码

import random
from random import shuffle
letters = ["c", "a", "e", "r", "u", "o", "i", "n", "b"]
score = 0
game_on = True
f = open(r"C:UsersMSIDesktopwordlist.txt", "r")

def easy(letter_list, file):
global score
global game_on
# unique_letters = [i for i in letter_list]
# mode_letters = random.sample(unique_letters, 3)
shuffle(letter_list)
mode_letters = letter_list[:3]
print(mode_letters)
guess_word = input("combine the letters to form a word")
for line in file:
if guess_word in line:
score += 1
print("correct word you get a +1 to your score")
print(score)
return score
else:
print(" that's not a word start the game again")
game_on = False
return game_on
while game_on:
print("hello welcome to word cookies game")
difficulty = input("choose what difficulty you would like to have Easy / Medium / difficult").lower()
if difficulty == "easy":
easy(letters, f)

return中断函数,而不仅仅是循环。在任何一种情况下,if/else都有返回,并且由于在循环的每次迭代中都会对其中一个进行求值,因此可以保证您会过早地脱离函数。

你可能想要的是摆脱只检查成功的其他方法,当这在任何情况下都不能保证时,然后宣布失败。

第二个返回似乎没有必要,尤其是因为它返回的类型(boolean(与score(int(不同,所以我会去掉它。

for line in file:
if guess_word in line:
score += 1
print("correct word you get a +1 to your score")
print(score)
return score
# after the for loop finishes we can safely say the word
# was not found in the file.
print("that's not a word start the game again")
game_on = False

尝试添加以下内容或类似内容:

file = open('File', 'r+')
words = file.readlines()
for word in words:
words.replace(word, word.strip()) # To remove all the 'n' newline characters
if guess_word in words:
score += 1

假设你每行都有不同的单词,这应该很好。

最新更新