用python做一个贪吃蛇
时间: 2023-07-18 07:45:21 浏览: 115
贪吃蛇python源码.pdf
5星 · 资源好评率100%
好的,下面是一个用Python实现的简单贪吃蛇游戏,使用了Pygame库。
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 创建游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和大小
snake_x = [300, 280, 260]
snake_y = [300, 300, 300]
snake_size = 20
# 定义食物的初始位置和大小
food_x = round(random.randrange(0, WINDOW_WIDTH - snake_size) / 20.0) * 20.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - snake_size) / 20.0) * 20.0
food_size = 20
# 定义蛇的移动速度
snake_speed = 20
# 定义蛇的移动方向
direction = "right"
# 定义字体
font = pygame.font.SysFont(None, 30)
# 定义游戏结束函数
def game_over():
text = font.render("游戏结束!", True, RED)
window.blit(text, [WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 定义游戏循环
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_LEFT:
direction = "left"
elif event.key == pygame.K_RIGHT:
direction = "right"
elif event.key == pygame.K_UP:
direction = "up"
elif event.key == pygame.K_DOWN:
direction = "down"
# 移动蛇的身体
for i in range(len(snake_x) - 1, 0, -1):
snake_x[i] = snake_x[i - 1]
snake_y[i] = snake_y[i - 1]
# 移动蛇的头部
if direction == "left":
snake_x[0] -= snake_speed
elif direction == "right":
snake_x[0] += snake_speed
elif direction == "up":
snake_y[0] -= snake_speed
elif direction == "down":
snake_y[0] += snake_speed
# 判断蛇是否吃到食物
if snake_x[0] == food_x and snake_y[0] == food_y:
food_x = round(random.randrange(0, WINDOW_WIDTH - snake_size) / 20.0) * 20.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - snake_size) / 20.0) * 20.0
snake_x.append(snake_x[-1])
snake_y.append(snake_y[-1])
# 判断蛇是否撞墙或者自己
if snake_x[0] >= WINDOW_WIDTH or snake_x[0] < 0 or snake_y[0] >= WINDOW_HEIGHT or snake_y[0] < 0:
game_over()
for i in range(1, len(snake_x)):
if snake_x[0] == snake_x[i] and snake_y[0] == snake_y[i]:
game_over()
# 绘制游戏界面
window.fill(WHITE)
pygame.draw.rect(window, GREEN, [food_x, food_y, food_size, food_size])
for i in range(len(snake_x)):
pygame.draw.rect(window, BLACK, [snake_x[i], snake_y[i], snake_size, snake_size])
pygame.display.update()
pygame.time.delay(100)
```
希望这个简单的示例可以帮助你入门Python编程和游戏开发。
阅读全文