贪吃蛇游戏代码Python
时间: 2024-06-16 11:02:24 浏览: 198
一个简单的贪吃蛇游戏的完整 Python 代码
贪吃蛇是一款经典的电子游戏,使用Python编写一个基本版本的贪吃蛇游戏并不复杂。主要涉及游戏循环、蛇的移动、食物生成和碰撞检测等核心部分。以下是一个简单的Python游戏代码概述:
1. 导入必要的库:`pygame`库用于图形处理。
```python
import pygame
```
2. 初始化游戏窗口和设置:
```python
pygame.init()
screen = pygame.display.set_mode((400, 400))
pygame.display.set_caption("贪吃蛇")
clock = pygame.time.Clock()
snake_color = (0, 255, 0)
food_color = (255, 0, 0)
```
3. 定义蛇、食物和得分:
```python
snake_block = 10
snake = [(100, 100), (90, 100), (80, 100)] # 初始位置
food_pos = (randint(0, screen_width // snake_block), randint(0, screen_height // snake_block))
score = 0
```
4. 游戏循环(主循环):
```python
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_UP] and snake > 0:
snake_head = (snake, snake - snake_block)
elif keys[pygame.K_DOWN] and snake < screen_height - snake_block:
snake_head = (snake, snake + snake_block)
elif keys[pygame.K_LEFT] and snake > 0:
snake_head = (snake - snake_block, snake)
elif keys[pygame.K_RIGHT] and snake < screen_width - snake_block:
snake_head = (snake[0] + snake_block, snake)
# 移动蛇身,添加新头部
new_snake = [snake_head]
new_snake.extend(snake[:-1])
snake = new_snake
# 检查碰撞和食物
if snake_head in snake[1:]:
print("Game Over!")
break
if snake_head == food_pos:
score += 1
food_pos = (randint(0, screen_width // snake_block), randint(0, screen_height // snake_block))
else:
snake.pop(0)
# 绘制元素
screen.fill((0, 0, 0))
for pos in snake:
pygame.draw.rect(screen, snake_color, pygame.Rect(pos, pos, snake_block, snake_block))
pygame.draw.rect(screen, food_color, pygame.Rect(food_pos, food_pos, snake_block, snake_block))
pygame.display.flip()
clock.tick(10)
```
阅读全文