代码运行良好,我的图像按原样翻转,但是当我没有按键时,我的图像消失了...我知道这与在每个'if'期间调用screen.blit方法时有关更新函数中的语句,但我不知道如何绕过这个......
import pygame, sys, glob
from pygame import *
h=400
w=800
screen = pygame.display.set_mode((w,h))
clock = pygame.time.Clock()
class player:
def __init__(self):
self.x = 200
self.y = 300
self.ani_speed_init = 8
self.ani_speed=self.ani_speed_init
self.Lani_speed_init = 8
self.Lani_speed=self.Lani_speed_init
self.ani = glob.glob("D:\Projects\pygame\TestGame\sprite*.png")
self.Lani = glob.glob("D:\Projects\pygame\TestGame\Lsprite*.png")
self.ani.sort()
self.ani_pos=0
self.Lani.sort()
self.Lani_pos=0
#takes length of the amount of images and subtracts 1 since count starts at 0
self.ani_max=len(self.ani) -1
self.Lani_max=len(self.Lani) -1
self.img = pygame.image.load(self.ani[0])
self.Limg = pygame.image.load(self.Lani[0])
self.update(0, 0)
def update(self, pos, posL):
if pos != 0:
#subtracts 1 from 10
self.ani_speed-=1
#adds self.x to itself
self.x+=pos
if self.ani_speed==0:
self.img = pygame.image.load(self.ani[self.ani_pos])
self.ani_speed = self.ani_speed_init
if self.ani_pos == self.ani_max:
self.ani_pos = 0
else:
self.ani_pos+=1
screen.blit(self.img,(self.x,self.y))
if posL != 0:
#subtracts 1 from 10
self.Lani_speed-=1
#adds self.x to itself
self.x+=posL
if self.Lani_speed==0:
self.Limg = pygame.image.load(self.Lani[self.Lani_pos])
self.Lani_speed = self.Lani_speed_init
if self.Lani_pos == self.Lani_max:
self.Lani_pos = 0
else:
self.Lani_pos+=1
screen.blit(self.Limg,(self.x,self.y))
player1 = player()
pos = 0
posL = 0
while 1:
screen.fill((255,255,255))
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.quit()
elif event.type == KEYDOWN and event.key == K_RIGHT:
pos = 1
elif event.type == KEYUP and event.key == K_RIGHT:
pos = 0
elif event.type == KEYDOWN and event.key == K_LEFT:
posL = -1
elif event.type == KEYUP and event.key == K_LEFT:
posL = 0
player1.update(pos, posL)
pygame.display.update()
答案 0 :(得分:0)
这是一个建议而不是一个答案,因为很难说你要做什么,但我需要格式化代码,所以评论并不真正有用。是否可以将更新函数扩展为具有以下默认行为:
def update(self, pos, posL):
updated = False
if pos != 0:
(logic removed)
screen.blit(self.img,(self.x,self.y))
updated = True
if posL != 0:
(logic removed)
screen.blit(self.Limg,(self.x,self.y))
updated = True
if not updated:
screen.blit(something sensible for arguments of 0,0)
如果刚刚测试了pos == 0和posL == 0,你可以避免使用'updated'变量但是更新后的测试允许上面的逻辑可能不会执行screen.blit,最后的测试将确保总是被写入屏幕。
答案 1 :(得分:0)
我不会允许更新功能将播放器blit到屏幕上,而是将播放器添加到默认的pygame精灵组并通过while循环绘制它!我也会避免每次更新时加载图像(由于开销),而是立即加载所有图像,然后在需要时将它们加入blit!