Python输入语句
我已经创建了一个类似战舰的游戏,除了一个细节外,其他都完成了 我有以下输入语句: x、 y=输入(“在此处输入两个数字:”).split() 输入与玩家选择的坐标对应的2个数字。我还需要能够为退出或帮助选项处理输入'q'或'h'。然而,由于我从这个语句中获取了两个变量,当只输入了q或h时,我得到了一个错误,即该语句需要两个元素来解包,这是有意义的。有没有关于如何避开这个问题的建议Python输入语句,python,input,Python,Input,我已经创建了一个类似战舰的游戏,除了一个细节外,其他都完成了 我有以下输入语句: x、 y=输入(“在此处输入两个数字:”).split() 输入与玩家选择的坐标对应的2个数字。我还需要能够为退出或帮助选项处理输入'q'或'h'。然而,由于我从这个语句中获取了两个变量,当只输入了q或h时,我得到了一个错误,即该语句需要两个元素来解包,这是有意义的。有没有关于如何避开这个问题的建议 import random, math class oceanTreasure: def __ini
import random, math
class oceanTreasure:
def __init__(self):
self.board = self.board()
self.found = 0
self.left = 3
self.sonarsLeft = 20
self.chests= []
self.chest()
def board(self):
board = []
for x in range(16): # the main list is a list of 60 lists
board.append([])
for y in range(61): # each list in the main list has 15 single-character strings.
board[x].append('~')
return board
def chest(self):
chest1 = [random.randint(0,60), random.randint(0,15)]
chest2 = [random.randint(0,60), random.randint(0,15)]
chest3 = [random.randint(0,60), random.randint(0,15)]
self.chests = [chest1, chest2, chest3]
def getChestsLeft(self):
return self.found
def getChests(self):
return self.chests
def getTreasuresLeft(self):
return self.left
def getSonarsLeft(self):
return self.sonarsLeft
def dropSonar(self,x,y):
ySonar = ['a','b','c','d','e','f','g']
whichAxis, axis = self.checkDistance(x,y)
if whichAxis == True:
sonar = axis
if whichAxis == 'xaxis':
sonar = axis
elif whichAxis == 'yaxis':
sonar = ySonar[axis-1]
elif whichAxis == None:
sonar = axis
self.board[int(y)][int(x)] = sonar
self.sonarsLeft -=1
return axis
def checkDistance(self,x,y):
closest = self.chests[0]
distance = 100
for chest in self.chests:
temp = math.sqrt(math.pow((chest[0]-int(x)),2) + math.pow((chest[1]-int(y)),2))
if temp < distance:
closest = chest
distance = temp
xaxis =math.fabs((closest[0] - int(x)))
yaxis = math.fabs((closest[1]-int(y)))
if yaxis == 0 and xaxis == 0:
self.chests.remove(closest)
self.found +=1
self.left -=1
return True, 'X'
elif xaxis <= 9 and yaxis <=5 :
if yaxis == 0 :
return 'xaxis',int(math.fabs(xaxis))
if xaxis == 0 :
return 'yaxis',int(math.fabs(yaxis))
if min(xaxis//2,yaxis) ==(xaxis//2) :
return 'xaxis', int(math.fabs(xaxis))
elif min(xaxis//2,yaxis) == (yaxis) or xaxis == 0 :
return 'yaxis', int(math.fabs(yaxis))
else: return None,0
def drawBoard(self):
firstLine = ' '
for i in range(1,7):
firstLine += (' '*9) + str(i)
print(firstLine)
secondLine = ' '
secondLine += ('0123456789' *6)
print(secondLine)
print()
i = 0
for i in range(0,16):
boardRow = ''
for x in range(0,61):
boardRow += str(self.board[i][x])
if i < 10:
print(str(i) +' ' + str(boardRow) + str(i))
if i >= 10:
print(str(i) +' ' + str(boardRow) + str(i))
print()
print(secondLine)
print(firstLine)
device = 'devices'
if self.sonarsLeft ==1:
device = 'device'
print('You have %s sonar %s availabe. You have found %s treasures and have %s left' %(self.sonarsLeft, device, self.found, self.left))
ocean = oceanTreasure()
ocean.drawBoard()
gameOver = False
instructionsList = ['This is a treasure hunting game.' , 'You begin the game with 20 sonar devices available (each device has a range of 9 units in the x axis and 5 in the y axis).','When you place a device, if an "O" is displayed that means there are no chests in range.', 'If a number from 1-9 is displayed, the closest chest is within n units away on the X axis.', 'If a letter from a-e is displayed, the closest chest is n units away on the Y axis (a =1, b =2 and so on...).', 'The game ends when you run out of sonar devices, all the treasure is found or you enter "q" to quit.', 'Thanks for playing and happy hunting!']
while ocean.getTreasuresLeft() != 0 and ocean.getSonarsLeft() >0 and gameOver == False:
response = False
coordinate = False
while response == False:
inputString = input("Enter two numbers seperated by a space (X Y): ")
if inputString == 'q':
gameOver = True
response = True
elif inputString == 'h':
for instruction in instructionsList:
print(instruction)
response = True
else:
try:
x,y = inputString.split()
assert int(x) <=60 and int(y) <=15
response = True
coordinate = True
except AssertionError:
print('Please enter a valid move')
if gameOver == True:
break
#whichAxis, axis =ocean.checkDistance(x,y)
#print(axis)
if coordinate == True:
axis = ocean.dropSonar(x,y)
ocean.drawBoard()
if axis == 'X':
print('Congratulations, you have found a treasure!')
if ocean.getTreasuresLeft() == 0:
print('Congratulations, you found all the treasure')
elif ocean.getSonarsLeft() == 0:
print('Sorry, you ran out of sonar devices, the remaining chests were: %s ' % str(ocean.getChests()))
导入随机、数学
类别:
定义初始化(自):
self.board=self.board()
self.found=0
self.left=3
self.sleft=20
self.chests=[]
self.cost()
def板(自身):
董事会=[]
对于范围(16)中的x:#主列表是由60个列表组成的列表
董事会。追加([]))
对于范围(61)中的y:#主列表中的每个列表都有15个单字符串。
线路板[x]。追加(“~”)
返回板
def箱(自身):
chest1=[random.randint(0,60),random.randint(0,15)]
chest2=[random.randint(0,60),random.randint(0,15)]
chest3=[random.randint(0,60),random.randint(0,15)]
self.chests=[chest1,chest2,chest3]
def getChestsLeft(自身):
找回自我
def getChests(自身):
归还自己的箱子
def getTreasuresLeft(自):
自左返回
def getSonarsLeft(自身):
返回self.sleft
def吊放声纳(自身、x、y):
ySonar=['a','b','c','d','e','f','g']
whichAxis,axis=自检距离(x,y)
如果whichAxis==True:
声纳=轴
如果whichAxis=='xaxis':
声纳=轴
elif whichAxis=='yaxis':
声纳=声纳[轴1]
elif whichAxis==无:
声纳=轴
自动板[int(y)][int(x)]=声纳
self.sleft-=1
返回轴
def检查距离(自身、x、y):
最近的=自身胸部[0]
距离=100
对于self.chests中的胸部:
temp=math.sqrt(math.pow((胸部[0]-int(x)),2)+math.pow((胸部[1]-int(y)),2))
如果温度<距离:
最近的=胸部
距离=温度
xaxis=math.fabs((最近的[0]-int(x)))
yaxis=math.fabs((最近的[1]-int(y)))
如果yaxis==0和xaxis==0:
自。箱。移除(最近的)
self.found+=1
self.left-=1
返回True,'X'
elif xaxis 0和gameOver==False:
响应=错误
坐标=假
当响应==False时:
inputString=input(“输入两个用空格分隔的数字(X Y):”)
如果inputString=='q':
gameOver=True
响应=真
elif inputString=='h':
对于说明列表中的说明:
打印(说明)
响应=真
其他:
尝试:
x、 y=inputString.split()
assert int(x)如何将测试分离得更清楚一些:
input_string = input("Enter two numbers here: ")
if input_string == 'q':
do_quit()
elif input_string == 'h':
do_help()
else:
x,y = input_string.split()
这样,您就可以针对您的特殊情况进行测试,如果找不到x和y,则可以对其进行处理。如何将测试分离开来,以便更清楚一些:
input_string = input("Enter two numbers here: ")
if input_string == 'q':
do_quit()
elif input_string == 'h':
do_help()
else:
x,y = input_string.split()
这样,您可以针对特殊情况进行测试,如果找不到x和y,则处理它们。可能是这样,例如:
a = input("text")
b = a.split()
if len(b) == 1:
if b[0] == 'q':
return
elif b[0] == 'h':
print 'it is help ... '
elif len(b) == 2:
# process for two inputted numbers
可能是这样,例如:
a = input("text")
b = a.split()
if len(b) == 1:
if b[0] == 'q':
return
elif b[0] == 'h':
print 'it is help ... '
elif len(b) == 2:
# process for two inputted numbers
您只需分离输入:
# get the input
ipt = input("Enter two numbers here: ")
# check if your option is entered
if ipt == 'q' or ipt == 'h':
# do something
else:
x,y = ipt.split()
您只需分离输入:
# get the input
ipt = input("Enter two numbers here: ")
# check if your option is entered
if ipt == 'q' or ipt == 'h':
# do something
else:
x,y = ipt.split()
这么简单。我一直在想我必须分开最初的输入,游戏结束了!谢谢你的帮助!不客气!简单的解决方案总是最好的:)。听起来你正在进行一个有趣的项目!如果回答了您的问题,请随意将此(或其他)答案标记为已接受。可以!如果有人觉得无聊,附上一份游戏副本:)我很想听听你的想法!这么简单。我一直在想我必须分开最初的输入,游戏结束了!谢谢你的帮助!不客气!简单的解决方案总是最好的:)。听起来你正在进行一个有趣的项目!如果回答了您的问题,请随意将此(或其他)答案标记为已接受。可以!如果有人觉得无聊,附上一份游戏副本:)我很想听听你的想法!