要想实现键盘控制作用,就需要给游戏键盘监听事件
利用pygame模块的key.get_pressed()方法,来检测按键是否按下
key_press =pygame.key.get_pressed()
if not key_press[K_UP] and ball.rect.bottom < height:
ball.movedown()
elif key_press[K_UP] and ball.rect.top>0:
ball.moveup()
1
2
3
4
5
实现效果
游戏中,当按下上键时游戏对象就往上移动,一松开按键,游戏对象就往下降
完整代码
import pygame
from pygame.locals import *
from sys import exit
pygame.init() #进行初始化
bgsize = width,height = 1000,600
pygame.display.set_mode(bgsize)
pygame.display.set_caption('进击的蜘蛛')
bg=(0,0,0) #设置背景颜色
turtl = pygame.image.load('D:QQMobileFile/spride.png')
ball_image = pygame.transform.scale(turtl,(width//10,height//10)) #对图片进行缩放
screen = pygame.display.get_surface()
class Ball(pygame.sprite.Sprite):
def __init__(self,up_speed,down_speed):
pygame.sprite.Sprite.__init__(self)
self.up_speed = up_speed
self.down_speed = down_speed
self.image = ball_image
self.rect = self.image.get_rect()
self.rect.top = 0
self.rect.left =(width-self.image.get_width())//2
def moveup(self):
self.rect.top -=self.up_speed
def movedown(self):
self.rect.top +=self.down_speed
ball = Ball(6,4)
clock = pygame.time.Clock()
while 1:
for event in pygame.event.get():
if event.type == QUIT:
exit()
key_press =pygame.key.get_pressed()
if not key_press[K_UP] and ball.rect.bottom < height:
ball.movedown()
elif key_press[K_UP] and ball.rect.top>0:
ball.moveup()
screen.fill(bg)
screen.blit(ball_image,ball.rect)
clock.tick(25)
pygame.display.flip() #将更新显示到屏幕上
---------------------