贪吃蛇小游戏代码python
时间: 2023-09-05 18:07:52 浏览: 92
贪吃蛇游戏python代码
5星 · 资源好评率100%
以下是一个简单的Python贪吃蛇小游戏的代码:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 游戏区域大小
width, height = 800, 600
# 创建游戏区域
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# 设置游戏帧率
clock = pygame.time.Clock()
fps = 10
# 定义贪吃蛇
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x, snake_y = width / 2, height / 2
# 定义食物
food_x = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
# 游戏结束函数
def game_over():
font_style = pygame.font.SysFont(None, 50)
message = font_style.render('Game Over!', True, red)
screen.blit(message, (width / 2 - 100, height / 2 - 50))
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
# 游戏主循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 处理键盘事件
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_x -= snake_block_size
elif keys[pygame.K_RIGHT]:
snake_x += snake_block_size
elif keys[pygame.K_UP]:
snake_y -= snake_block_size
elif keys[pygame.K_DOWN]:
snake_y += snake_block_size
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_block_size) / 10.0) * 10.0
snake_length += 1
# 判断是否撞到墙壁或自己
if snake_x < 0 or snake_x > width - snake_block_size or snake_y < 0 or snake_y > height - snake_block_size:
game_over()
head = []
head.append(snake_x)
head.append(snake_y)
snake_list.append(head)
if len(snake_list) > snake_length:
del snake_list[0]
for block in snake_list[:-1]:
if block == head:
game_over()
# 绘制游戏区域
screen.fill(black)
pygame.draw.rect(screen, green, [food_x, food_y, snake_block_size, snake_block_size])
for block in snake_list:
pygame.draw.rect(screen, blue, [block[0], block[1], snake_block_size, snake_block_size])
pygame.display.update()
# 控制游戏帧率
clock.tick(fps)
```
这个代码使用了Pygame库来实现游戏界面和交互逻辑。要运行这个代码,你需要安装Pygame并在Python环境中运行它。
阅读全文