随笔 - 31  文章 - 0  评论 - 0  阅读 - 5133

用pygame开发的贪吃蛇小游戏

import pygame
import sys
import random

初始化Pygame

pygame.init()

游戏窗口的宽度和高度

WIDTH, HEIGHT = 400, 400

定义颜色

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)

设置游戏窗口

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")

定义贪吃蛇的初始位置

snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]

定义食物的初始位置

food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True

定义初始方向

direction = 'RIGHT'
change_to = direction

定义游戏速度(帧数)

FPS = 15

定义得分

score = 0

游戏主循环

while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'

# 防止贪吃蛇反向移动
if change_to == 'UP' and not direction == 'DOWN':
    direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
    direction = 'DOWN'
if change_to == 'LEFT' and not direction == 'RIGHT':
    direction = 'LEFT'
if change_to == 'RIGHT' and not direction == 'LEFT':
    direction = 'RIGHT'

# 根据方向移动贪吃蛇头部
if direction == 'UP':
    snake_pos[1] -= 10
if direction == 'DOWN':
    snake_pos[1] += 10
if direction == 'LEFT':
    snake_pos[0] -= 10
if direction == 'RIGHT':
    snake_pos[0] += 10

# 增加贪吃蛇的长度
snake_body.insert(0, list(snake_pos))

# 如果吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
    score += 10
    food_spawn = False
else:
    snake_body.pop()

if not food_spawn:
    food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]

food_spawn = True
screen.fill(BLACK)

for pos in snake_body:
    pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))

pygame.draw.rect(screen, WHITE, pygame.Rect(food_pos[0], food_pos[1], 10, 10))

if (snake_pos[0] < 0 or snake_pos[0] > WIDTH-10 or
    snake_pos[1] < 0 or snake_pos[1] > HEIGHT-10):
    pygame.quit()
    sys.exit()

for block in snake_body[1:]:
    if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
        pygame.quit()
        sys.exit()

pygame.display.flip()
pygame.display.update()
pygame.time.Clock().tick(FPS)
posted on   IT老boy  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示