Мое меню дисплея повторяется несколько раз при вводе - PullRequest
0 голосов
/ 26 августа 2018

Я занимаюсь практикой и наследованием в рамках идеи программы, которую я придумал сам.По сути, я делаю симулятор аркадного игрового меню, в котором можно играть в двух режимах: одиночном и многопользовательском.Каждый раз, когда я ввожу выбор, 1 или 2, меню отображается пару раз, а затем оно продолжает принимать ввод, я хочу, чтобы меню отображалось только один раз.Вот мой код:

    # Suppose you are at an arcade and you and your friend want to play a multiplayer game that requires UI.
# Make the game ask for the users name and age to see if they can play, make the program so that it can add a friend.
# If any of the players are under the age of 18, they are not allowed to  play, otherwise proceed.
# **EXTRA CREDIT** --> Add a functionality which adds the players to a list until the list reaches 4 players, then stop adding to the list.

# arcade_game.py
import sys


# give the user a greeting
import self as self

lst = []


class menu:
    def __init__(self, ready):
        self.ready = ready

    #display menu
    @classmethod
    def display_menu(self):
        print("Pick from one of the choices below, type in the corressponding number")
        print("1. single player \n"
              "2. Multiplayer")
        choice = int(input("Enter your choice here: "))
        return choice

    # ready or not function to see if the user is ready to play
    def ready_or_not(self):
        # see if user types 1 or 2 with try & except
        try:
            # ask user if they are ready
            self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
            self.display_menu()
        except ValueError:
            print("You did not type 1 or 2, please try again!")


# add players class
class player(menu):
    # add a default player to __init__(), **(since there has to be at least one player)**
    def __init__(self, ready, player1):
        super().__init__(ready)
        self.player1 = player1

    # single player method
    def set_name(self):
        self.player1 = input("Enter your name for single player mode")
        print("Lets play! ", self.player1)

    # multiplayer method
    def set_names(self):
        try:
            self.player1 = input("Enter your name to begin")
            lst.append(self.player1)
            # add another player to continue
            while len(lst) <= 4:
                add = input("Add player here: ")
                lst.append(add)
                if len(lst) == 4:
                    print("Player limit reached!")
                    break;
        except ValueError:
            print("You didnt enter valid input, please try again")

    # get the names of the players only if 1 is picked from display_menu() above, including player1
    def check_choice(self):
        if self.display_menu() == 1:
            self.set_name()
        elif self.display_menu() == 2:
            self.set_names()
        else:
            print("Exiting....")
            print("Goodbye!")
            sys.exit(0)


m = menu("yes")
m.ready_or_not()
p = player("yes", "test")
p.check_choice()

Ответы [ 2 ]

0 голосов
/ 26 августа 2018

Мне потребовалось некоторое время, чтобы понять, но, похоже, когда вы закончите с display_menu() своим звонком ready_or_not(), вам нужно удалить display_menu() из готовности или не так

   # ready or not function to see if the user is ready to play
    def ready_or_not(self):
        # see if user types 1 or 2 with try & except
        try:
            # ask user if they are ready
            self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
#            self.display_menu()
        except ValueError:
            print("You did not type 1 or 2, please try again!")

РЕДАКТИРОВАТЬ

похоже, что я опоздал на вечеринку

0 голосов
/ 26 августа 2018

ready_or_not звонки self.display_menu():

def ready_or_not(self):
    # see if user types 1 or 2 with try & except
    try:
        # ask user if they are ready
        self.ready = int(input("Are you ready to play? Type 1 for yes, 2 for no"))
        self.display_menu()
    except ValueError:
        print("You did not type 1 or 2, please try again!")

check_choice также вызывают self.display_menu() как минимум один раз и дважды, если вы в первый раз что-нибудь наберите, кроме 1:

def check_choice(self):
    if self.display_menu() == 1:
        self.set_name()
    elif self.display_menu() == 2:
        self.set_names()
    else:
        print("Exiting....")
        print("Goodbye!")
        sys.exit(0)

Ваш код верхнего уровня вызывает ready_or_not() для одного экземпляра меню:

m = menu("yes")
m.ready_or_not()

… и check_choice() для другого:

p = player("yes", "test")
p.check_choice()

Итак, ваша программаотображает меню дважды, а затем в третий раз, если вы вводите что-либо, кроме 1.

Если вы не хотите, чтобы меню отображалось два или три раза, не вызывайте метод два или три раза.


Если вы хотите отобразить меню только один раз и запомнить выбор, вместо того, чтобы отображать его два или три раза, вам нужно использовать атрибут self.ready, который вы создаете в ready_or_not, вместоповторного вызова метода.

Однако, это все равно не будет работать как есть, потому что дизайн вашего класса странный.Вы сделали два отдельных экземпляра, m и p, каждый из которых имеет свои независимые атрибуты.Я не уверен, почему player наследуется от menu во-первых (или почему display_menu является @classmethod, или почему он вызывает свой параметр self вместо cls, если он один, иразличные другие вещи), но, учитывая, что player является menu в вашем дизайне, вы, вероятно, просто хотите один player экземпляр, например:

p = player("yes", "test")
p.ready_or_not()
p.check_choice()

И затем вы можетеизменить check_choice вот так:

def check_choice(self):
    if self.choice == 1:
        self.set_name()
    elif self.choice == 2:
        self.set_names()
    else:
        print("Exiting....")
        print("Goodbye!")
        sys.exit(0)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...