Pygame draw.rect 2d对象阵列黑屏

时间:2017-12-10 02:26:25

标签: python python-2.7 pygame

我的程序有问题。我正在尝试编写一个战舰游戏,问题就在这里:

class Battleship(object):

    def __init__(self):

        pygame.init()
        pygame.display.set_caption('battleship')
        self.gameDisplay = pygame.display.set_mode((DISPLAYWIDTH, DISPLAYHEIGHT))
        self.clock = pygame.time.Clock()

class Tile(object):
    def __init__(self):

        self.occupied = False
        self.shipID = 0
        self.playerID = 0

    def setOccupied(self, occupied):
        self.occupied = occupied

    def setShipID(self, shipID):
        self.shipID = shipID

    def setPlayerID(self, pID):
        self.playerID = pID

class Board:

    shipSizes = [1, 2, 3]
    sizeX = 25
    sizeY = 25

    def __init__(self, playerID):

        self.playerID = playerID

        self.playerShips = []

        for i in range(0, len(self.shipSizes)):

            self.playerShips.append(Ship(i, self.shipSizes[i]))

        self.tiles = [[Tile() for i in range(self.sizeX)] for j in range(self.sizeY)]

    def drawBoard(self):
        x = 0
        y = 0
        for row in self.visual:
            for col in row:
                pygame.draw.rect(Battleship().gameDisplay, black, (x, y, CASILLA, CASILLA), LINEWIDTH)
                x = x + CASILLA
            y = y + CASILLA
            x=0

我没有收到任何错误,但功能无法正常工作,只显示黑屏,检查其他所有内容,问题肯定在于该部分。

编辑,我添加了clas Battleship

1 个答案:

答案 0 :(得分:0)

我写了这个最小的例子来向你展示我在评论中描述的内容。 board实例现在是Battleship的属性,您只需在战列舰的draw方法中调用其draw方法。

import pygame as pg


GRAY = pg.Color('gray20')
BLUE = pg.Color('dodgerblue1')

class Battleship(object):

    def __init__(self):
        pg.init()
        pg.display.set_caption('battleship')
        self.display = pg.display.set_mode((800, 600))
        self.clock = pg.time.Clock()
        self.fps = 30
        self.done = False
        # Is an attribute of the Battleship now.
        self.board = Board()

    def run(self):
        while not self.done:
            self.handle_events()
            self.run_logic()
            self.draw()
            self.clock.tick(self.fps)

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

    def run_logic(self):
        pass

    def draw(self):
        self.display.fill(GRAY)
        # Call the board's draw method and pass the display.
        self.board.draw(self.display)
        pg.display.flip()


class Board:

    shipSizes = [1, 2, 3]
    sizeX = 25
    sizeY = 25

    def __init__(self):
        self.tiles = [['-' for i in range(self.sizeX)] for j in range(self.sizeY)]

    def draw(self, display):
        for y, row in enumerate(self.tiles):
            for x, col in enumerate(row):
                pg.draw.rect(
                    display, BLUE,
                    (x*self.sizeX, y*self.sizeY, self.sizeX, self.sizeY), 
                    2)


battleship = Battleship()
battleship.run()