pygame 初学者入门案例

我以代码+注释的方式给大家讲解基本的pygame。大家请看案例详情,注意结合注释学习哟!这是创建一个pygame窗口,如果点击窗口的“x”关闭窗口按钮就能退出。希望你能跟着敲一遍代码,接下来我会列举几个简单且典型的案例,大家可以根据自己需要进行拓展学习,有疑问可以在评论区交流!

import pygame #导入 Pygame 模块,这样可以在代码中使用 Pygame 提供的功能。
pygame.init()#初始化 Pygame 模块。在使用 Pygame 前,需要调用 pygame.init() 来进行初始化。

screen = pygame.display.set_mode((800, 600))#创建一个窗口大小为 800x600 的显示窗口,并将其赋给变量 screen。这个窗口是用来显示游戏内容或图形的。

running = True #设置一个变量 running 为 True,用来控制游戏的运行状态。
while running:  #进入一个循环,只要 running 为 True,就会一直执行循环内的代码。
    for event in pygame.event.get(): #遍历当前发生的事件列表。Pygame 中的事件可以是键盘事件、鼠标事件等。
        if event.type == pygame.QUIT:#检查当前事件是否为退出事件,即用户点击窗口的关闭按钮。
            running = False   #如果检测到退出事件,将 running 设置为 False,从而退出循环。

pygame.quit() #退出 Pygame 模块,释放资源。

1-移动的方块

这段代码使用Pygame库在Python中创建了一个简单的游戏。它创建了一个窗口,在窗口中你可以用箭头键移动一个白色的正方形

import pygame
pygame.init()

win=pygame.display.set_mode((800,600)) #参数是用来设置游戏窗口的大小的元组
pygame.display.set_caption("移动的方块")
x,y=400,300
speed=1
while True:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            pygame.quit()
            #sys.exit()
    keys=pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        x-=speed
    if keys[pygame.K_RIGHT]:
        x+=speed
    if keys[pygame.K_UP]:
        y-=speed
    if keys[pygame.K_DOWN]:
        y+=speed
    win.fill("black")
    pygame.draw.rect(win,"white",(x,y,20,20))
    pygame.display.update()

 2-贪吃蛇

#请看下面这个简单的 Pygame 入门小游戏示例,这是一个基于 Pygame 的经典贪吃蛇游戏:

import pygame
import random

pygame.init()

# 设置窗口大小
WIDTH, HEIGHT = 800, 600
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

# 初始化贪吃蛇和食物
snake = [(200, 200), (210, 200), (220, 200)] #初始化贪吃蛇的初始位置。
food = (random.randrange(0, WIDTH, 10), random.randrange(0, HEIGHT, 10))#随机生成食物的初始位置。
#randrange函数第一个参数是生成随机数的起始范围(包含在内);第二个参数是生成随机数的结束范围(不包含在内);第三个参数是生成的随机数的间隔(步长)。
direction = 'RIGHT' #初始移动方向为向右。

clock = pygame.time.Clock()#创建一个用于控制游戏帧率的Clock对象,以确保游戏画面的流畅性

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and direction != 'RIGHT':
        direction = 'LEFT'
    if keys[pygame.K_RIGHT] and direction != 'LEFT':
        direction = 'RIGHT'
    if keys[pygame.K_UP] and direction != 'DOWN':
        direction = 'UP'
    if keys[pygame.K_DOWN] and direction != 'UP':
        direction = 'DOWN'

    # 移动蛇头
    x, y = snake[0]
    if direction == 'RIGHT':
        x += 10
    if direction == 'LEFT':
        x -= 10
    if direction == 'UP':
        y -= 10
    if direction == 'DOWN':
        y += 10

    # 添加新的蛇头
    snake.insert(0, (x, y))

    # 检测是否吃到食物
    if snake[0] == food:
        food = (random.randrange(0, WIDTH, 10), random.randrange(0, HEIGHT, 10))
    else:
        snake.pop()

    # 绘制界面
    win.fill(BLACK)#将游戏窗口的背景颜色填充为黑色
    pygame.draw.rect(win, RED, (food[0], food[1], 10, 10)) #draw.rect()方法来在游戏窗口中绘制一个红色的矩形,表示食物的位置。
    #在游戏窗口win中绘制一个红色矩形,其左上角的位置为(food[0], food[1]),宽度和高度分别为10像素。这里的RED表示矩形的颜色,可以根据需要更改为其他颜色。
    for segment in snake:
        pygame.draw.rect(win, WHITE, (segment[0], segment[1], 10, 10))
        #中绘制一个白色矩形,其左上角的位置由 segment[0] 和 segment[1] 决定,矩形的宽度和高度都为 10 像素。这里的 WHITE 表示矩形的颜色,

    pygame.display.update()
    clock.tick(10)

这是一个简单的贪吃蛇游戏,贪吃蛇通过方向键控制移动,吃到食物后身体会变长。
 

3-躲避小球

import pygame
import random

pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Ball Game")

player_radius = 20 #玩家球的半径大小
player_color = (255, 0, 0)
player_x = screen_width // 2
player_y = screen_height - 50
player_speed = 5

obstacle_width = 100
obstacle_height = 20
obstacle_color = (0, 0, 255)
obstacle_speed = 3

obstacle_x = random.randint(0, screen_width - obstacle_width)
obstacle_y = 0

clock = pygame.time.Clock()

running = True
while running:
    screen.fill((0, 0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and player_x > player_radius:
        player_x -= player_speed
    if keys[pygame.K_RIGHT] and player_x < screen_width - player_radius:
        player_x += player_speed

    pygame.draw.circle(screen, player_color, (player_x, player_y), player_radius)

    pygame.draw.rect(screen, obstacle_color, (obstacle_x, obstacle_y, obstacle_width, obstacle_height))

    obstacle_y += obstacle_speed
    if obstacle_y > screen_height:
        obstacle_x = random.randint(0, screen_width - obstacle_width)
        obstacle_y = 0

    if player_x + player_radius > obstacle_x and player_x - player_radius < obstacle_x + obstacle_width \
            and player_y + player_radius > obstacle_y and player_y - player_radius < obstacle_y + obstacle_height:
        print("Game Over")
        running = False

    pygame.display.flip()
    clock.tick(60)

pygame.quit()

4、Flappybird 愤怒小鸟的模拟

import pygame
import sys

# 初始化 Pygame
pygame.init()

# 定义窗口大小
WIDTH,HEIGHT = 600,400

# 创建窗口
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Flappy Bird Clone")

# 颜色定义
BACKGROUND_COLOR = (135,206,250)
BIRD_COLOR = (255,255,0)

# 初始化小鸟位置和速度
bird_x,bird_y = WIDTH//2,HEIGHT // 2
#print(type(bird_x))
bird_vel_y = 0

# 游戏主循环
while True:
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # 小鸟控制
    keys = pygame.key.get_pressed()
    if keys[pygame.K_SPACE]:
        bird_vel_y = -1
    
    # 小鸟移动
    bird_y += bird_vel_y
    bird_vel_y += 0.02  # 添加重力

    # 绘制背景
    win.fill(BACKGROUND_COLOR)

    # 绘制小鸟
    print(bird_x)
    print(bird_y)
    pygame.draw.circle(win,BIRD_COLOR,(bird_x,bird_y),10)


    # 更新窗口
    pygame.display.update()


 

希望这几个示例能帮助你开始学习 Pygame,并开发自己的游戏。如果你有任何问题或需要进一步的说明,请告诉我。祝你玩得开心

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值