这是一个简单的 Python 贪吃蛇游戏代码示例,使用 Pygame 库实现。

import pygame
import sys
import time
import random

pygame.init()

# 游戏窗口的尺寸
window_width = 800
window_height = 600

# 贪吃蛇和食物的尺寸
snake_size = 20
food_size = 20

# 贪吃蛇的移动速度
snake_speed = 15

# 定义颜色
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)

# 创建游戏窗口
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')

# 初始化蛇的初始位置和长度
snake_head = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]

# 初始化食物的位置
food_pos = [random.randrange(1, (window_width // snake_size)) * snake_size,
            random.randrange(1, (window_height // snake_size)) * snake_size]
food_exists = True

# 初始化移动方向
direction = 'RIGHT'
change_to = direction

# 初始化游戏得分
score = 0


# 游戏结束函数
def game_over():
    font = pygame.font.SysFont(None, 72)
    text = font.render('Game Over!', True, red)
    game_window.blit(text, (window_width / 2 - text.get_width() / 2, window_height / 2 - text.get_height() / 2))
    pygame.display.flip()
    time.sleep(2)
    pygame.quit()
    sys.exit()


# 游戏主循环
while True:
    # 检测游戏退出事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # 检测按键事件
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT or event.key == ord('d'):
                change_to = 'RIGHT'
            if event.key == pygame.K_LEFT or event.key == ord('a'):
                change_to = 'LEFT'
            if event.key == pygame.K_UP or event.key == ord('w'):
                change_to = 'UP'
            if event.key == pygame.K_DOWN or event.key == ord('s'):
                change_to = 'DOWN'
            if event.key == pygame.K_ESCAPE:
                pygame.event.post(pygame.event.Event(pygame.QUIT))

    # 根据移动方向更新蛇头的坐标
    if change_to == 'RIGHT' and direction != 'LEFT':
        direction = 'RIGHT'
    if change_to == 'LEFT' and direction != 'RIGHT':
        direction = 'LEFT'
    if change_to == 'UP' and direction != 'DOWN':
        direction = 'UP'
    if change_to == 'DOWN' and direction != 'UP':
        direction = 'DOWN'

    if direction == 'RIGHT':
        snake_head[0] += snake_size
    if direction == 'LEFT':
        snake_head[0] -= snake_size
    if direction == 'UP':
        snake_head[1] -= snake_size
    if direction == 'DOWN':
        snake_head[1] += snake_size

    # 更新蛇的身体
    snake_body.insert(0, list(snake_head))
    if snake_head[0] == food_pos[0] and snake_head[1] == food_pos[1]:
        score += 1
        food_exists = False
    else:
        snake_body.pop()

    # 生成新的食物
    if not food_exists:
        food_pos = [random.randrange(1, (window_width // snake_size)) * snake_size,
                    random.randrange(1, (window_height // snake_size)) * snake_size]
    food_exists = True

    # 游戏界面绘制
    game_window.fill(black)
    for pos in snake_body:
        pygame.draw.rect(game_window, green, pygame.Rect(pos[0], pos[1], snake_size, snake_size))
    pygame.draw.rect(game_window, white, pygame.Rect(food_pos[0], food_pos[1], food_size, food_size))

    # 判断游戏结束条件
    if snake_head[0] >= window_width or snake_head[0] < 0 or snake_head[1] >= window_height or snake_head[1] < 0:
        game_over()
    for block in snake_body[1:]:
        if snake_head[0] == block[0] and snake_head[1] == block[1]:
            game_over()

    # 更新游戏得分
    font = pygame.font.SysFont(None, 24)
    score_text = font.render('Score: ' + str(score), True, white)
    game_window.blit(score_text, (5, 5))

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

    # 控制游戏速度
    clock = pygame.time.Clock()
    clock.tick(snake_speed)

请注意,这只是一个简单的示例,代码中可能还有一些需要改进的地方。同时,运行此代码需要安装 Pygame 库。

如何安装 Pygame 库:

pip install pygame

原文地址: https://www.cveoy.top/t/topic/o5lQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录