python - Pygame:玩家没有属性'rect'
问题描述
我正在制作一个 2d 射击游戏,但是当我运行它时,我收到一个错误,python 告诉我“玩家没有属性 'rect'”。
这是我的“播放器”的编码
class Player(pygame.sprite.Sprite):
def _init_(self):
super(). __init__()
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface([20,20])
self.image.fill(COLOUR2)
self.rect=self.image.get_rect()
player.rect.x=20
这是我整个游戏的编码:
import pygame
import sys
import math
from pygame.locals import *
pygame.init()
WINDOW = pygame.display.set_mode((900, 700))
COLOUR2 = (32,59,202)
COLOUR = (0,180,0)
COLOUR3 =(1,234,254)
WINDOW.fill(COLOUR)
keys=pygame.key.get_pressed()
y=100
z=100
x=100
FPS=70
fpsClock=pygame.time.Clock()
#Defines what a pygame bullet is.
class Bullet(pygame.sprite.Sprite):
def __init__(self):
super(). __init__()
self.image=pygame.Surface
self.image.fill(COLOUR2)
self.rect=self.image.get_rect()
def update(self):
self.rect.y-=3
class Player(pygame.sprite.Sprite):
def __init__(self):
super(). __init__()
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface([20,20])
self.image.fill(COLOUR2)
self.rect=self.image.get_rect()
player.rect.x=20
all_sprites_list=pygame.sprite.Group()#List of all the sprites
bullets_lis=pygame.sprite.Group()#List of all the bullets
player=Player()#Creates a player sprite and adds it to the small sprite list
all_sprites_list.add(player)#Adds the players to the list
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
keys=pygame.key.get_pressed()
#Makes Player character move right by pressing "d"
if keys[pygame.K_d]:
x=x+3
if x> 900:
x=900
#Makes player character move left by pressing "a"
if keys[pygame.K_a]:
x=x-3
if x<0:
x=0
#Makes bullets shoot out of player character by pressing *space*
if keys[pygame.K_SPACE]:
bullet=Bullet()
bullet.rect.x=player.rect.x
bullet.rect.y=player.rect.y
all_sprites_list.add(bullet)
bullet_list.add(bullet)
pygame.display.update()
#Updates all sprites (makes them move)
all_sprites_list.update()
#Draws all the sprites
all_sprites_list.draw(WINDOW)
pygame.display.flip()
fpsClock.tick(FPS)
我已经纠正了你们告诉我的语法错误,但我仍然被告知同样的事情。AttributeError:类型对象'Player'没有属性'rect'。
解决方案
而不是player.rect
你应该self.rect
在定义中使用,因为它是Player
class Player(pygame.sprite.Sprite):
def __init__(self):
super(). __init__()
pygame.sprite.Sprite.__init__(self)
self.image=pygame.Surface([20,20])
self.image.fill(COLOUR2)
self.rect=self.image.get_rect()
self.rect.x=20
推荐阅读
- php - PHP图像水印不支持高棉字体Unicode
- javascript - 是否可以在我的反应网站上加载另一个网站页面?
- android - 如何将 Android.Graphics.Bitmap 转换为 System.Drawing.Bitmap 并返回?
- solr - java.lang.NullPointerException\n\tat org.apache.solr.schema.TrieField.readableToIndexed(TrieField.java:433)
- vue.js - Vue.elementDirective 不是函数
- r - 在 R 中,如何在绘图的两个内部函数之间传递数据帧/小标题,然后保存绘图?
- php - 表单邮件安全
- javascript - 如何使用 puppeteer 访问一个接一个的 url
- reactjs - 在 React 中为 Month 类型的输入设置最小值
- laravel - 方法 Laravel\Passport\Bridge\AccessToken::__toString() 不能抛出异常,升级后捕获 InvalidArgumentException 错误