首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python hangman代码

Python hangman代码
EN

Code Review用户
提问于 2020-06-14 15:28:46
回答 1查看 246关注 0票数 7

伙计们,我对python很陌生,我决定通过自己做一些项目来学习它,所以我开始做Hangman游戏,有人愿意检查我的代码中的一些常见错误,还有什么可以做得比它更好,顺便说一句。

代码语言:javascript
复制
import random


def rand_word(version):
    if version.lower() == "slovak":
        words = open("Slova", "r")
        all_lines = words.readlines()
        line_num = random.randint(0, len(all_lines))
        words.close()
        return all_lines[line_num]
    elif version.lower() == "english":
        words = open("Words", "r")
        all_lines = words.readlines()
        line_num = random.randint(0, len(all_lines))
        words.close()
        return all_lines[line_num]
    else:
        print("Wrong input! [FATAL ERROR]")
        input("Press enter to EXIT!")
        exit()


def draw(what_to_do):

    HANGMANPICS = ['''
      +---+
      |   |
          |
          |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
          |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
      |   |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|   |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|\  |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|\  |
     /    |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|\  |
     / \  |
          |
    =========''']

    if what_to_do == 1:
        print(HANGMANPICS[what_to_do])
    elif what_to_do == 2:
        print(HANGMANPICS[what_to_do])
    elif what_to_do == 3:
        print(HANGMANPICS[what_to_do])
    elif what_to_do == 4:
        print(HANGMANPICS[what_to_do])
    elif what_to_do == 5:
        print(HANGMANPICS[what_to_do])
    elif what_to_do == 6:
        print(HANGMANPICS[what_to_do])
    elif what_to_do == 7:
        print(HANGMANPICS[what_to_do])
    else:
        print(HANGMANPICS[0])


def list_fill(size):
    i = 0
    size -= 1
    while i < size:
        positions.append("_")
        i += 1


print("HANGMAN")
print("You have 6 tries to guess the correct word!")
dictionary = input("Chose dictionary Slovak or English: ")
positions = []
tries = 0
win_con = 1
addition = False
temp_word = rand_word(dictionary)
#print(temp_word)
list_fill(len(temp_word))


while tries < 6:

    counter = 0
    draw(tries)
    print(*positions)
    user_letter = input("Enter a letter: ")

    for letter in temp_word:

        if letter == user_letter:
            positions[counter] = letter
            win_con += 1
            tries -= 1
        else:
            addition = True

        counter += 1

    if addition:
        tries += 1

    if win_con == len(temp_word):
        print("You have won!")
        print(*positions)
        input("Press enter to EXIT!")
        exit()

print("You have run out of tries! ")
print(f"The word was {temp_word.upper()}")
input("Press enter to EXIT!")
EN

回答 1

Code Review用户

回答已采纳

发布于 2020-06-14 16:14:58

在我的版本下面有更改-我没有运行它来测试。

我用代码来描述它。

代码语言:javascript
复制
import random

# --- constants ---

HANGMANPICS = ['''
      +---+
      |   |
          |
          |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
          |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
      |   |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|   |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|\  |
          |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|\  |
     /    |
          |
    =========''', '''
      +---+
      |   |
      O   |
     /|\  |
     / \  |
          |
    ========='''
]

# --- functions ---

def rand_word(version):
    
    version = version.lower()
    
    if version == "slovak":
        filename = "Slova"
    elif version == "english":
        filename = "Words"
    else:
        print("Wrong input! [FATAL ERROR]")
        input("Press enter to EXIT!")
        exit()

    words = open(filename) 
    #all_lines = words.readlines()  # it keeps `\n` in lines
    #all_lines = words.read().split('\n')  # it removes `\n`  in lines
    all_lines = words.read().splitlines()  # it removes `\n`  in lines
    words.close()
    
    print(all_lines)

    #line_num = random.randint(0, len(all_lines))
    #return all_lines[line_num]

    word = random.choice(all_lines)
    return word    

def draw(what_to_do):

    if 1 <= what_to_do <= 7:
        print(HANGMANPICS[what_to_do])
    else:
        print(HANGMANPICS[0])
   
    # or

    #if what_to_do < 1 or what_to_do > 7:
    #    what_to_do = 0
    #print(HANGMANPICS[what_to_do])

def list_fill(size):
    return ["_"] * size
    #return ["_"] * size-1 # if you didn't remove `\n` from lines

# --- main ---
print("HANGMAN")
print("You have 6 tries to guess the correct word!")

dictionary = input("Chose dictionary Slovak or English: ")

tries = 0
win_con = 0

temp_word = rand_word(dictionary)
positions = list_fill(len(temp_word))

while tries < 6:

    counter = 0
    
    draw(tries)
    #print(*positions)
    print(' '.join(positions))  # the same result
    
    user_letter = input("Enter a letter: ")

    addition = False
    
    for letter in temp_word:

        if letter == user_letter:
            positions[counter] = letter
            win_con += 1
            tries -= 1
        else:
            addition = True

        counter += 1

    if addition:
        tries += 1

    if win_con == len(temp_word):
        print("You have won!")
        print(*positions)
        input("Press enter to EXIT!")
        exit()

print("You have run out of tries! ")
print(f"The word was {temp_word.upper()}")
input("Press enter to EXIT!")

rand_word()

你只能转换到低一次

代码语言:javascript
复制
version = version.lower()

if/else内部,您使用相同的代码,以便在if/else之后使用它

代码语言:javascript
复制
if version == "slovak":
    filename = "Slova"
elif version == "english":
    filename = "Words"
else:
    print("Wrong input! [FATAL ERROR]")
    input("Press enter to EXIT!")
    exit()

words = open(filename) 
all_lines = words.readlines()  # it keeps `\n` in lines
words.close()

line_num = random.randint(0, len(all_lines))
return all_lines[line_num]

但是readlines()给出了使用\n的行(可能在以后您必须使用size-1win_con = 1),但是您可以以不同的方式读取它以删除\n

代码语言:javascript
复制
all_lines = words.read().split('\n')  # it removes `\n`  in lines

代码语言:javascript
复制
all_lines = words.read().splitlines()  # it removes `\n`  in lines

最终使用列表压缩从列表上的元素中删除\n

代码语言:javascript
复制
all_lines = [line.strip() for line in all_lines]

使用strip()rstrip(),如果它们在文件中,也会删除空格/制表符。

random有许多有用的函数,无需使用索引就可以得到随机单词。

代码语言:javascript
复制
word = random.choice(all_lines)

return word 

顺便说一下:可能有一个问题--如果要为多个单词运行hangmap,那么choice() (或randint())可能会再次选择相同的单词。您必须记住已经使用过的单词并重复选择--或者您应该洗牌列表random.shuffle(all_lines),然后您可以使用for word in all_lines运行代码,它将使用不同的单词随机顺序。

draw()

HANGMANPICS永远不会改变,所以使用UPPER_CASE_NAME是件好事。但你可以把它放在外部功能。函数内部,当您运行draw()时,它会一次又一次地创建它(但是它的值总是相同的,因此不需要一次又一次地创建)

编辑: HANGMANPICS具有从06索引的元素,但您使用的是7

您可以使用<=而不是==来简化它。

代码语言:javascript
复制
if 1 <= what_to_do <= 6:  # EDIT: it has to be 6 instead of 7
    print(HANGMANPICS[what_to_do])
else:
    print(HANGMANPICS[0])

或者使用“反向”比较

代码语言:javascript
复制
if what_to_do < 1 or what_to_do > 6:  # EDIT: it has to be 6 instead of 7
    what_to_do = 0

print(HANGMANPICS[what_to_do])

list_fill()

可以使用*重复列表中的字符串。

代码语言:javascript
复制
def list_fill(size):
    return ["_"] * size-1

并使用return分配给position

代码语言:javascript
复制
positions = list_fill(len(temp_word))

这样,您就可以在一个循环中运行它,该循环可以用下一个单词重复游戏。

other代码

我不确定,但是addition = False可能应该在while-loop中,在每个改变addition = Truefor-loop之前

BTW: open()默认使用"r",这样您就不必使用它了。

编辑:我不知道我是否理解addition。当您不猜字母时,您只向tries添加了1,但也从tries中删除了很多次--即。如果您在word ABBA中猜到D48,那么它会减除2,因为a在这个单词中是两次。char b也是如此-它会减缩2。

只有当没有找到字母时,我才会添加1--并且在找到字母时保持当前值(而且它在word中存在的次数并不重要)。

代码语言:javascript
复制
    found = False
    
    for index, letter in enumerate(word):
        if letter == user_letter:
            positions[index] = letter
            win_con += 1
            found = True

    if not found:
        tries += 1
票数 4
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/243866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档