用pygame制作一个超级好玩的不用导入图片的小游戏
下面是一个使用pygame制作的简单小游戏,不需要导入任何图片。这个游戏是一个简单的“躲避球”游戏,玩家需要控制一个小球,避开随机生成的障碍物。游戏会计算玩家的得分,并在玩家碰到障碍物时结束。
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口的宽度和高度
WIDTH = 800
HEIGHT = 600
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("躲避球")
# 定义颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 定义小球的初始位置和半径
ball_x = WIDTH // 2
ball_y = HEIGHT - 50
ball_radius = 10
# 定义小球的移动速度
ball_speed = 5
# 定义障碍物的初始位置和大小
obstacle_x = random.randint(0, WIDTH)
obstacle_y = 0
obstacle_width = random.randint(50, 200)
obstacle_height = random.randint(50, 200)
# 定义得分
score = 0
# 游戏循环
running = True
while running:
    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # 移动小球
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and ball_x > ball_radius:
        ball_x -= ball_speed
    if keys[pygame.K_RIGHT] and ball_x < WIDTH - ball_radius:
        ball_x += ball_speed
    # 移动障碍物
    obstacle_y += 3
    # 判断是否碰撞
    if obstacle_y > HEIGHT:
        obstacle_x = random.randint(0, WIDTH)
        obstacle_y = 0
        obstacle_width = random.randint(50, 200)
        obstacle_height = random.randint(50, 200)
        score += 1
    if ball_x + ball_radius > obstacle_x and ball_x - ball_radius < obstacle_x + obstacle_width and ball_y + ball_radius > obstacle_y and ball_y - ball_radius < obstacle_y + obstacle_height:
        running = False
    # 绘制背景
    screen.fill(WHITE)
    # 绘制小球
    pygame.draw.circle(screen, RED, (ball_x, ball_y), ball_radius)
    # 绘制障碍物
    pygame.draw.rect(screen, RED, (obstacle_x, obstacle_y, obstacle_width, obstacle_height))
    # 绘制得分
    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(score), True, RED)
    screen.blit(text, (10, 10))
    # 刷新屏幕
    pygame.display.flip()
# 退出游戏
pygame.quit()
这个游戏中,玩家可以使用左右箭头键控制小球的移动,避开障碍物。随着时间的推移,障碍物的速度会逐渐增加,难度会逐渐增加。当小球碰到障碍物时,游戏结束,会显示玩家的得分
原文地址: https://www.cveoy.top/t/topic/iaDO 著作权归作者所有。请勿转载和采集!