keys=pygame.key.get_pressed(),接受游戏中当前按下的所有按键,并把它们保存为一个列表,放在keys变量中

pygame.K_w告诉PyGame你在检查w键,通过修改最后的一个字母,你可以把它修改为任何你想要检查的按键

import pygame
pygame.init()
size=[400,300]
screen=pygame.display.set_mode(size)
clock=pygame.time.Clock()
done=False
while not done:
    keys=pygame.key.get_pressed()
    if keys[pygame.K_w]:
        print "hello"

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            done=True
    clock.tick(32)
pygame.quit()

控制小球上下左右移动

import pygame
pygame.init()
size=[400,300]
screen=pygame.display.set_mode(size)
clock=pygame.time.Clock()
x=size[0]/2
y=size[1]/2
red=pygame.color.Color('#FF8080')
blue=pygame.color.Color('#8080FF')
white=pygame.color.Color('#FFFFFF')
black=pygame.color.Color('#000000')

done=False
while not done:
    screen.fill(black)
    keys=pygame.key.get_pressed()
    if keys[pygame.K_w]:
        y-=1
    if keys[pygame.K_s]:
        y+=1
    if keys[pygame.K_a]:
        x-=1
    if keys[pygame.K_d]:
        x+=1
    pygame.draw.circle(screen,red,[x,y],6)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            done=True
    clock.tick(72)
pygame.quit()

注:防止小球出屏幕,加判断

import pygame
pygame.init()
size=[400,300]
screen=pygame.display.set_mode(size)
clock=pygame.time.Clock()
x=size[0]/2
y=size[1]/2
red=pygame.color.Color('#FF8080')
blue=pygame.color.Color('#8080FF')
white=pygame.color.Color('#FFFFFF')
black=pygame.color.Color('#000000')


def checkOffScreenX(x):
    if x>size[0]:
        x=0
    elif x<0:
        x=size[0]
    return x

def checkOffScreenY(y):
    if y>size[1]:
        y=0
    elif y<0:
        y=size[1]
    return y
done=False
while not done:
    screen.fill(black)
    keys=pygame.key.get_pressed()
    if keys[pygame.K_w]:
        y-=1
    if keys[pygame.K_s]:
        y+=1
    if keys[pygame.K_a]:
        x-=1
    if keys[pygame.K_d]:
        x+=1

    x=checkOffScreenX(x)
    y=checkOffScreenY(y)
    pygame.draw.circle(screen,red,[x,y],6)
    pygame.display.flip()

    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            done=True
    clock.tick(72)
pygame.quit()

完整游戏代码:

import random
import pygame
pygame.init()
size=[400,300]
screen=pygame.display.set_mode(size)
clock=pygame.time.Clock()
x=size[0]/2
y=size[1]/2
ballX=random.randrange(0,size[0])
ballY=random.randrange(0,size[1])
goalX=size[0]/2-10
goalY=size[1]/2-10
goalW=20
goalH=20
points=0
red=pygame.color.Color('#FF8080')
blue=pygame.color.Color('#8080FF')
white=pygame.color.Color('#FFFFFF')
black=pygame.color.Color('#000000')


def checkOffScreenX(x):
    if x>size[0]:
        x=0
    elif x<0:
        x=size[0]
    return x

def checkOffScreenY(y):
    if y>size[1]:
        y=0
    elif y<0:
        y=size[1]
    return y
def checkTouching():
    global x
    global ballX
    global y
    global ballY
    if -10