我目前正在用 Python 开发一个猫捉老鼠的程序,当我设置我的板时,我想知道是否有更有效的方法来替换我的二维列表中的“占位符”。目前我在做:
# setting dimensions and printing all placeholders as '[ . ]'
rows, cols = (6, 10)
board = [['[ . ]' for i in range(cols)] for j in range(rows)]
# manually changing placeholders to add numbers for coordinate system on each side
# changing values of top of board
board[0][0] = ' '
board[0][1] = ' 1 '
board[0][2] = ' 2 '
board[0][3] = ' 3 '
board[0][4] = ' 4 '
board[0][5] = ' 5 '
board[0][6] = ' 6 '
board[0][7] = ' 7 '
board[0][8] = ' 8 '
board[0][9] = ' '
# changes left side of board
board[1][0] = ' 1 '
board[2][0] = ' 2 '
board[3][0] = ' 3 '
board[4][0] = ' 4 '
board[5][0] = ' '
板的右侧和底部依此类推。最终董事会看起来像: empty playing board
我想有一种更有效的方法可以做到这一点,但我不确定我会怎么做。任何帮助将不胜感激,谢谢。
最佳答案
下面的解决方案使用 numpy
库,因为它是用于矩阵操作的优秀(如果不是the)库。您可能熟悉也可能不熟悉它,因此我尝试使用更明确的代码并相应地进行评论。
示例代码使用了两个函数:
build()
构建初始棋盘。show()
在游戏的任何阶段显示棋盘。
future 发展:
我留下了一些内容供您自行开发。一些想法是:
- 代码可以优化成一个
类
。 - 包含一个
move()
函数,它可以根据每个玩家的移动更新棋盘。但我会把这个小项目留给你去研究和实现。
示例代码:
import numpy as np
def build() -> np.ndarray:
"""Build the board.
Returns:
A new playing board as a ``np.ndarray``.
"""
# Board configuration.
cols = 8
rows = 4
# Create horizontal, vertical and dot lists.
h = list(range(0, cols+1)) + [0]
v = list(range(0, rows+1)) + [0]
d = ['.' for i in range(1, cols+1)]
# Initialise a new (empty) matrix of size.
m = np.zeros([rows+2, cols+2], dtype=str)
# Populate vertical labels.
m[:, 0] = np.array(v)
m[:, -1] = np.array(v)
# Populate horizontal labels.
m[0, :] = np.array(h)
m[-1, :] = np.array(h)
# Populate dots.
m[1:-1, 1:-1] = np.array(d)
# Replace remaining zeros with a space.
m[m == '0'] = ' '
# Return the new playing board.
return m
def show(board):
"""Display the ndarray as a board.
Args:
board (np.ndarray): Board to be displayed.
"""
for row in board:
print(' '.join(row))
# Create and show a new playing board.
board = build()
show(board=board)
新董事会:
1 2 3 4 5 6 7 8
1 . . . . . . . . 1
2 . . . . . . . . 2
3 . . . . . . . . 3
4 . . . . . . . . 4
1 2 3 4 5 6 7 8
玩吧!
我不确定游戏是怎么玩的,但假设每个玩家在下面轮流,Player1 是 x
,Player2 是 o
。
棋盘会随着每个玩家的棋子而更新。
# Update `board` for [row, col]
board[1, 3] = 'x'
board[3, 6] = 'o'
# Show the updated board.
show(board=board)
更新版:
1 2 3 4 5 6 7 8
1 . . x . . . . . 1
2 . . . . . . . . 2
3 . . . . . o . . 3
4 . . . . . . . . 4
1 2 3 4 5 6 7 8
关于python - 更有效的方法来替换二维列表中的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64198990/