请用Python写一个贪吃蛇的游戏
时间: 2024-01-05 11:04:46 浏览: 90
使用Python写一个贪吃蛇游戏实例代码
以下是一个简单的贪吃蛇游戏的Python代码:
```python
import pygame, random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 500
window_height = 500
window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置蛇的初始位置和长度
snake_x = 250
snake_y = 250
snake_size = 10
snake_speed = 10
snake_list = []
snake_length = 1
# 设置食物的位置
food_x = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
# 设置游戏循环标志
game_over = False
# 定义画蛇和画食物的函数
def draw_snake(snake_list):
for x,y in snake_list:
pygame.draw.rect(window, black, [x, y, snake_size, snake_size])
def draw_food(food_x, food_y):
pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 处理蛇的移动
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
snake_x -= snake_speed
if keys[pygame.K_RIGHT]:
snake_x += snake_speed
if keys[pygame.K_UP]:
snake_y -= snake_speed
if keys[pygame.K_DOWN]:
snake_y += snake_speed
# 判断是否吃到食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_size) / 10.0) * 10.0
snake_length += 1
# 更新蛇的位置列表
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断是否碰到边界或自身
if snake_x < 0 or snake_x > window_width - snake_size or snake_y < 0 or snake_y > window_height - snake_size:
game_over = True
for block in snake_list[:-1]:
if block == snake_head:
game_over = True
# 绘制游戏界面
window.fill(white)
draw_snake(snake_list)
draw_food(food_x, food_y)
pygame.display.update()
# 退出pygame
pygame.quit()
```
这个代码实现了一个简单的贪吃蛇游戏,玩家可以通过方向键控制蛇的移动。游戏中包括蛇的移动、食物的生成、碰撞检测等基本功能。
阅读全文