2017-07-28 100 views
0

我在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) 

下面是輸出的一個屏幕截圖,讓你知道我的意思: invalid choice

+0

請修復您的縮進。想想你想在'elif'中評估什麼。使用括號可能有幫助... – albert

+1

首先,修復你的縮進。其次,閱讀[詢問用戶輸入,直到他們給出了有效的答覆](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)。 –

回答

0

你可能有while ship_not_placed

def player_place_ships(player_board, ships): 
    for i, j in ships.items(): 
    ship_not_place = true 
    while ship_not_placed : 
     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 
     ship_not_place = false 
     elif ori == 'h' and placement == '.': 
     player_board[x][y] = i 
     player_board[x][y+k] = i 
     ship_not_place = false 
     elif ori != 'v' or 'h' and placement != '.': 
     print('Invalid choice, please try again.') 
解決您的問題

或只是一個while true和突破而不是改變ship_not_placed (我從未理解這兩者之間的最佳做法)

+0

非常感謝你們的這個訣竅!難以置信的是,一段時間:真假只是它需要的一切。我可能是過度的,而我的代碼我認爲= P – Tinadark

+0

@Tinadark這將是大多數編程語言的解決方案 – pwnsauce