我在Python中製作遊戲戰艦,並且陷入了一段代碼。我製作了一個10×10的網格板,玩家/電腦將放置5個不同尺寸的船。這些船被存儲在一本字典中。for循環播放dict.items()戰列艦蟒蛇遊戲
我有#標籤卡住的地方。當玩家試圖放置一艘不可用的地點時,它會打印出「無效的選擇」,玩家應該能夠重新放置它。但循環繼續,因此跳過放置該船。我已經嘗試過調用函數「player_place_ships」,但隨後它會重新開始並放置已經放置的船隻的重複項。
我正在考慮在for循環中創建一個計數,並在「無效選擇」之前再次從其停止的地方開始循環,但不確定是否可以從特定地點的dict.items開始for循環?
希望有一個善良的靈魂在那裏有一些建議,我相當新的python所以可能會使用壞/非正統的代碼在這裏。
下面是代碼:
#Dictionary for ships
ships = {'A': 5, 'B': 4, 'C': 3, 'S': 3, 'D': 2}
#Create player board
player_board = []
for player_row in range(10):
player_board.append([])
for player_col in range(10):
player_board[player_row].append('.')
#Print player board
def print_player_board(player_board):
for player_row in player_board:
print(" ".join(player_row))
def player_place_ships(player_board, ships):
for i, j in ships.items():
ori = input('Enter orientation, v or h: ')
x = int(input('Enter row: '))
y = int(input('Enter col: '))
place = x,y
placement = player_board[x][y]
if ori == 'v' and placement == '.':
for k in range(j):
player_board[x][y] = i
player_board[x+k][y] = i
elif ori == 'h' and placement == '.':
player_board[x][y] = i
player_board[x][y+k] = i
elif ori != 'v' or 'h' and placement != '.':
print('Invalid choice, please try again.') #This is where I'm stuck
player_place_ships(player_board, ships)
print_player_board(player_board)
請修復您的縮進。想想你想在'elif'中評估什麼。使用括號可能有幫助... – albert
首先,修復你的縮進。其次,閱讀[詢問用戶輸入,直到他們給出了有效的答覆](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response ),但也[我如何測試一個變量對多個值?](https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values)。 –