2015-11-28 47 views
0

我正在用Python創建一個戰艦遊戲。我正在嘗試生成兩個位置的船,但確保位置鏈接的while循環會一直持續下去。我使用Python 2.7生成兩個鏈接的2D陣列位置

from random import randint 
board = [] 
for x in range(5): 
    board.append(["O"] * 5) 
def print_board(board): 
    for row in board: 
     print " ".join(row) 
print "Let's play Battleship!" 
print_board(board) 
def random_row(board): 
    return randint(0, len(board) - 1) 
def random_col(board): 
    return randint(0, len(board[0]) - 1) 
ship_row1 = random_row(board) + 1 
ship_col1 = random_col(board) + 1 
ship_row2 = random_row(board) + 1 
ship_col2 = random_col(board) + 1 
print "Generating ship..." 
while (ship_row2 != ship_row1 + 1 or ship_row2 != ship_row1 - 1): 
    ship_row2 = random_row(board) + 1 
while (ship_col2 != ship_col1 + 1 or ship_col2 != ship_col1 - 1): 
    ship_col2 = random_col(board) + 1 
print ship_row1 
print ship_col1 
print ship_row2 
print ship_col2 

回答

1

要回答你的問題,你已經交換了orand運營商。嘗試重新思考循環後面的布爾邏輯。

可是......你爲什麼不乾脆更換:

while (ship_row2 != ship_row1 + 1 or ship_row2 != ship_row1 - 1): 
    ship_row2 = random_row(board) + 1 
while (ship_col2 != ship_col1 + 1 or ship_col2 != ship_col1 - 1): 
    ship_col2 = random_col(board) + 1 

由:

ship_row2 = random.choice([ship_row1 + 1, ship_row1 - 1]) 
ship_col2 = random.choice([ship_col1 + 1, ship_col1 - 1]) 

,所以你只想要,而不是試圖他們所有的任意兩個位置之間進行選擇?

+0

我沒有使用「和」,因爲我從if語句開始。 – marloso2

0

您需要使用and,而不是or

while (ship_row2 != ship_row1 + 1 and ship_row2 != ship_row1 - 1): 
    ship_row2 = random_row(board) + 1 
while (ship_col2 != ship_col1 + 1 and ship_col2 != ship_col1 - 1): 
    ship_col2 = random_col(board) + 1 

隨着or,這就像說「循環直到ship_row2等於ship_row1 +1直到ship_row2等於ship_row1 -1這是不可能