所以我有一个非常基本的游戏板:
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 block 跳过W block ,还应该删除W block 它跳到了@坐标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(语句),而且谁知道每个游戏的每一步棋盘会是什么样子?
有人可以帮助我思考如何去做,以及如何使其“通用”,无论游戏有多少种不同的玩法吗?提前致谢!!
最佳答案
被跳过的棋子始终是源和目标 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。
关于python - (Python) 2D Array Checkers - 如何跳跃并吃掉对手的棋子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414908/