安装 pip install pygame
import sys, pygame pygame.init() size = width, height = (1200, 800) speed = [1, 1] Black = 0, 0, 0 screen = pygame.display.set_mode(size) pygame.display.set_caption("pygame谈球") fps = 300 fclock = pygame.time.Clock() ball = pygame.image.load("D:/ball.jpg") ballrect = ball.get_rect() # pygame对任意导入的图像都表示为surface对象,通过get_rect()形成与对象紧密相关的矩形对象 # rect对象有一些重要属性,如top,bottom,left,right表示上下左右边的坐标width和height表示宽和高 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])) elif event.key == pygame.K_RIGHT: speed[0] = speed[0] + 1 if speed[0] > 0 else speed[0] - 1 elif event.key == pygame.K_UP: speed[1] = speed[1] + 1 if speed[1] > 0 else speed[1] - 1 elif 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]) # 通过move方法可以对矩形进行移动 if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] # 遇到上下边界则y方向速度取反,遇到左右边界则x方向速度取反 screen.fill(Black) # 显示窗口进行填充,因为移动后默认原本位置为白色,所以必须不断刷新背景,使用RGB色彩体系 screen.blit(ball, ballrect) # 实际的移动是通过不断把小球的图像绘制到对应的矩形框里面来完成的 pygame.display.update() fclock.tick(fps)
第一个弹球游戏