【问题标题】:My display menu repeats multiple times when an input is entered输入输入时,我的显示菜单重复多次
【发布时间】:2018-08-26 16:35:16
【问题描述】:

我在自己提出的程序创意中练习类和继承。基本上我正在制作一个街机游戏菜单模拟器,可以玩两种模式,单人游戏和多人游戏。每次我输入一个选项,无论是 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()

【问题讨论】:

  • 你能展示你的输出吗?或尝试添加input('') 并调试复制菜单代码的代码到底在哪里
  • @Surya Tej 你准备好玩了吗?输入 1 表示是,2 表示否 1 从以下选项之一中选择,输入相应的数字 1. 单人游戏 2. 多人游戏 在此处输入您的选择: 2 从以下选项之一中选择,输入相应的数字 1. 单人玩家 2. 多人游戏 在此处输入您的选择: 2 从以下选项之一中选择,输入相应的数字 1. 单人游戏 2. 多人游戏 在此处输入您的选择: 2 输入您的姓名开始
  • 当我在菜单方法中添加输入时,它仍然重复但有一个空白空格@SuryaTej

标签: python class object


【解决方案1】:

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 之外的任何内容,则会显示第三次。

如果不希望菜单显示两三次,就不要调用该方法两三次。


如果您只想显示一次菜单并记住选择,而不是显示两次或三次,则需要使用您在ready_or_not 中创建的self.ready 属性,而不是再次调用该方法。

但是,这仍然无法按原样工作,因为您的班级设计很奇怪。您已经创建了两个独立的实例,mp,每个实例都有自己独立的属性。我不确定为什么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)

【讨论】:

  • 很有道理,我在想,但不是 100% 确定,非常感谢!感谢你的帮助! @abamert
  • @nathan 您能否解释一下您如何在代码中使用@classmethod
【解决方案2】:

我花了一段时间才弄明白,但似乎当您完成了 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!")

编辑

看来我迟到了

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2020-03-12
    • 2021-09-12
    • 2020-11-30
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多