pygame入门实例——弹弹弹,小游戏!

xiaoxiao2025-09-17  134

pygame入门实例——弹弹弹,小游戏!

解释看注释,加入自己的动画图片,替换timg.jpg

import pygame import sys from pygame.locals import * #初始化pygame pygame.init() size = width, height = 600,400 speed = [-2,1] #背景设置,全白 bg = (255,255,255) #创建指定大小的窗口 Surface对象 screen = pygame.display.set_mode(size) #设置窗口标题 pygame.display.set_caption("弹弹弹,小游戏!") #加载图片 gamemaster = pygame.image.load("timg.jpg") #获得图像的位置矩形 position = gamemaster.get_rect() l_head = gamemaster r_head = pygame.transform.flip(gamemaster,True,False) #事件,终止事件 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: exit() if event.type == KEYDOWN: if event.key == K_LEFT: gamemaster = l_head speed = [-2,1] if event.key == K_RIGHT: gamemaster = r_head speed = [2,-1] if event.key == K_UP: speed = [1,-2] if event.key == K_DOWN: speed = [-1,2] elif event.type == KEYUP: #speed =[-2,1] pass #移动图像 position = position.move(speed) if position.left <0 or position.right > width: #图像翻转 gamemaster,True,False 左右翻转 上下不翻转 gamemaster = pygame.transform.flip(gamemaster,True,False) #反方向移动 speed[0] = -speed[0] if position.top <0 or position.bottom >height: #反方向移动 speed[1] = -speed[1] #填充背景 screen.fill(bg) #更新图像 screen.blit(gamemaster,position) #更新界面 pygame.display.flip() #延时10ms pygame.time.delay(10)

效果图:

 

2.pygame入门实例——基本图形绘制,画个圆

同心圆跟着鼠标移动

import pygame import sys from pygame.locals import* pygame.init() WHITE = (255,255,255) BLACK = (0,0,0) GREEN = (0,255,0) RED = (255,0,0) BLUE =(0,0,255) size = width,height = 640,480 screen = pygame.display.set_mode(size) pygame.display.set_caption("基本图形绘制Demo") position = size[0]//2,size[1]//2 moving = False clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == QUIT: #pygame.quit() exit() #鼠标移动 if event.type == MOUSEBUTTONDOWN: if event.button == 1: moving = True if event.type == MOUSEBUTTONUP: if event.button == 1: moving = False #得到鼠标位置,圆形移动 if moving: position = pygame.mouse.get_pos() screen.fill(WHITE) #画圆形,position为圆心 pygame.draw.circle(screen, RED, position, 25, 1) pygame.draw.circle(screen, GREEN, position, 75,1) pygame.draw.circle(screen, BLUE, position, 125, 1) #更新图片 pygame.display.flip() #设置帧率 clock.tick(120)

效果图:

更多编程实例,请关注我。

转载请注明原文地址: https://www.6miu.com/read-5036470.html

最新回复(0)