PyGame屏幕在运行时返回黑色

时间:2017-12-05 05:26:23

标签: python-3.x pygame

在尝试运行正在为项目开发的游戏时,代码不起作用并导致屏幕变黑。 Mycharacter是一个角色,敌人是敌人角色,障碍是游戏中的障碍。该设计应该是一个追逐敌人的角色,而敌人正在追逐角色,以获得障碍物。 我们将其他类导入到此函数和主类中。 所有帮助都将被批准。 下面是代码的外观:

($line -split ':')[1].Trim()
N/A

1 个答案:

答案 0 :(得分:3)

我可以看到的第一个问题是,您将self作为参数传递给self.startGame(self)中的不同场景方法mainLoop。只需删除self

即可

runGame方法中,您错误地缩进了很多代码。游戏逻辑和绘图代码不应该在事件循环中,而应在外部while循环中。但它仍应绘制所有内容,但仅限于事件在队列中(例如,如果鼠标移动)。

此外,self.background表面只是黑色,因为您从未用其他颜色填充它。

附注:您忘记了clock = pygame.time.Clockpygame.quit背后的一些括号。

endGame方法中,每次发生事件时都会加载json文件(例如,鼠标移动)。每次点击鼠标或类似的东西,你最好这样做一次。

这是一个正常工作的最小例子:

import pygame


GREEN = pygame.Color('green')

class Controller:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((800, 800))
        self.background = pygame.Surface(self.screen.get_size()).convert()
        self.background.fill(GREEN)  # Fill the background if it shouldn't be black.
        self.clock = pygame.time.Clock()
        self.currentState = "start"
        self.button = pygame.Rect(350, 50, 100, 100)

    def mainLoop(self):
        self.done = False
        while not self.done:
            if self.currentState == "start":
                self.startGame()
            elif self.currentState == "running":
                self.start_time = pygame.time.get_ticks()
                self.runGame()

    def startGame(self):
        start = True
        while start:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                    start = False
                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_pos = pygame.mouse.get_pos()
                    if self.button.collidepoint(mouse_pos):
                        self.currentState = "running"
                        return  # Back to the mainloop

            self.screen.fill((255, 0, 255))
            pygame.draw.rect(self.screen, (0, 0, 110), self.button)
            pygame.display.flip()
            self.clock.tick(60)

    def runGame(self):
        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.done = True
                    run = False

            self.screen.blit(self.background, (0, 0))
            pygame.draw.rect(self.screen, (200, 0, 0), [20, 30, 50, 90])
            pygame.display.flip()
            self.clock.tick(60)


def main():
    the_game = Controller()
    the_game.mainLoop()

main()
pygame.quit()
相关问题