python贪吃蛇编程代码
时间: 2023-07-03 09:29:28 浏览: 99
以下是一个简单的Python贪吃蛇游戏代码示例:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 窗口大小
width = 500
height = 500
# 颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建窗口
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇游戏")
# 蛇的大小
snake_size = 10
# 蛇的移动速度
snake_speed = 15
# 字体
font = pygame.font.SysFont(None, 30)
# 显示文字函数
def message(msg, color):
text = font.render(msg, True, color)
window.blit(text, [width / 6, height / 3])
# 绘制蛇的函数
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(window, black, [pixel[0], pixel[1], snake_size, snake_size])
# 游戏循环
def game_loop():
# 蛇的初始位置
x = width / 2
y = height / 2
# 蛇的移动方向
x_change = 0
y_change = 0
# 食物的初始位置
food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
# 蛇的初始长度
snake_pixels = []
snake_length = 1
# 游戏结束标志
game_over = False
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -snake_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -snake_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = snake_size
x_change = 0
# 移动蛇的位置
x += x_change
y += y_change
# 判断是否吃到食物
if x == food_x and y == food_y:
food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
# 绘制窗口
window.fill(white)
# 绘制食物
pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size])
# 判断游戏是否结束
if x >= width or x < 0 or y >= height or y < 0:
game_over = True
# 更新蛇的位置
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_pixels.append(snake_head)
if len(snake_pixels) > snake_length:
del snake_pixels[0]
# 判断蛇是否碰到自己
for pixel in snake_pixels[:-1]:
if pixel == snake_head:
game_over = True
# 绘制蛇
draw_snake(snake_size, snake_pixels)
# 刷新窗口
pygame.display.update()
# 控制游戏速度
pygame.time.Clock().tick(snake_speed)
# 显示游戏结束文字
message("游戏结束,按 Q 退出,按 C 重新开始", red)
pygame.display.update()
# 游戏结束
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
quit()
elif event.key == pygame.K_c:
game_loop()
# 开始游戏
game_loop()
```
这个代码实现了基本的贪吃蛇游戏,玩家通过方向键控制蛇的移动,吃到食物后蛇的长度会增加,当蛇碰到窗口边缘或碰到自己时游戏结束。
阅读全文