用python写贪吃蛇游戏
时间: 2023-09-30 14:11:00 浏览: 51
好的,以下是用Python实现贪吃蛇游戏的代码:
```python
import pygame
import random
# 初始化pygame模块
pygame.init()
# 设置屏幕大小及标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 定义方向常量
UP = 0
DOWN = 1
LEFT = 2
RIGHT = 3
# 定义蛇类
class Snake:
def __init__(self):
self.body = [(screen_width // 2, screen_height // 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = green
def move(self):
# 获取蛇头位置
x, y = self.body[0]
# 根据方向改变位置
if self.direction == UP:
y -= 10
elif self.direction == DOWN:
y += 10
elif self.direction == LEFT:
x -= 10
elif self.direction == RIGHT:
x += 10
# 将新的头部位置插入到蛇身中
self.body.insert(0, (x, y))
# 删除蛇尾
self.body.pop()
def draw(self):
for x, y in self.body:
pygame.draw.rect(screen, self.color, (x, y, 10, 10))
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
# 定义食物类
class Food:
def __init__(self):
self.position = self.new_position()
self.color = red
def new_position(self):
x = random.randrange(0, screen_width - 10, 10)
y = random.randrange(0, screen_height - 10, 10)
return (x, y)
def draw(self):
x, y = self.position
pygame.draw.rect(screen, self.color, (x, y, 10, 10))
# 创建贪吃蛇和食物对象
snake = Snake()
food = Food()
# 游戏循环
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:
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.body[0] == food.position:
snake.body.append(snake.body[-1])
food.position = food.new_position()
# 判断是否撞到墙或自己
if snake.body[0][0] < 0 or snake.body[0][0] > screen_width - 10 or snake.body[0][1] < 0 or snake.body[0][1] > screen_height - 10:
pygame.quit()
quit()
for i in range(1, len(snake.body)):
if snake.body[0] == snake.body[i]:
pygame.quit()
quit()
# 绘制背景和文字
screen.fill(white)
text = font.render('Score: ' + str(len(snake.body) - 1), True, black)
screen.blit(text, (10, 10))
# 绘制蛇和食物
snake.draw()
food.draw()
# 更新显示
pygame.display.update()
```
这个游戏实现了贪吃蛇的基本逻辑,包括蛇的移动、吃食物、撞墙或自己等情况的判断。你可以尝试运行代码,体验一下这个游戏。