【发布时间】: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