用python写一个贪吃蛇的程序能运行能用键盘控制
- 1.源码
- 2.运行效果
1.源码
开发库使用:pygame random
直接在终端运行:pip install pygame
pycharm安装库:文件-设置-项目-Python 解释器
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置标题
pygame.display.set_caption("Snake Game")
# 设置蛇的初始位置
snake_x = 350
snake_y = 350
# 设置蛇的速度
snake_speed = 20
# 设置蛇的身体
snake_body = [(snake_x, snake_y)]
# 设置食物的位置
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 设置游戏结束标志
game_over = False
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake_y -= snake_speed
elif event.key == pygame.K_DOWN:
snake_y += snake_speed
elif event.key == pygame.K_LEFT:
snake_x -= snake_speed
elif event.key == pygame.K_RIGHT:
snake_x += snake_speed
# 移动蛇的身体
snake_body.insert(0, (snake_x, snake_y))
# 检查蛇是否碰到墙壁
if snake_x < 0 or snake_x >= screen_width - 10 or snake_y < 0 or snake_y >= screen_height - 10:
game_over = True
# 检查蛇是否碰到自己
#if蛇身体中的任何两个点重叠:
# game_over = True
# 检查蛇是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = random.randint(0, screen_width - 10)
food_y = random.randint(0, screen_height - 10)
snake_body.append((food_x, food_y))
# 绘制背景
screen.fill((0, 0, 0))
# 绘制蛇的身体
for x, y in snake_body[1:]:
pygame.draw.rect(screen, (0, 255, 0), (x, y, 10, 10))
# 绘制食物
pygame.draw.rect(screen, (255, 0, 0), (food_x, food_y, 10, 10))
# 更新屏幕
pygame.display.flip()
# 游戏结束
pygame.quit()