在 Python 中创建和/或检查编号变量的优雅方法

问题描述 投票:0回答:1

我是一个试图学习 Python 的老家伙,所以我最后的编码经验是使用 BASIC - 不,不是 Visual Basic。 我理解一些与 Python 相关的概念,但我处于初级编码阶段,所以我使用“强力”逻辑编写了这个项目 - 基本上,将字符串分解为单个字母,然后用经典的“”测试每个字母猜单词类型游戏。

采用的基本逻辑是:

  1. 提出标准问候语。
  2. 从定义的列表中抓取一个随机单词 - 列表被缩短以使得 测试更容易。
  3. 将字符串分成单独的字母。
  4. 将未猜出的字母显示为“_”并缩短显示,以便 如果字符少于每个单词的变量数量, 它将显示“”。
  5. 如果该字母包含在之前的列表中,请更改“_” 猜测。
  6. 如果“_”被消除,则宣布您获胜。
  7. 如果您的猜测用完,则宣布您失败。
  8. 询问您是否要重播。

要扩展超过 4 位数字的单词的代码,我会复制并粘贴逻辑来创建 v4 和 output4 等 - 就像我说的,这是一种暴力方法。

所以,人们对以下内容的任何评论:

  1. 让它看起来更漂亮的技巧 - 或者更好的方法来完成同样的任务 目标(即,我不需要将字符串分解为单个字母 全部)
  2. 任何不必暴力命名所有变量和的技巧 有更小的代码自动生成正确的变量 您尝试猜测的随机单词的长度。

这是我的代码:

import random

words = ['rai', 'com']

turns = 5


def set_random():  # set the random word the user will try to guess
    ran = random.choice(words)
    main(ran)


def main(ran):  # main body, a giant function which avoids using global variables
    lives = turns  # used to pass in the initial message on how many lives and then count down for wrong guesses
    user_guesses = []
    print(f'Your word has {len(ran)} letters')
    flag = True  # used to end the game if the user guesses all of the letters

    while lives > 0 and flag == True:  # testing both conditions, lives still remain and game not won
        test_length = len(ran)

        # my logic to break down the random word string into individual letters used for the subsequent testing.  Also,
        # fixes display so that if the brute force placeholders for checking is longer than the actual answer, it will
        # display a black placeholder
        if test_length > 0:
            v0 = ran[0]
        else:
            v0 = ""

        if test_length > 1:
            v1 = ran[1]
        else:
            v1 = ""

        if test_length > 2:
            v2 = ran[2]
        else:
            v2 = ""

        if test_length > 3:
            v3 = ran[3]
        else:
            v3 = ""

        # brute for logic - initialize the output with default values which are then tested and changed in the next step
        output0 = "_"
        output1 = "_"
        output2 = "_"
        output3 = "_"

        # collect user guess, add it to the prior guess list and sort it for display later
        guess = input(str("Please guess a letter:  "))
        user_guesses.append(guess)
        user_guesses.sort()

        # the positive condition meaning the guess was included and then to change the display output to reflect guessed
        # letters or the "_" or show nothing if the word was shorter than the brute force placeholders
        if guess in ran:
            print(f'"{guess}" is in the word')
            if v0 == "":
                output0 = ""
            elif v0 in user_guesses:
                output0 = v0
            else:
                pass

            if v1 == "":
                output1 = ""
            elif v1 in user_guesses:
                output1 = v1
            else:
                pass

            if v2 == "":
                output2 = ""
            elif v2 in user_guesses:
                output2 = v2
            else:
                pass

            if v3 == "":
                output3 = ""
            elif v3 in user_guesses:
                output0 = v3
            else:
                pass

            print(f'You have guessed {user_guesses}')

        else:
            lives -= 1
            if v0 == "":
                output0 = ""
            elif v0 in user_guesses:
                output0 = v0
            else:
                pass

            if v1 == "":
                output1 = ""
            elif v1 in user_guesses:
                output1 = v1
            else:
                pass

            if v2 == "":
                output2 = ""
            elif v2 in user_guesses:
                output2 = v2
            else:
                pass

            if v3 == "":
                output3 = ""
            elif v3 in user_guesses:
                output0 = v3
            else:
                pass

        print("")
        print(f'Sorry, there is no "{guess}" is in the word')
        print(f'You have {lives} lives remaining')
        print(f'You have guessed {user_guesses}')
        print("")

        # command to display the user guesses with "_" for the unguessed numbers
        print(output0, output1, output2, output3)

        # logic to test if the game has been won by guessing all the correct letter - eliminating all "_"
        x = output0 + output1 + output2 + output3
        if "_" not in x:
            print("")
            print(f'You have correctly guessed "{ran}"! You have won the game!')
            print("")
            flag = False
        else:
            pass

    # code to end the game if all the lives are lost
    if lives == 0:
        print(f'Sorry, you are out of lives.  Your word was {ran}')
        print("")
    else:
        pass

    replay_game()


# function to replay the game starting with the random word being re-selected and passed to the main function
def replay_game():
    choice = input("Would you like to play again? (Y/N): ")
    choice = choice.lower()
    if choice == 'y':
        print("")
        set_random()
    else:
        print("")
        print("Thanks for playing!, good bye")


# standard greeting message - ask for name and if the user wants instructions on how to play
def greeting():
    print("Welcome to my game!")
    print("")
    name_player = input(str("Please input your name: "))
    print("")
    print(f'Hello {name_player}, let us begin the Word Guessing Game')
    instructions = input(str(f'Would you like instructions on how to play? Y/N: '))
    if instructions.upper() == "Y":
        print("")
        print(
            f'You will have {turns} lives to guess the right word.  Input letters until you solve the word or you run out of lives.')
        print(f'Now, we will start the game!')
        print("")
    else:
        print("")
        print(f'Then we will start the game!')
        print("")


greeting()
set_random()

我的解决方案有效并且可以扩展 - 但是,这是一种蛮力方法,我认为有更好的方法来编码。 然而,该函数中的编码确实达到了其预期目的。

我不知道的是:

  1. 我是否违反了任何编码经验规则? 比如我原来的 代码使用了全局变量,所以这是我的重新代码来解决这个问题。
  2. 像我一样划分我的代码是标准的还是我应该对其进行分段 放入更多函数以便代码函数更可重用? - 基本上,主要功能是巨大的。
  3. 自动生成变量并根据值赋值的更好方法 if/then 语句。 基本上,我可以结合以下步骤 缩短显示以匹配单词的长度并更改 猜测与“_”与在我的代码中使用多个步骤?

任何帮助将不胜感激。

python loops variables
1个回答
0
投票

即使这对于主 Stack Overflow 来说可能有点偏离主题,你的游戏逻辑也可以归结为相当惯用的 Python 之类的东西:

def word_guessing(word, turns):
    lives = turns
    user_guesses = set()
    word_letters = set(word)

    while True:
        if user_guesses >= word_letters:
            print(f'You have correctly guessed "{word}"! You have won the game!')
            break
        if lives <= 0:
            print(f"Sorry, you are out of lives.  Your word was {word}")
            break

        word_display = "".join(letter if letter in user_guesses else "_" for letter in word)
        print(f"You have guessed {sorted(user_guesses)}")
        print(f"You have {lives} lives remaining")
        print(word_display)

        while True:
            guess = input(str("Please guess a letter:  "))
            if len(guess) == 1:
                break
        user_guesses.add(guess)

        if guess in word_letters:
            print(f'"{guess}" is in the word')
        else:
            lives -= 1
            print(f'Sorry, there is no "{guess}" is in the word')


word_guessing("supercalifragi", 8)

主要思想是使用Python set来存储用户的猜测(以及单词中的字母集合,因此很容易比较这两个集合是否相同(即用户已经猜出了所有字母) ).

列表理解将目标单词中的每个字母格式化为下划线(如果没有猜到)以进行显示。

© www.soinside.com 2019 - 2024. All rights reserved.