一种可能性是创建一个Coordinate
类,并表示每个可能的坐标对:
class Coordinate(models.Model):
x = models.IntegerField()
y = models.IntegerField()
board = models.ForeignKey(Board)
hit = models.BooleanField(default=False)
ship = models.ForeignKey(Ship, null=True) # assumes you have Ship objects somewhere
您可以按如下方式点击一个位置(假设board
是一个Board
对象):
x = 2
y = 3
location = board.coordinate_set.filter(x=x, y=y)
if location.ship != None:
# hit a ship! Do something with location.ship object
# either way, save that it was hit
location.hit = True
location.save()
这对于大型网格来说效率不高,但在这种情况下,每个板只有 100 个坐标,因此它可能是合理且直观的。