我正在创建一个类似战舰的游戏,在那里我必须检查用户是否已经击中了一艘船。我正在尝试检查输入是否是8艘船(战舰)的x,y坐标列表的一部分)。 我列出的清单如下:
ships = [ship1][ship2][ship3] and so on (6 ships).
每艘船的清单是:
ship1 = ['7','6,]['2','5']['3','8']
等等。
到目前为止,我正在使用:
if input[0] ==ship1[0] and input[1] == ship1[1]
到目前为止,这是我唯一能够完成工作的东西,但现在我意识到要为所有船只和所有坐标进行概括是很难的。
我也尝试将输入用作字符串并检查它是否已发货,但它总是返回false。任何帮助将不胜感激!
答案 0 :(得分:3)
假设您 使用列表:
ship1 = [(1,1),(1,2),(1,3)]
ship2 = [(3,4),(3,5),(3,6)]
...
ships = [ship1, ship2, ... ]
shot = (3,5)
for ship in ships:
if shot in ship:
hit...
break
但正如其他人所说,dict可能更整洁。
答案 1 :(得分:1)
我意识到这可能不是你想要的答案,但我可能会设置一些不同的方式来帮助自己。我将ships
设置为一个字典,其中每个船只作为一个键,坐标是一个操作列表。它看起来像这样:
ships = {"ship1": [("7", "6"), ("2", "5"), ("3", "8")], "ship2": [and so on]}
guess = raw_input("What is your guess? ")
现在,在没有放弃太多游戏的情况下,你的下一步就是在字典中循环每艘船并检查猜测的坐标是否与任何船只的任何值相匹配。
我希望有所帮助。
答案 2 :(得分:1)
我建议使用NumPy 2D数组。
您可以将电路板初始化为零矩阵,然后在相应的行和列中标记每个电路板的编号。然后检查用户击中哪艘船非常简单。
小例子:
import numpy as np
# create board
board = np.zeros((8,8))
board[2:5,4] = 1
board[6,5:7] = 2
print(board)
# check shot
input = (2,4)
ship_num = board[input]
if ship_num != 0:
print("hit!")
答案 3 :(得分:1)
你正在向后看。不要检查船只,看看它们是否存在于被射击位置,让BOARD负责知道船只在哪里,向对手报告有击中,并向船舶报告它被击中
class Board(list):
def __init__(self, size, ships):
for row in range(size):
self.append([0] * size)
self.ships = ships
for ship in self.ships:
# each ship is a list of tuples (column, row)
for coord in ship:
x, y = coord
self[y][x] = ship # store a reference to the ship at
# each location the ship is in
def check_hit(self, location):
x, y = location
if self[y][x]:
# there's a ship here!
ship = self[y][x]
self[y][x] = 0 # don't report another hit at this location
still_alive = ship.get_shot(location)
# tell the ship it's been hit and ask it if it's still alive
if still_alive:
return Ship.ALIVE # tell the caller that it hit something
else:
self.ships.remove(ship)
return Ship.DEAD # tell the caller it KILLED something
else:
return False # you missed
然后你的船可能是:
class Ship(object):
ALIVE = 1
DEAD = 2
def __init__(self, type_, locations):
self.type = type_ # battleship, destroyer, etc
self.locations = locations
@property
def is_alive(self):
return bool(self.locations)
# is self.locations is empty, this is a dead ship!
def get_hit(self, location):
self.locations.remove(location)
return self.is_alive