import pygame
import time
import random
# 初始化pygame
pygame.init()
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置蛇和食物的大小
SNAKE_SIZE = 20
FOOD_SIZE = 20
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# 设置蛇的初始位置和速度
snake_pos = [[100, 50],
[90, 50],
[80, 50]]
snake_speed = 10
# 设置食物的位置
food_pos = [random.randrange(1, (SCREEN_WIDTH//SNAKE_SIZE)) * SNAKE_SIZE,
random.randrange(1, (SCREEN_HEIGHT//SNAKE_SIZE)) * SNAKE_SIZE]
# 设置初始方向
direction = 'RIGHT'
change_to = direction
# 设置游戏结束标志
game_over = False
# 设置分数
score = 0
# 设置游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇小游戏')
# 游戏主循环
while not game_over:
# 检查事件
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_UP:
change_to = 'UP'
elif event.key == pygame.K_DOWN:
change_to = 'DOWN'
elif event.key == pygame.K_LEFT:
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
# 确认蛇的方向
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
elif change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# 移动蛇
if direction == 'UP':
snake_pos[0][1] -= SNAKE_SIZE
elif direction == 'DOWN':
snake_pos[0][1] += SNAKE_SIZE
elif direction == 'LEFT':
snake_pos[0][0] -= SNAKE_SIZE
elif direction == 'RIGHT':
snake_pos[0][0] += SNAKE_SIZE
# 蛇身体增长
snake_pos.insert(0, list(snake_pos[0]))
if snake_pos[0] == food_pos:
score += 1
food_pos = [random.randrange(1, (SCREEN_WIDTH//SNAKE_SIZE)) * SNAKE_SIZE,
random.randrange(1, (SCREEN_HEIGHT//SNAKE_SIZE)) * SNAKE_SIZE]
else:
snake_pos.pop()
# 检查游戏结束条件
if snake_pos[0][0] < 0 or snake_pos[0][0] > SCREEN_WIDTH-SNAKE_SIZE:
game_over = True
if snake_pos[0][1] < 0 or snake_pos[0][1] > SCREEN_HEIGHT-SNAKE_SIZE:
game_over = True
for block in snake_pos[1:]:
if snake_pos[0] == block:
game_over = True
# 绘制蛇和食物
screen.fill(BLACK)
for pos in snake_pos:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], SNAKE_SIZE, SNAKE_SIZE))
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], FOOD_SIZE, FOOD_SIZE))
# 更新屏幕显示
pygame.display.flip()
# 控制游戏速度
pygame.time.Clock().tick(snake_speed)
# 退出游戏
pygame.quit()
ssss.rar贪吃蛇游戏demo
需积分: 5 48 浏览量
2024-03-01
18:26:24
上传
评论
收藏 1KB RAR 举报
jing静~
- 粉丝: 618
- 资源: 3