在战舰python游戏中循环遍历dict.items()

时间:2017-07-28 09:40:38

标签: python list dictionary

我正在使用Python制作游戏战舰并且已经陷入了一段代码。我制作了一个10x10网格板,玩家/计算机将放置5艘不同尺寸的船。船只存放在字典中。

我已经#hastagged我被困的地方。当玩家试图将船只放置在一个无法使用的地点时,它会打印出“无效选择”#34;并且玩家应该能够再次放置它。但循环继续,因此跳过放置该船。我试过调用函数" 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

1 个答案:

答案 0 :(得分: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(我从未理解两者之间的最佳做法)