sun_1997 发表于 2021-3-21 19:57:11

关于实例属性引用的问题(小白)

import pygame
import sys


class AlienInvasion:
    def __init__(self):
      '''初始化游戏并创建游戏资源'''
      pygame.init()
      self.screen = pygame.display.set_mode((1200,1200))
      pygame.display.set_caption('Alien Invasion')
      self.bg_color = (230,230,230)

    def run_game(self):
       #开始游戏的主循环
      while True:
            '''监视键盘和鼠标'''
            for event in pygame.event.get():#pygame.event.get()返回一个列表
                if event.type == pygame.QUIT:
                  sys.exit()
            # 让最近绘制的屏幕可见
            pygame.display.flip()
            # 每次循环时都会重绘屏幕
            self.screen.fill(self.bg_color)

if __name__ == '__main__':
    ai = AlienInvasion()
    ai.run_game()



问题:self.screen = pygame.display.set_mode((1200,1200))这个实例属性在下面run_game方法里为什么能够引用fill方法self.screen.fill(self.bg_color){:5_92:}

z5560636 发表于 2021-3-21 20:55:28

ai = AlienInvasion()
这里就初始化添加了一个属性
self.screen = pygame.display.set_mode((1200,1200))

pygame.display 对象应该有个fill 方法重绘,   颜色是 自己定义的   self.bg_color

小伤口 发表于 2021-3-21 23:03:32

本帖最后由 小伤口 于 2021-3-21 23:10 编辑

display.set_mode创建指定大小的窗口
创建之后会返回一个Surface对象在这里当作背景画布
self.screen = pygame.display.set_mode((1200,1200))
其实这就是调用函数的过程
类似于下面这样
>>> def test(x):
        surface=x+5
        return surface

>>> screen=test(5)
>>>
>>> screen
10
函数会返回一个Surface对象(当然不是上面的surface)
surface文档
surface有一个方法就是fill所以可以调用
页: [1]
查看完整版本: 关于实例属性引用的问题(小白)