昼临明麟 发表于 2022-8-1 14:12:41

python遇到错误AttributeError: 'Settings' object has no attribute 'screen_width'

AttributeError: 'Settings' object has no attribute 'screen_width'
运行就出现,改了就会出现其他错误,各位大佬能帮忙看看吗?
class Settings():
    """存储《外星人入侵》的所有设置的类"""

    def _init_(self):
      """初始化游戏的设置"""
      #屏幕设置
      self.screen_width = 1080
      self.screen_height = 960
      self.bg_color = (230, 230, 230)
      
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
import pygame

class Ship():

    def _init_(self,screen):
      """初始化飞船并设置其初始位置"""
      self.screen = screen

      #加载飞船图像并获取其外链接矩形
      self.image = pygame.image.load('images/ship.bmp')
      self.rect = self.image.get_rect()
      self.screen_rect = screen.get_rect()

      #将每艘新飞船放在屏幕底部中央
      self.rect.centerx = self.screen_rect.centerx
      self.rect.bottom = self.screen_rect.bottom

    def blitme(self):
      """在指定位置绘制飞船"""
      self.screen.blit(self.image, self.rect)



\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
import sys
import pygame

from settings import Settings
from ship import Ship

def run_game():
    #初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
      (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Imvasion")

    #创建一艘飞船
    ship = Ship(screen)


    #开始游戏的主循环
    while True:

      #监视键盘和鼠标事件
      for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
      #每次循环都重绘屏幕
      screen.fill(ai_settings.bg_color)
      ship.blitme()

      #让最近绘制的屏幕可见
      pygame.display.flip()


run_game()
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
我有修改代码,只要不用前面两个就能跑
用了就报错,有大佬能说一下原因吗?
AttributeError: 'Settings' object has no attribute 'screen_width'
TypeError: Ship() takes no arguments

ZhKQYu 发表于 2022-8-1 14:12:42

构造函数时双下划线开始双下划线结束

theS 发表于 2022-8-1 18:14:26

def __init__(self,screen):
页: [1]
查看完整版本: python遇到错误AttributeError: 'Settings' object has no attribute 'screen_width'