Pygame贪吃蛇

本文介绍了一个使用Python和Pygame库实现的经典贪吃蛇游戏。游戏包含蛇的移动、食物生成及碰撞检测等功能,并实现了基本的游戏循环和用户交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记一次,自己使用Pygame写的贪吃蛇游戏

 

# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
from sys import exit
from random import randint


size = width, height = 640, 480         # 窗口大小
snake_size = 20                         # 蛇身大小
snake_head_color = 255, 0, 255          # 蛇头的颜色
snake_color = 0, 0, 255                 # 蛇身的颜色
food_color = 255, 0, 0                  # 食物的颜色
background_color = 255, 255, 255        # 背景颜色
line_color = 200, 200, 200              # 边框线颜色


direction = {K_UP: (0, -1), K_DOWN: (0, 1),
    K_LEFT:(-1, 0), K_RIGHT:(1, 0)}     # 上下左右的方向
snake_direction = K_UP                  # 蛇移动的方向,默认向上移动
quit = False                            # 是否退出
pause = False                           # 是否暂停


pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption('贪吃蛇')


food = (0, 0)                           # 食物坐标
snake = [((width // snake_size) // 2, ((height // snake_size) // 2) - 1)]   # 蛇
snake.append((snake[0][0], snake[0][1] + 1))
snake.append((snake[1][0], snake[1][1] + 1))
clock = pygame.time.Clock()
time = 0                               
FPS = 30


def get_food():
    food = snake[0]
    while food in snake:
        food = randint(0, (width // snake_size) - 1), randint(0, (height // snake_size) - 1)
    return food

def draw_rect(color, point):
    pygame.draw.rect(screen, color, ((point[0] * snake_size + 1, point[1] * snake_size + 1),
    (snake_size - 1, snake_size - 1)))


def snake_move():
    '''撞墙或撞到蛇身死亡则返回False, 否则返回true'''
    global food
    next_head = (snake[0][0] + direction[snake_direction][0],
                    snake[0][1] + direction[snake_direction][1])
    if next_head in snake:
        return False

    if next_head[0] < 0 or next_head[0] >= width // snake_size or \
        next_head[1] < 0 or next_head[1] >= height // snake_size:
        return False

    # 蛇向前移动
    snake.insert(0, next_head)
    # 重画旧蛇头为蛇身
    draw_rect(snake_color, snake[1])
    # 画新的蛇头
    draw_rect(snake_head_color, snake[0])
    
    # 判断是否吃到食物
    if next_head[0] == food[0] and next_head[1] == food[1]:
        # 蛇已经满屏了
        if len(snake) == (width // snake_size) * (height // snake_size):
            return Flase

        # 产生新食物
        food = get_food()
        # 画新的食物
        draw_rect(food_color, food)

    else:
        # 抹去蛇尾
        draw_rect(background_color, snake[-1])
        snake.pop()

    return True
    


food = get_food()
# 先画以下背景 白色
screen.fill(background_color)
# 画边框
for x in range(width // snake_size):
    pygame.draw.line(screen, line_color, (x * snake_size, 0), (x * snake_size, height), 1)
for y in range(height // snake_size):
    pygame.draw.line(screen, line_color, (0, y * snake_size), (width, y * snake_size), 1)
# 画食物
draw_rect(food_color, food)
# 画蛇头
draw_rect(snake_head_color, snake[0])
for point in snake[1:]:
    # 画蛇身
    draw_rect(snake_color, point)


while True:
    # 锁定帧率
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == QUIT:
            quit = True
            break
        elif event.type == KEYDOWN:
            if event.key == K_UP or event.key == K_DOWN or\
                event.key == K_LEFT or event.key == K_RIGHT:
                # 避免反向自杀
                if direction[snake_direction][0] + direction[event.key][0] != 0 and \
                    direction[snake_direction][1] + direction[event.key][1] != 0:
                    snake_direction = event.key
            elif event.key == K_p:
                pause = not pause
            elif event.key == K_ESCAPE:
                quit = True

    if pause: continue
    if quit: break

    # 5 / FPS s 移动一次
    if time > 5:
        # 移动
        if not snake_move(): break
        # 刷新画面
        pygame.display.update()
        time = 0
    else:
        time += 1



# 显示游戏结束
font = pygame.font.SysFont('方正粗黑宋简体', 48)
text_surface = font.render(u'游戏结束!', True, (255, 0, 0))
x, y = (width - text_surface.get_width()) // 2, (height - text_surface.get_height()) // 2
screen.blit(text_surface, (x, y))
pygame.display.update()

# 暂停 1500 ms
pygame.time.wait(2000)

pygame.display.quit()



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值