战舰游戏:如何检查用户输入是否在列表列表中?

Battleship game: how can I check if user input is in a list of lists?

我正在创建一个类似战舰的游戏,我必须在其中检查用户是否击中了一艘船,或者 not.I 正在尝试检查输入是否是 x,y 坐标列表的一部分8艘(战列舰)。 我的大清单如下:

 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]    

到目前为止,这是我唯一的工作,但现在我意识到很难将其推广到所有船只和所有坐标。

我也试过将输入用作字符串并检查它是否已发货,但它总是 return 错误。如有任何帮助,我们将不胜感激!

我知道这可能不是您正在寻找的答案,但我可能会以不同的方式设置它以帮助您解决问题。我将 ships 设置为字典,其中每艘船作为键,坐标是元组列表。它看起来像这样:

ships = {"ship1": [("7", "6"), ("2", "5"), ("3", "8")], "ship2": [and so on]}
guess = raw_input("What is your guess? ")

现在,在不放弃太多游戏内容的情况下,您的下一步是遍历字典中的每艘船,并检查猜测的坐标是否与任何船的任何值匹配。

希望对您有所帮助。

假设您使用列表:

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 可能会更整洁。

我建议使用 NumPy 二维数组。

您可以将棋盘初始化为零矩阵,然后在适当的行和列中标记每艘船的编号。那么查看用户命中了哪艘船就很简单了。

小例子:

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!")

你是在倒着看这个。不要与船只核实它们是否存在于被射击的位置,让 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