|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
一个小游戏,一个小球在框内运动,代码可以运行,但其中几句不太理解,
elif event.type == pygame.KEYDOWN:部分,
结果在先,判断条件在后,全部写的同一行,语法之前没见过?
绝对数减一,总体上这几句还是不太理解,请大侠指导一下,谢谢
import pygame,sys
pygame.init()
size = width,height=600,400
speed = [1,1]
BLACK = 0,0,0
screen = pygame.display.set_mode(size)
pygame.display.set_caption("游戏travel")
ball = pygame.image.load("cat.jpg")
ballrect = ball.get_rect()
fps = 100
fclock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
speed[0] = speed[0] if speed[0] == 0 else(abs(speed[0])-1)*int(speed[0]/abs(speed[0]))
#击左键,横向速度递减,如果速度为0,不要减,如果速度不为0,判断其绝对数减一
#如果负向速度要给负号,如果正向速度要给正号,后边部分解决符号问题
elif event.key == pygame.K_RIGHT:
speed[0] = speed[0]+1 if speed[0]>0 else speed[0]+1
elif event.key == pygame.K_UP:
speed[1] = speed[1]+1 if speed[1]>0 else speed[1]+1
elif event.key == pygame.K_DOWN:
#speed[1] = speed[1]+1 if speed[1]>0 else speed[1]+1
speed[1] = speed[1] if speed[1] == 0 else(abs(speed[1])-1)*int(speed[1]/abs(speed[1]))
ballrect = ballrect.move(speed[0],speed[1])
if ballrect.left<0 or ballrect.right>width:
speed[0] = -speed[0]
if ballrect.top<0 or ballrect.bottom>height:
speed[1] = -speed[1]
screen.fill(BLACK)
screen.blit(ball,ballrect)
pygame.display.update()
fclock.tick(fps)
|
|