python实现贪吃蛇游戏
时间: 2023-08-23 13:08:26 浏览: 154
好的,下面是一个简单的贪吃蛇游戏的 Python 实现:
```python
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 设置窗口大小
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# 设置方格大小
BLOCK_SIZE = 20
# 初始化 Pygame
pygame.init()
# 创建窗口
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 设置窗口标题
pygame.display.set_caption('贪吃蛇')
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇类
class Snake():
def __init__(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
def get_head_position(self):
return self.positions[0]
def turn(self, point):
if self.length > 1 and (point[0]*-1, point[1]*-1) == self.direction:
return
else:
self.direction = point
def move(self):
cur = self.get_head_position()
x, y = self.direction
new = ((cur[0] + (x*BLOCK_SIZE)), (cur[1] + (y*BLOCK_SIZE)))
if new in self.positions[2:]:
self.reset()
else:
self.positions.insert(0, new)
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
self.length = 1
self.positions = [(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
def draw(self, surface):
for p in self.positions:
r = pygame.Rect((p[0], p[1]), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义食物类
class Food():
def __init__(self):
x = random.randrange(0, SCREEN_WIDTH, BLOCK_SIZE)
y = random.randrange(0, SCREEN_HEIGHT, BLOCK_SIZE)
self.position = (x, y)
self.color = RED
def draw(self, surface):
r = pygame.Rect((self.position[0], self.position[1]), (BLOCK_SIZE, BLOCK_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# 定义方向常量
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# 创建贪吃蛇和食物对象
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.turn(UP)
elif event.key == pygame.K_DOWN:
snake.turn(DOWN)
elif event.key == pygame.K_LEFT:
snake.turn(LEFT)
elif event.key == pygame.K_RIGHT:
snake.turn(RIGHT)
# 移动贪吃蛇
snake.move()
# 判断是否吃到食物
if snake.get_head_position() == food.position:
snake.length += 1
food = Food()
# 绘制游戏画面
screen.fill(WHITE)
snake.draw(screen)
food.draw(screen)
pygame.display.update()
# 控制游戏帧率
clock.tick(15)
```
这个代码实现了一个基本的贪吃蛇游戏,玩家可以通过方向键控制贪吃蛇的移动,吃到食物后贪吃蛇的长度会增加。
阅读全文