亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將我的 PyGame 游戲拆分為單獨的文件?

如何將我的 PyGame 游戲拆分為單獨的文件?

嚕嚕噠 2022-04-23 21:55:39
我正在為一群超級聰明的年輕愛好者教授每兩周一次的編碼課程。我們已經介紹了 OOP 并使用 OOP 創建了一個基于文本的冒險?,F在我打算教 PyGame 并繼續使用對象,我想知道是否可以以這樣一種方式構建游戲,即每個對象的代碼都在一個單獨的文件中?這將非常簡潔且易于構建。那么對于下面的代碼,我嘗試為每個對象制作單獨的文件。這只是部分成功,因為繪制方法從來沒有很好地工作,我相信我不能有單獨的文件引用同一個 pygame 屏幕的問題。import pygameimport randomimport time# Define some colorsBLACK = (0, 0, 0)WHITE = (255, 255, 255)BLUE = (0,0,255)SCREEN_WIDTH = 700SCREEN_HEIGHT = 500pygame.init()class Paddle:    '''Class to keep players location'''    def __init__(self,x=350, y=480, width =70,height=20):        self.x = x        self.y = y        self.change_x = 0        self.change_y = 0        self.width = width        self.height = height        self.score = 0    def move(self):        self.x += self.change_x        self.y += self.change_y    def draw(self):        pygame.draw.rect(screen, BLUE, [self.x,self.y, self.width, self.height])    def check_collision(self,ball):        if ball.y>460:            if abs(35+ self.x - ball.x) < 30:                self.score += 1                ball.draw(BLUE)                ball.y = 0                ball.x = random.randint(0,650)                ball.change_y = random.randint(2,3+int(self.score/5))class Ball:    """Class to keep track of a ball's location and vector."""    def __init__(self,x=350,y=250,size=25):        self.x = x        self.y = y        self.change_x = 0        self.change_y = 0        self.size = size    def move(self):        self.x += self.change_x        self.y += self.change_y    def draw(self,colour = WHITE):        pygame.draw.circle(screen,WHITE, [self.x, self.y], self.size)# Set the height and width of the screensize = [SCREEN_WIDTH, SCREEN_HEIGHT]screen = pygame.display.set_mode(size)pygame.display.set_caption("Bouncing Balls")done = Falseclock = pygame.time.Clock()screen.fill(BLACK)ball = Ball()player = Paddle()ball.change_y = 2ball.draw()當我有單獨的文件時,這是我遇到的與屏幕相關的錯誤line 20, in draw   pygame.draw.circle(screen,WHITE, [self.x, self.y], self.size)NameError: name 'screen' is not defined
查看完整描述

1 回答

?
鴻蒙傳說

TA貢獻1865條經驗 獲得超7個贊

向類的方法添加一個surface參數,并在傳遞給該方法的表面上繪制對象:draw()PaddleBall


class Paddle:

    # [...]


    def draw(self, surface):

        pygame.draw.rect(surface, BLUE, [self.x,self.y, self.width, self.height])

class Ball:

    # [...]


    def draw(self, surface, colour = WHITE):

        pygame.draw.circle(surface, colour, [self.x, self.y], self.size)

pygame.Surface現在您可以在任何您想要的對象上繪制對象,例如screen:


ball.draw(screen)

player.draw(screen)


查看完整回答
反對 回復 2022-04-23
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號