使用Pygame脚本问题 [英] Issue with script using Pygame
问题描述
我在业余时间正在写一个小游戏。到目前为止,这是我所拥有的:
I'm writing a small game in my spare time. This is what I have so far:
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)
简而言之,它应该在背景上创建一个对象,并允许您使用箭头键。但是,我得到了错误:
In short, it should create an object on a background and allow you to move the object using the arrow keys. However, I get the error:
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类的播放器实例无法识别move方法。另外,我对为什么在win.blit()函数中为什么要给参数player而不是player.image(存储图像的属性)感到困惑。
I'm struggling to understand why my player instance of the sprite class is not recognising the move method. Also, I'm confused by why during the win.blit() function, I have to give the argument player instead of player.image, the attribute which I've stored the image.
任何建议将不胜感激。
Any advice would be appreciated.
推荐答案
在代码中
def resize(self, sh, sw):
self.image = transform.scale(self.image, (sh, sw))
return self.image
您返回的图像是 Surface
实例-因此位于
you returns image which is Surface
instance - so in line
player = player.resize(20, 20)
您将 sprite
实例替换为 Surface
实例
但是您不必再次将其分配给玩家
。
But you don't have to assign it to player
again.
执行:
def resize(self, sh, sw):
self.image = transform.scale(self.image, (sh, sw))
# without return
# without player =
player.resize(20, 20)
之后 player.move(...)
将再次起作用。
您将必须在 blit()
这篇关于使用Pygame脚本问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!