python贪吃蛇代码
时间: 2023-07-09 09:41:09 浏览: 33
以下是一个简单的Python贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义方向
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 初始化
pygame.init()
# 设置窗口大小和标题
screen_width = 800
screen_height = 600
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 = random.randint(0, 3)
self.score = 0
def move(self):
head = self.body[0]
if self.direction == UP:
new_head = (head[0], head[1]-10)
elif self.direction == DOWN:
new_head = (head[0], head[1]+10)
elif self.direction == LEFT:
new_head = (head[0]-10, head[1])
else:
new_head = (head[0]+10, head[1])
self.body.insert(0, new_head)
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_food(self, food):
if self.body[0][0] == food.x and self.body[0][1] == food.y:
self.body.append((food.x, food.y))
self.score += 10
return True
else:
return False
def collide_self(self):
if self.body[0] in self.body[1:]:
return True
else:
return False
def collide_wall(self):
if self.body[0][0] < 0 or self.body[0][0] > screen_width-10 \
or self.body[0][1] < 0 or self.body[0][1] > screen_height-10:
return True
else:
return False
# 定义食物类
class Food:
def __init__(self):
self.x = random.randint(0, screen_width-10)
self.y = random.randint(0, screen_height-10)
def draw(self):
pygame.draw.rect(screen, RED, (self.x, self.y, 10, 10))
# 初始化贪吃蛇和食物
snake = Snake()
food = Food()
# 游戏循环
game_over = False
while not game_over:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
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)
# 绘制背景
screen.fill(WHITE)
# 绘制贪吃蛇和食物
for part in snake.body:
pygame.draw.rect(screen, GREEN, (part[0], part[1], 10, 10))
food.draw()
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.eat_food(food):
food = Food()
# 判断是否碰到自己或者墙壁
if snake.collide_self() or snake.collide_wall():
game_over = True
# 显示分数
font = pygame.font.SysFont(None, 25)
text = font.render("Score: " + str(snake.score), True, BLACK)
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.update()
# 控制帧率
clock.tick(15)
# 退出游戏
pygame.quit()
```
运行以上代码,即可打开贪吃蛇游戏窗口,使用方向键控制贪吃蛇的移动,吃到食物可以加分,碰到自己或者墙壁会结束游戏。