帮我用python写一个贪吃蛇
时间: 2023-07-01 10:06:48 浏览: 79
用python写一个贪吃蛇小游戏
好的,以下是一个简单的贪吃蛇游戏的Python代码。代码中使用了Pygame库来实现游戏界面的绘制,如果你没有安装过Pygame,请先安装。
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义常量
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
BLOCK_SIZE = 20
SPEED = 5
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
# 创建窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 创建时钟对象
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake:
def __init__(self):
self.body = [(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)]
self.direction = 'up'
self.score = 0
def move(self):
x, y = self.body[0]
if self.direction == 'up':
y -= BLOCK_SIZE
elif self.direction == 'down':
y += BLOCK_SIZE
elif self.direction == 'left':
x -= BLOCK_SIZE
elif self.direction == 'right':
x += BLOCK_SIZE
self.body.insert(0, (x, y))
self.body.pop()
def change_direction(self, direction):
if direction == 'up' and self.direction != 'down':
self.direction = 'up'
elif direction == 'down' and self.direction != 'up':
self.direction = 'down'
elif direction == 'left' and self.direction != 'right':
self.direction = 'left'
elif direction == 'right' and self.direction != 'left':
self.direction = 'right'
def eat(self, food):
if self.body[0] == food:
self.body.append(self.body[-1])
self.score += 1
return True
else:
return False
def check_collision(self):
x, y = self.body[0]
if x < 0 or x >= SCREEN_WIDTH or y < 0 or y >= SCREEN_HEIGHT:
return True
for i in range(1, len(self.body)):
if self.body[i] == self.body[0]:
return True
return False
# 定义食物类
class Food:
def __init__(self):
self.position = self.get_random_position()
def get_random_position(self):
x = random.randint(0, (SCREEN_WIDTH - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
y = random.randint(0, (SCREEN_HEIGHT - BLOCK_SIZE) // BLOCK_SIZE) * BLOCK_SIZE
return (x, y)
def draw(self):
pygame.draw.rect(screen, RED, (self.position[0], self.position[1], BLOCK_SIZE, BLOCK_SIZE))
# 创建贪吃蛇对象和食物对象
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
snake.change_direction('up')
elif event.key == pygame.K_DOWN:
snake.change_direction('down')
elif event.key == pygame.K_LEFT:
snake.change_direction('left')
elif event.key == pygame.K_RIGHT:
snake.change_direction('right')
# 移动贪吃蛇
snake.move()
# 检查是否吃到食物
if snake.eat(food.position):
food.position = food.get_random_position()
# 检查是否撞到墙或自身
if snake.check_collision():
pygame.quit()
exit()
# 绘制游戏界面
screen.fill(WHITE)
snake_head = pygame.draw.rect(screen, BLACK, (snake.body[0][0], snake.body[0][1], BLOCK_SIZE, BLOCK_SIZE))
for i in range(1, len(snake.body)):
pygame.draw.rect(screen, BLACK, (snake.body[i][0], snake.body[i][1], BLOCK_SIZE, BLOCK_SIZE))
food.draw()
pygame.display.update()
# 控制游戏速度
clock.tick(SPEED)
```
这个贪吃蛇游戏比较简单,可能还有许多需要改进的地方,欢迎你进行修改和完善。
阅读全文