给一段贪吃蛇的python代码
时间: 2024-08-27 15:01:12 浏览: 85
Python-贪吃蛇.zip
好的,下面是一个简单的贪吃蛇游戏的Python代码示例,使用了pygame库来创建游戏界面:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
screen_width = 400
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("贪吃蛇")
snake_speed = 15
snake_color = (0, 255, 0)
food_color = (255, 0, 0)
# 初始化蛇的位置和大小
snake_pos = [(screen_width // 2, screen_height // 2)]
snake_size = 1
direction = "right"
# 定义食物生成位置
def generate_food():
while True:
food_x = random.randint(0, screen_width - snake_size)
food_y = random.randint(0, screen_height - snake_size)
if (food_x, food_y) not in snake_pos:
return food_x, food_y
# 游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != "down":
direction = "up"
elif event.key == pygame.K_DOWN and direction != "up":
direction = "down"
elif event.key == pygame.K_LEFT and direction != "right":
direction = "left"
elif event.key == pygame.K_RIGHT and direction != "left":
direction = "right"
# 更新蛇的位置
new_head = list(snake_pos[-1])
if direction == "up":
new_head[1] -= snake_size
elif direction == "down":
new_head[1] += snake_size
elif direction == "left":
new_head[0] -= snake_size
else:
new_head[0] += snake_size
snake_pos.append(new_head)
# 检查边界和碰撞
if new_head[0] < 0 or new_head[0] >= screen_width or new_head[1] < 0 or new_head[1] >= screen_height:
print("Game Over! You hit the border.")
break
if new_head in snake_pos[:-1]:
print("Game Over! You hit yourself.")
break
# 移除蛇尾
snake_pos.pop(0)
# 画蛇和食物
screen.fill((0, 0, 0))
for pos in snake_pos:
pygame.draw.rect(screen, snake_color, [pos[0], pos[1], snake_size, snake_size])
food_x, food_y = generate_food()
pygame.draw.rect(screen, food_color, [food_x, food_y, snake_size, snake_size])
# 更新屏幕
pygame.display.update()
pygame.time.delay(snake_speed)
# 结束游戏
pygame.quit()
```
阅读全文