gpt4 book ai didi

python - 如何使用 matplotlib 创建某种类型的网格

转载 作者:行者123 更新时间:2023-11-30 23:24:45 25 4
gpt4 key购买 nike

我编写了一个程序(Python 3.3)来解决n皇后问题,并以列表的形式给出解决方案(例如[1, 5, 7, 2, 0, 3, 6, 4])它指定了皇后在每一行中的位置。例如,该特定列表有 8 个元素长(因此它是 n=8 的解决方案,或标准棋盘),我的程序将打印如下内容:

+---+---+---+---+---+---+---+---+
| | ۩ | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | ۩ | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | ۩ |
+---+---+---+---+---+---+---+---+
| | | ۩ | | | | | |
+---+---+---+---+---+---+---+---+
| ۩ | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | ۩ | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | ۩ | |
+---+---+---+---+---+---+---+---+
| | | | | ۩ | | | |
+---+---+---+---+---+---+---+---+

我的问题是:我如何使用 matplotlib 来做类似的事情,但没有 ascii 艺术?我想这样做是因为我使用的打印格式不允许大于 96x96 的板。

最佳答案

如果您使用的字体带有皇后符号,那么您可能会执行以下操作:

import matplotlib.pyplot as plt
import numpy as np

board = np.zeros((8,8,3))
board += 0.5 # "Black" color. Can also be a sequence of r,g,b with values 0-1.
board[::2, ::2] = 1 # "White" color
board[1::2, 1::2] = 1 # "White" color

positions = [1, 5, 7, 2, 0, 3, 6, 4]

fig, ax = plt.subplots()
ax.imshow(board, interpolation='nearest')

for y, x in enumerate(positions):
# Use "family='font name'" to change the font
ax.text(x, y, u'\u2655', size=30, ha='center', va='center')

ax.set(xticks=[], yticks=[])
ax.axis('image')

plt.show()

但是,我似乎无法在我的系统上找到带有该字符的字体,所以我只得到:

enter image description here

您还可以使用图像作为符号:

import matplotlib.pyplot as plt
import numpy as np

board = np.zeros((8,8,3))
board += 0.5 # "Black" color
board[::2, ::2] = 1 # "White" color
board[1::2, 1::2] = 1 # "White" color

positions = [1, 5, 7, 2, 0, 3, 6, 4]

fig, ax = plt.subplots()
ax.imshow(board, interpolation='nearest')

queen = plt.imread('queen.png')
extent = np.array([-0.4, 0.4, -0.4, 0.4]) # (0.5 would be the full cell)
for y, x in enumerate(positions):
ax.imshow(queen, extent=extent + [x, x, y, y])

ax.set(xticks=[], yticks=[])
ax.axis('image')

plt.show()

enter image description here

关于python - 如何使用 matplotlib 创建某种类型的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23298961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com