(Python)2D阵列检查器 - 如何跳跃并抓住对手的棋子

时间:2016-11-04 03:39:09

标签: python arrays 2d coordinates

所以我有一个非常基本的游戏板:

  B W B W            with assigned coordinates of       1  2  3  4
  W B W B                                               5  6  7  8
  B W B W                                               9  10 11 12

这个游戏实际上不是跳棋,而是类似的。每个用户在游戏开始前选择要删除的一块(B或W)。所以我们将从这样的事情开始:

   - W B W
   W B W B
   B - B W

接下来,用户将能够“跳过”其他用户的作品。跳跃只能是水平或垂直,没有对角线大声跳跃。所以我首先要捕捉用户正在选择的棋子的坐标,以及他们跳跃后降落的目的地坐标:

   Bjump = input(BLACK, first select the coordinate of the piece you want to move as well as the coordinate where you would like to land. Please Separate Coordinates with a SINGLE space: ")

用户需要能够选择B @坐标'3',跳过W @ 2,然后降落@坐标1.这个过程不仅要将B块跳过W块,还要移除W块它跳过@坐标2.用' - '

替换它

给出输出:

  B - - W
  W B W B
  B - B W

我的第一个想法是做这样的事情:

   if(Bjump == "3 1"):
    if(grid[0][1] == 'W'):
        if(grid[0][2] == 'B'):
            grid[0][2] = '-'
            grid[0][1] = '-'
            grid[0][1] = 'B'
        else:
            print("oops! try again!")
   else:
        print("oops! You can only jump over W's!")

我的问题是,我不仅要为每种可能的场景创建一个if(声明),而且谁知道每场比赛的每一步都会有什么样的游戏板?

有人可以帮助我解决不仅如何去做,而且如何让它成为“通用”,无论游戏有多少种不同的方式?在此先感谢!!

2 个答案:

答案 0 :(得分:1)

被跳过的棋子始终是源和目标x,y坐标的平均值。考虑到这一点,你可以写下这样的东西:

board = [
    ['-', 'W', 'B', 'W'],
    ['W', 'B', 'W', 'B'],
    ['B', '-', 'B', 'W']
]

def print_board(board):
    for row in board:
        print(row)

def coords(board, num):
    num = int(num) - 1
    return num % len(board), num // len(board)

def jump(board, move):
    (src_x, src_y), (dst_x, dst_y) = (coords(board, x) for x in move.split())
    x_diff = abs(src_x - dst_x)
    y_diff = abs(src_y - dst_y)

    if sorted([x_diff, y_diff]) != [0, 2]:
        print('Oops, invalid coordinates')
        return

    mid_x = (src_x + dst_x) // 2
    mid_y = (src_y + dst_y) // 2

    if board[src_y][src_x] == '-':
        print('Oops, source cell empty')

    if board[dst_y][dst_x] != '-':
        print('Oops, target cell occupied')

    if board[mid_y][mid_x] == '-':
        print('Oops, no piece to jump over')

    if board[src_y][src_x] == board[mid_y][mid_x]:
        print('Oops, can\'t jump over piece with same color')

    board[dst_y][dst_x] = board[src_y][src_x]
    board[mid_y][mid_x] = '-'
    board[src_y][src_x] = '-'

move = '3 1'
print_board(board)
print('Execute move {}'.format(move))
jump(board, move)
print_board(board)

输出:

['-', 'W', 'B', 'W']
['W', 'B', 'W', 'B']
['B', '-', 'B', 'W']
Execute move 3 1
['B', '-', '-', 'W']
['W', 'B', 'W', 'B']
['B', '-', 'B', 'W']

请注意,上述内容仅适用于Python 3。

答案 1 :(得分:0)

如果您打印电路板如下:

for row in board:
print(" ".join(row)) 

...它以更好看的网格打印电路板,看起来更像是一个合适的GUI游戏类型。试试吧,你会看到。