我目前正在编写一款游戏,其中你的播放器是一个png文件,你必须避免使用石头。我一直收到错误"类型对象播放器没有属性rect"。我是OOP的新手,所以任何帮助都将不胜感激!代码如下:
import pygame
import os
import random
import sys
random.seed()
_image_library = {}
def get_image(path):
global _image_library
image = _image_library.get(path)
if image == None:
canonicalized_path = path.replace('/', os.sep).replace('\\', os.sep)
image = pygame.image.load(canonicalized_path)
_image_library[path] = image
return image
y = 250
class Player(object):
def __init__(self):
self.rect = pygame.Rect(0, y, 50, 50)
def move(self, dx, dy):
# Move each axis separately. Note that this checks for collisions both times.
if dx != 0:
self.move_single_axis(dx, 0)
if dy != 0:
self.move_single_axis(0, dy)
def move_single_axis(self, dx, dy):
# Move the rect
self.rect.x += dx
self.rect.y += dy
pygame.init()
screen = pygame.display.set_mode((500, 500))
done = False
clock = pygame.time.Clock()
rockXList = []
rockYList = []
y = 250
xrand = 750
speed = 1
loop = 0
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
if(y > 3):
y -= 3
if pressed[pygame.K_DOWN]:
if(y < 497):
y += 3
a = 0
while(a < len(rockXList)):
rx = rockXList[a]
rx = rx - speed
rockXList[a] = rx
a = a + 1
screen.fill((153, 76, 0))
screen.blit(get_image("race-toad.png"), (0, y))
i = 0
while(i < len(rockXList)):
rx = rockXList[i]
ry = rockYList[i]
pygame.draw.rect(screen, (160, 160, 160), pygame.Rect(rx, ry, 32, 32))
execstr = "end_rect"+str(i)+" = pygame.Rect(rx, ry, 32, 32)"
exec execstr
i = i + 1
b = 0
while(b < len(rockXList)):
rx = rockXList[b]
ry = rockYList[b]
name = "if Player.rect.colliderect(end_rect" + str(b) + "):\n speed = 0\n print 'YOU LOSE!'"
exec name
b = b + 1
xadd = random.randint(10, 125)
rockX = xrand + xadd
xrand = rockX
rockY = random.randint(0, 450)
rockXList.append(rockX)
rockYList.append(rockY)
if(loop > 600):
speed = speed + 1
loop = 0
else:
loop = loop + 1
pygame.display.flip()
clock.tick(60)
答案 0 :(得分:0)
我不是OOP的专家,但从我所看到的,问题是你没有创建一个 INSTANCE 的Player()类,相反,你只创建了类本身
在OOP中,(自定义)类是一个LETS您创建自定义对象的结构,但在您创建该类的 INSTANCE 之前,您还没有真正创建任何内容。
我认为解决方案是在初始化pygame之后添加类似的东西:
player = Player()
然后你应该在每次用“玩家”引用“玩家”时替换,因为“玩家()”是 CLASS ,而“玩家”是实际的 INSTANCE 你将在游戏中使用。
希望我所说的是对的,也是有道理的。
另外,我认为你应该学习pygame.sprite模块,因为它似乎适合你想要实现的目标。