我正在嘗試製作國際象棋應用程序。代碼如下: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()
我想呼籲位於網格對象變量的值[1] [0]
它看起來是這樣的:
print currentBoard.grid[1][0].value
此代碼沒有按」告訴我我錯過了一些關於對象和變量範圍的東西。這是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
它是如何「不加工」?可能的話,你應該在這裏遇到一個'SyntaxError':'grid = [] []'。 –
對於這個問題,'self.grid [1] [0] = self.pieces.append(Pawn())'這可能會拋出一個錯誤,或者至少肯定不會做你期望的。無論如何,如果你有一些'grid'列表,那麼你絕對可以訪問屬於列表中的對象的屬性,比如'grid [0] [0] .value'。這不是你的代碼的問題。您應該閱讀Python中的列表基礎知識。 –
@ juanpa.arrivillaga我明白你在說什麼。對不起,我遺漏了一部分代碼。當試圖調用該方法時,它會中斷,我已經在計算機上的代碼中初始化了2d列表。我會稍微更新一下。對於那個很抱歉。 –