我之前有 Java 和 Web 开发经验,但最近在学习 Python。为了帮助我学习这门语言,我一直致力于创建一个程序来解决 Dragon Fjord A-Puzzle-A-Day 日历难题 (https://www.dragonfjord.com/product/a-puzzle-a-天/))。我希望该程序在命令行中运行。到目前为止,我已经制作了棋盘和棋子,但正在努力实现放置棋子的功能。我希望对以下代码中的 place() 函数有一些反馈,谢谢!
import numpy as np
#numpy
#make the empty board
board = np.zeros((7,7))
board[0:2,6]=9
board[6,4:7]=9
#make a dictionary with a numpy array and a boolean stating if the piece is used or not
pieces = {1: [np.array([[1,0],[1,0],[1,1],[0,1]]),0],
2: [np.array([[0,0,2],[2,2,2],[2,0,0]]),0],
3: [np.array([[3,3,3],[3,0,0],[3,0,0]]),0],
4: [np.array([[4,0],[4,4],[4,0],[4,0]]),0],
5: [np.array([[5,5,5],[5,5,5]]),0],
6: [np.array([[6,6],[6,6],[6,0]]),0],
7: [np.array([[0,0,0,7],[7,7,7,7]]),0],
8: [np.array([[8,0,8],[8,8,8]]),0]}
#place a piece on the board
def place(p,x,y):
def overlap(p,x,y):
for i in range(0,pieces[p][0].size):
for j in range(0,pieces[p][0][0].size):
print("j is {0}".format(j))
if board[x+i,y+j] != 0 and pieces[p][0][i,j] != 0:
return True
return False
#check if piece is used and it would overlap
if pieces[p][1] != 1 and not overlap(p,x,y):
for i in range(0,pieces[p][0].size):
for j in range(0,pieces[p][0][0].size):
#index across the rows and columns replacing
board[x+i,y+j]=pieces[p][0][i,j]
pieces[p][1] = 1
#rotate a piece left
def rotatel(p):
pieces[p] = np.rot90(pieces[p])
#rotate a piece right
#this function is kinda arbitrary but im gonna keep it for now incase it comes in handy later
def rotater(p):
rotatel(p)
rotatel(p)
rotatel(p)
#testing placing
print(board)
place(1,1,1)
print(board)
我的想法是使用 numpy,因为它似乎是创建和更改数组的好工具。我认为也可以使用列表列表,其结果非常相似。主要问题不应该是 numpy 实现,但似乎是索引错误。
如果有帮助的话,这是抛出的错误:
line 24, in overlap
if board[x+i,y+j] != 0 and pieces[p][0][i,j] != 0:
IndexError: index 7 is out of bounds for axis 0 with size 7
board
的形状为 (7,7)。通过使用 board[x+i,y+j]
,如果 x+i
或 y+j
大于或等于 7(Python 数组从索引 0 开始),则会出现错误。在您的情况下,会引发错误,因为此时 x
为 1,而 i
为 6,因此尝试访问不存在的索引 7。
我认为这里的主要问题是您在使用
size
时错误地使用了pieces[p][0].size
参数。您通过 pieces[p][0]
访问的数组是
[[1,0],[1,0],[1,1],[0,1]]
但是,这个数组的
size
不是我认为你假设的 4,而是元素总数(此处:8)。要获取子数组的数量,可以使用 pieces[p][0].shape[0]
。
shape
为您提供元组 (4,2)
,然后您可以访问其中的第一个值。