我在业余时间写了一个小游戏。这就是我到目前为止所做的:
from pygame import * #import relevant modules
from PIL import Image
import os, sys
init() #initialise
class sprite:
def __init__(self, object, x = 0, y = 0, w = 0, h = 0):
self.image = image.load(object).convert()
self.posx = x
self.posy = y
self.position = ((x, y, w, h))
def resize(self, sh, sw):
self.image = transform.scale(self.image, (sh, sw))
return self.image
def move(self, window, background, right, down):
self.posx = x + right
self.posy = y + down
window.blit(background, self.position, self.position)
self.position.move(right, down)
window.blit(self, self.position)
window.update()
os.chdir('C:\\Users\\alesi\\Documents\\Pygame\\Project\\') #current folder change
win = display.set_mode((736, 552))#load window
Clock = time.Clock() #handy clock
background = image.load('background.jpg').convert()#load images
player = sprite('ball.png', 350, 275, 20, 20)
player = player.resize(20, 20)
win.blit(background, (0, 0))
win.blit(player, (350, 275))
display.update()
while True:
event.pump()
keys = key.get_pressed()
if keys[K_ESCAPE]:
sys.exit()
elif keys[K_RIGHT]:
player.move(win, background, 20, 0)
elif keys[K_LEFT]:
player.move(win, background, -20, 0)
elif keys[K_DOWN]:
player.move(win, background,0, 20)
elif keys[K_UP]:
player.move(win, background, 0, -20)
简而言之,它应该在背景上创建一个对象,并允许您使用箭头键移动对象。但是,我收到错误:
C:\Users\alesi\Documents\Pygame\Project>python2 game2.py
Traceback (most recent call last):
File "game2.py", line 51, in <module>
player.move(win, background, -20, 0)
AttributeError: 'pygame.Surface' object has no attribute 'move'
我很难理解为什么我的sprite类的播放器实例没有识别移动方法。另外,我很困惑为什么在win.blit()函数中,我必须给出参数player而不是player.image,这是我存储图像的属性。
任何建议都将不胜感激。
答案 0 :(得分:1)
代码
def resize(self, sh, sw):
self.image = transform.scale(self.image, (sh, sw))
return self.image
你返回Surface
实例的图像 - 所以在行
player = player.resize(20, 20)
您将sprite
实例替换为Surface
实例
但您不必再将其分配给player
。
执行:
def resize(self, sh, sw):
self.image = transform.scale(self.image, (sh, sw))
# without return
# without player =
player.resize(20, 20)
之后player.move(...)
将重新开始。
同样,您必须在player.image
blit()