【问题标题】:For loop over dict.items() in battleships python game对于战舰python游戏中的dict.items()循环
【发布时间】:2018-01-04 07:39:51
【问题描述】:

我正在用 Python 制作游戏战舰,但被一段代码卡住了。我制作了一个 10x10 的网格板,播放器/计算机将放置 5 艘不同尺寸的船。船只存储在字典中。

我已经#hastag了我卡住的地方。当玩家试图在不可用的位置放置一艘船时,它会打印“无效选择”并且玩家应该能够再次放置它。但循环继续,因此跳过放置那艘船。我试过调用函数“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)

这是输出的屏幕截图,所以您知道我的意思:

【问题讨论】:

标签: python list dictionary


【解决方案1】:

您可以通过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(我一直不明白两者之间的最佳做法是什么)

【讨论】:

  • 非常感谢 pwnsauce,成功了!令人难以置信的一段时间:真/假就是它需要工作的全部。我在编码时可能会想得太多,我认为 =P
  • @Tinadark 这将是大多数编程语言的解决方案
猜你喜欢
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-18
  • 1970-01-01
  • 2018-01-05
相关资源
最近更新 更多