import pygame,sys
from pygame.locals import *
pygame.init()
width=650
height=650
screen=pygame.display.set_mode((width,height))
pygame.display.set_caption('my game')
fly = pygame.image.load("./img/fly.png")
fly_rect = fly.get_rect()
distance = [0, 0]
fps = 100
fclock =pygame.time.Clock()
while True: # 游戏循环
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[pygame.K_d]:
distance[0] += .1
elif pressed_keys[pygame.K_a]:
distance[0] -= .1
elif pressed_keys[pygame.K_w]:
distance[1] -= .1
elif pressed_keys[pygame.K_s]:
distance[1] += .1
else:distance=[0, 0]
if fly_rect.left < 0:
if distance[0] < 0 :distance[0]=0
elif fly_rect.right > width:
if distance[0]>0:distance[0]=0
elif fly_rect.top < 0 :
if distance[1]<0:distance[1]=0
elif fly_rect.bottom > height:
if distance[1]>0:distance[1]=0
fly_rect = fly_rect.move(distance[0], distance[1])
#screen.fill((0,0,0))
screen.blit(fly, fly_rect)
pygame.display.update()
fclock.tick(fps)
运行后如图,方块可操控上下左右移动(通过wasd)?
?
|