python

怎么用python实现一个简单的贪吃蛇游戏

小亿
96
2024-03-21 19:21:54
栏目: 编程语言

下面是一个简单的贪吃蛇游戏的Python实现代码示例:

import pygame
import time
import random

pygame.init()

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

# 设置颜色
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)

# 设置蛇和食物初始位置
snake_block = 10
snake_speed = 15
snake_pos = [(win_width//2, win_height//2)]
food_pos = (random.randint(0, win_width//snake_block - 1) * snake_block, random.randint(0, win_height//snake_block - 1) * snake_block)

# 初始化方向
x_change = 0
y_change = 0

# 游戏主循环
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -snake_block
                y_change = 0
            elif event.key == pygame.K_RIGHT:
                x_change = snake_block
                y_change = 0
            elif event.key == pygame.K_UP:
                x_change = 0
                y_change = -snake_block
            elif event.key == pygame.K_DOWN:
                x_change = 0
                y_change = snake_block
    
    # 更新蛇的位置
    new_pos = (snake_pos[0][0] + x_change, snake_pos[0][1] + y_change)
    snake_pos.insert(0, new_pos)
    
    # 检查蛇是否吃到食物
    if snake_pos[0] == food_pos:
        food_pos = (random.randint(0, win_width//snake_block - 1) * snake_block, random.randint(0, win_height//snake_block - 1) * snake_block)
    else:
        snake_pos.pop()
    
    # 绘制窗口
    win.fill(black)
    for pos in snake_pos:
        pygame.draw.rect(win, white, (pos[0], pos[1], snake_block, snake_block))
    pygame.draw.rect(win, red, (food_pos[0], food_pos[1], snake_block, snake_block))
    
    pygame.display.update()
    
    # 控制蛇的速度
    pygame.time.Clock().tick(snake_speed)
    
# 退出游戏
pygame.quit()

这段代码实现了一个简单的贪吃蛇游戏,玩家可以通过方向键控制蛇的移动方向,吃到食物会增加蛇的长度,如果蛇撞到墙壁或者撞到自己就会游戏结束。希望对你有帮助!

0
看了该问题的人还看了