python写贪吃蛇游戏的代码
时间: 2023-07-10 14:19:03 浏览: 89
好的,以下是一个简单的Python贪吃蛇游戏的代码:
```python
import pygame
import random
# 初始化
pygame.init()
# 设置窗口尺寸
window_width = 640
window_height = 480
window = pygame.display.set_mode((window_width, window_height))
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 设置游戏速度
clock = pygame.time.Clock()
fps = 10
# 定义方块大小和间隔
block_size = 10
block_gap = 2
# 定义蛇的类
class Snake:
def __init__(self):
self.length = 1
self.positions = [(window_width / 2, window_height / 2)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_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 = [(window_width / 2, window_height / 2)]
self.direction = random.choice([pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_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)
def handle_keys(self):
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:
self.turn((0, -1))
elif event.key == pygame.K_DOWN:
self.turn((0, 1))
elif event.key == pygame.K_LEFT:
self.turn((-1, 0))
elif event.key == pygame.K_RIGHT:
self.turn((1, 0))
# 定义食物的类
class Food:
def __init__(self):
x = random.randint(0, (window_width-block_size) // block_size) * block_size
y = random.randint(0, (window_height-block_size) // block_size) * 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)
# 初始化蛇和食物
snake = Snake()
food = Food()
# 游戏循环
while True:
# 处理按键事件
snake.handle_keys()
# 移动蛇
snake.move()
# 判断蛇是否吃到食物
if snake.get_head_position() == food.position:
snake.length += 1
food = Food()
# 绘制背景
window.fill(white)
# 绘制蛇和食物
snake.draw(window)
food.draw(window)
# 更新显示
pygame.display.update()
# 控制游戏速度
clock.tick(fps)
```
这是一个比较简单的贪吃蛇游戏,可以根据需要进行修改和扩展。
阅读全文