簡體   English   中英

Pygame使用OOP繪制矩形

[英]Pygame drawing a rectangle with OOP

我正在嘗試使用pygame學習OOP並制作一個簡單的游戲,我正在松懈地跟隨一個教程,但是嘗試修改它以適應我自己的需求,但現在不起作用。 我試圖在黑色窗口上繪制一個白色矩形,本教程在黑色窗口上繪制一個藍色圓圈,當我將圓圈替換為矩形時,它不起作用。 我的代碼分為兩個不同的文件,這里是第一個文件:

import pygame
import LanderHandler

black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)


class MainLoop(object):
    def __init__(self, width=640, height=400):

        pygame.init()
        pygame.display.set_caption("Lander Game")
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((self.width, self.height), pygame.DOUBLEBUF)
        self.background = pygame.Surface(self.screen.get_size()).convert()

    def paint(self):
        lander = LanderHandler.Lander()
        lander.blit(self.background)

    def run(self):

        self.paint()
        running = True

        while running:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        running = False

            pygame.display.flip()

        pygame.quit()


if __name__ == '__main__':
    # call with width of window and fps
    MainLoop().run()

而我的第二個文件:

import pygame

black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)


class Lander(object):
    def __init__(self, height=10, width=10, color=white, x=320, y=240):
        self.x = x
        self.y = y
        self.height = height
        self.width = width
        self.surface = pygame.Surface((2 * self.height, 2 * self.width))
        self.color = color

        pygame.draw.rect(self.surface, white, (self.height, self.height, self.width, self.width))

    def blit(self, background):
        """blit the Ball on the background"""
        background.blit(self.surface, (self.x, self.y))

    def move(self, change_x, change_y):
        self.change_x = change_x
        self.change_y = change_y

        self.x += self.change_x
        self.y += self.change_y

        if self.x > 300 or self.x < 0:
            self.change_x = -self.change_x
        if self.y > 300 or self.y < 0:
            self.change_y = -self.change_y

謝謝您,任何幫助或為我指明正確的方向。 PS我沒有運行錯誤,並且會彈出黑色窗口,但是沒有白色矩形。

問題是因為您在表面self.background上繪制了矩形

lander.blit(self.background)

但是您永遠不會在self.background上對self.screen進行blit,這是主緩沖區,當您執行此操作時會在監視器上發送

pygame.display.flip()

這樣您就可以直接在self.screenself.screen

lander.blit(self.screen)

否則您必須在self.background上對self.screen進行blit

lander.blit(self.background)

self.screen.blit(self.background, (0,0))

您不應該創建名稱為blit的函數,因為它可能會妨礙實際的blit函數。 同樣在第二個代碼中:

pygame.draw.rect(self.surface, white, (self.height, self.height, self.width, self.width))

你應該使用表面

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM