Python Угадай число

Это мой взгляд на игру с числами. У пользователя есть три попытки угадать случайно выбранное число. Число от 0 до 9 включительно. Он говорит пользователю угадывать больше или меньше и показывает число, если игра проиграна.

Ввод, который не является числом от 0 до 9, включая, не принимается, и курсор останется в той же строке.

Зеленый — победа, красный — повтор.

Я протестировал код, он работает правильно. Пожалуйста, вперед.

guess_the_number.py

"" "У пользователя есть три попытки угадать, какое число было выбрано случайным образом" "" __all__ = []

импортировать случайную строку импорта из colorama import deinit, init right_answer = random.choice (string.digits) as_int = int (right_answer) MSG_ANS = 'Ответ был' + right_answer MSG_ASK = 'Угадай число (0-9)' MSG_OK = '  033[92mCorrect!33[0m'
MSG_TRY = '33[91mTry again *33[0m'


def ask(msg_wrong):
    """
    One attempt

    Non-digits are not accepted

    Digits accepted are removed from the pool
    and are not accepted in subsequent attempts
    """
    global pool

    cursor_up = '33[A'

    cursor_up_ask = cursor_up + '                       '

    while True:
        answer = input(MSG_ASK)

        if answer and answer in pool:
            break

        answer_sz = len(answer)
        answer_sz = answer_sz * ' '

        line = cursor_up_ask + answer_sz + cursor_up

        print(line)

        print()
        print()

        print(line, end='r')

    if answer == right_answer:
        print(MSG_OK)

        exit()

    if msg_wrong == MSG_TRY:
        i = int(answer)

        if i > as_int:
            hint=">"
        else:
            hint="<"

        msg_wrong = msg_wrong.replace('*', hint)

    print(msg_wrong)

    pool = pool.replace(answer, '')


if __name__ == '__main__':
    pool = string.digits

    init()

    ask(MSG_TRY)

    ask(MSG_TRY)

    ask(MSG_ANS)

    deinit()

2 Answers
2

Positives

  • Your function docstring was informative and helped me understand the code better.
  • Good use of variables like cursor_up to manage the ANSI control characters

Small improvements

  • As long as you’re bringin in colorama, can you use any of the named constants in provides instead of the control characters?
  • If you need to do something multiple times, I like to see if there’s a good way to do n times instead. See if you can make the number of turns more configurable.
  • I’m not sure what you’re doing with line = cursor_up_ask + answer_sz + cursor_up. This would be a good place for a comment or a function with a clear name.
  • You’re taking len(answer), but shouldn’t that always be 1? My understanding is that you’re expecting a one-digit answer. It would be nice to have some error handling so that, e.g. 23 isn’t treated as a valid guess.
  • You could eliminate the pool global by wrapping it and your functions together in a class. You could also eliminate the global by having more focused functions.
  • Instead of doing a find-replace on the * in MSG_TRY, you can do something like this:
MSG_TRY = '33[91mTry again {}33[0m'
msg_wrong = msg_wrong.format(hint)

Larger gripes

  • I’m finding the flow of the program hard to follow. Consider breaking it down into smaller functions so it’s more clear what’s going on. It could look something like:
def play_one_turn(final_turn = False):
    guess = get_player_input()
    if guess == right_answer:
        print(OK_MSG)
        return True
    if not final_turn:
        show_hint(guess)
    else:
        print(MSG_ANS)

(I’m not saying this is the best way to do things. It’s showing how smaller well-named functions can give more clarity with the same structure)

  • exit() in the middle of a function is suspicious. (Is the code missing from sys import exit?) I’d expect to see it at the end of a main function to return a status code back to the user. It should not be used for control flow. It would make more sense to return True or False depending on whether the guess is correct, and let the caller manage things from there.

    Your code does work, nice try 🙂

    It’s an interesting exercise. If you are open to another way of approaching the game, here’s what I’d suggest:

    import random
    import string
    
    def possible_answers() -> list:
        #['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        возвращение [char for char in string.digits]
    
    def generate_answer () -> str: return random.choice (possible_answers ()) def ask_for_input () -> str: print ('Ваше предположение>', end = '') return input () def new_game (max_attempts: int): правильно_answer = generate_answer () попытки = []
        print ('Добро пожаловать в новый раунд :)') в то время как len (пытается) 
    • Мы создаем новую игру после окончания предыдущей.

    • В каждой игре мы:

      • принять max_attempts как конфигурация игры

      • генерировать случайный правильный ответ

      • принимать попытки и действовать в соответствии с ними

    • Вы можете легко изменить случайный набор, изменив possible_answers() метод

    • Я игнорирую здесь форматирование вывода, но его можно легко добавить в new_game() метод.

    Если вы не против немного почитать, ТВЕРДЫЙ это то, что стоит изучить. Надеюсь, вам понравится чтение и продолжайте в том же духе 🙂

    • 1

      Я действительно собираюсь проголосовать против этого ответа. Вы предоставляете альтернативный код, но без объяснения причин, почему указанный код лучше, чем код OP.

      - Программист

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *