Python:将对象存储在2D数组中并调用其方法

2024-06-28 19:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个象棋应用程序。代码如下:

#file containing pieces classes
class Piece(object):`

     name = "piece"
     value = 0
     grid_name = "____"


class Pawn(Piece):

# Rules for pawns.
#If first move, then can move forward two spaces

name = "Pawn"
value = 1
grid_name = "_PN_"
first_move = True


#Main file
from Piece import *



class GameBoard:

   pieces = []
   grid = [][]

   def __init__(self):

      self.grid[1][0] = self.pieces.append(Pawn())



currentBoard = GameBoard()

我想为位于grid[1][0]的对象调用value变量

它看起来像:

^{pr2}$

这段代码不起作用,这说明我缺少一些关于对象和变量范围的信息。这在Python中是可能的吗?在

编辑-解决方案

我确实找到了一个解决方法,使用网格列表保存对工件列表中对象索引的引用。代码如下:

class GameBoard:

    # initialize empty board
    grid = [["____" for i in range(8)] for j in range(8)]
    pieces = []

    def __init__(self):

        self.grid[0][0] = 0
        self.grid[0][1] = 1
        self.grid[0][2] = 2
        self.grid[0][3] = 3
        self.grid[0][4] = 4
        self.grid[0][5] = 5
        self.grid[0][6] = 6
        self.grid[0][7] = 7
        self.grid[1][0] = 8
        self.grid[1][1] = 9
        self.grid[1][2] = 10
        self.grid[1][3] = 11
        self.grid[1][4] = 12
        self.grid[1][5] = 13
        self.grid[1][6] = 14
        self.grid[1][7] = 15


pieces = []

pieces.append(Pawn())

#grid will return the integer which can be passed to the other list to pull an 
#object for using the .value attribute

print pieces[currentBoard.grid[1][0]].value

Tags: the对象代码nameselfforpiecemove
1条回答
网友
1楼 · 发布于 2024-06-28 19:28:17

重写代码,使其仅作为单个文件运行:

#file containing pieces classes
class Piece(object):
     name = "piece"
     value = 0
     grid_name = "____"


class Pawn(Piece):
    # Rules for pawns.
    #If first move, then can move forward two spaces

    name = "Pawn"
    value = 1
    grid_name = "_PN_"
    first_move = True

class GameBoard:

   pieces = []
   grid = [[],[]]

   def __init__(self):

      self.grid[0][1] = self.pieces.append(Pawn())



currentBoard = GameBoard()

有一些事情需要纠正。首先,PiecePawn和{}中定义的变量不是在__init__()方法下定义的。这意味着这些变量将由类的所有实例共享。在

示例:

^{pr2}$

要避免这种情况,请在方法__init__()下为所有三个类定义类属性。在

示例:

class Pawn(Piece):
    # Rules for pawns.
    #If first move, then can move forward two spaces
    def __init__(self):
        self.name = "Pawn"
        self.value = 1
        self.grid_name = "_PN_"
        self.first_move = True

接下来,您的变量grid在python中没有正确定义。如果您想要一个包含两个空列表的列表,可以执行以下操作

grid = [[], []]

但是,一个简单的方法是生成一个8x8空列表结构

grid = [[[] for i in xrange(8)] for j in xrange(8)]

相关问题 更多 >