Python game

Keyboard control action in order to achieve, you need to listen to the game keyboard events
key.get_pressed use pygame module () method to detect key presses

= pygame.key.get_pressed KEY_PRESS ()
IF Not KEY_PRESS [K UP] ball.rect.bottom and <height:
ball.movedown ()
elif KEY_PRESS [K UP] and ball.rect.top> 0:
ball.moveup ()
. 1
2
. 3
. 4
. 5
to achieve the effect of
the game, when the button is pressed the game will move up the object, a release button, go out into the drop game object

完整代码
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:\QQ\MobileFile/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() #将更新显示到屏幕上

--------------------- 

Guess you like

Origin www.cnblogs.com/ly570/p/11278006.html