目录
小球碰壁运动
import pygame, sys
pygame.init()
size = width, height = 600, 400
speed = [1, 1]
BLACK = 0, 0, 0
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame for Game")
ball = pygame.image.load("PYG02-ball.gif")
ballRect = ball.get_rect()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
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()
pygame.display.update()
pygame.image.load(filename)
将filename路径下的图像载入游戏,支持JPG、
PNG、GIF(非动画)等13种常用图片格式
ballrect.move(x,y)
矩形移动一个偏移量(x,y),即在横轴方向移
动x像素,纵轴方向移动y像素,xy为整数
screen.fill(color)
显示窗口背景填充为color颜色,采用RGB色
彩体系。由于壁球不断运动,运动后原有位置
将默认填充白色,因此需要不断刷新背景色
控制小球的运行的节奏
import pygame, sys
import math
pygame.init()
size = width, height = 600, 400
speed = [2, 2]
BLACK = 0, 0, 0
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame for Game")
ball = pygame.image.load("PYG02-ball.gif")
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()
ballRect = ballRect.move(speed[0], speed[1])
if ballRect.left < 0 or ballRect.right > width:
speed[0] = -speed[0]*abs(math.cos(ballRect.left))
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)
壁球小游戏(操控型)与键盘的基本使用
import pygame, sys
import math
pygame.init()
size = width, height = 600, 400
speed = [2, 2]
BLACK = 0, 0, 0
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pygame for Game")
ball = pygame.image.load("PYG02-ball.gif")
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]))
if event.key == pygame.K_RIGHT:
speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] -1
if event.key == pygame.K_UP:
speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] -1
if event.key == pygame.K_DOWN:# 如果减为零就不用减了
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]*abs(math.cos(ballRect.left))
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)