2011-12-15 107 views
0
SHIPS = (('AirCraftCarrier', 5), ('Battleship', 4), 
     ('Submarine', 3), ('Destroyer', 3), ('PatrolBoat', 2)) 
position = ('v', 'h') 

def setShip(self, board, graphics): 
     maxval = board.getSize() - 1 
     coords = [] 
     sizes = [(v) for k, v in SHIPS] 
     for i in sizes: 
      legal = False 
      while not legal: 
       pos = choice(position) 
       if pos == 'v': 
        x = randint(0, maxval-1) 
        y = some kind of code to change y while keeping x same 
       if pos == 'h': 
        x = some kind of code to change x while keeping y same 
        y = randint(0, maxval-1) 

       if not board.isOccupied(x, y): 
        legal = True 
        coords.append((pos, x, y)) 
      #return grid.displayShip(x, y) 
      return coords 

現在,如果選擇v=vertical選擇了Ÿ而X值保持不變值必須改變。這將導致我的船垂直放置。我不知道有什麼辦法可以做到這一點。我需要隨機選擇第一個值,然後是剛剛進入船長的值,但最後一個值不能大於9,因爲我的網格只能達到9.如何創建一個只有一個變量變化但其他變量保持不變的(x,y)列表?

+0

你只有改變的Y值不隨x做任何事情,是不是你需要什麼?所以就像`如果pos =='v':y = newy`,沒有提及x。 – yosukesabai 2011-12-16 03:30:28

回答

0

您必須取出您希望不會從正在檢查可用位置的while循環中更改的變量。你可以以多種方式做到這一點。其中一種選擇是:

def setShip(self, board, graphics): 
     maxval = board.getSize() - 1 
     coords = [] 
     sizes = [v for k, v in SHIPS] 
     for i in sizes: 
      legal = False 
      x = randint(0, maxval-1) 
      y = randint(0, maxval-1) 
      pos = choice(position) 
      while not legal: 
       if pos == 'v': 
        y = y+1 if y < 9 else 0 
       if pos == 'h': 
        x = x+1 if x < 9 else 0 
       if not board.isOccupied(x, y): 
        legal = True 
        coords.append((pos, x, y)) 

      return coords 

請注意,我也限制了職位可以承擔的價值。如果船隻從一側消失,它將從另一側出現。這個代碼的問題是,船總是在一個方向(從0 - > 9)。你應該改變這可能選擇你想要的方向。例如:

sense = choice([1, -1]) 

,然後在內部循環,福爾例如:

y = y + sense if y < 9 else 0