python编写贪吃蛇
时间: 2023-07-07 07:39:02 浏览: 82
好的,下面是一个简单的 Python 贪吃蛇游戏的代码示例:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 设置屏幕大小
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇")
# 定义蛇的初始位置和大小
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
# 定义食物的初始位置和大小
food_pos = [random.randrange(1, (SCREEN_WIDTH//10)) * 10, random.randrange(1, (SCREEN_HEIGHT//10)) * 10]
food_spawned = 1
# 定义方向
direction = "RIGHT"
change_to = direction
# 定义游戏结束条件
game_over = False
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义显示分数的函数
def show_score(score):
score_font = font_style.render("Score: " + str(score), True, WHITE)
screen.blit(score_font, [0, 0])
# 定义游戏结束的函数
def game_over_msg():
game_font = font_style.render("Game Over!", True, RED)
screen.blit(game_font, [SCREEN_WIDTH//3, SCREEN_HEIGHT//3])
# 游戏循环
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 判断键盘事件
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_to = "RIGHT"
elif event.key == pygame.K_LEFT:
change_to = "LEFT"
elif event.key == pygame.K_UP:
change_to = "UP"
elif event.key == pygame.K_DOWN:
change_to = "DOWN"
# 判断蛇不能掉头
if change_to == "RIGHT" and direction != "LEFT":
direction = "RIGHT"
elif change_to == "LEFT" and direction != "RIGHT":
direction = "LEFT"
elif change_to == "UP" and direction != "DOWN":
direction = "UP"
elif change_to == "DOWN" and direction != "UP":
direction = "DOWN"
# 移动蛇的身体
if direction == "RIGHT":
snake_pos[0] += 10
elif direction == "LEFT":
snake_pos[0] -= 10
elif direction == "UP":
snake_pos[1] -= 10
elif direction == "DOWN":
snake_pos[1] += 10
# 增加蛇的身体长度
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
food_spawned = 0
else:
snake_body.pop()
# 生成新的食物
if food_spawned == 0:
food_pos = [random.randrange(1, (SCREEN_WIDTH//10)) * 10, random.randrange(1, (SCREEN_HEIGHT//10)) * 10]
food_spawned = 1
# 绘制游戏界面
screen.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(screen, WHITE, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
if snake_pos[0] < 0 or snake_pos[0] > SCREEN_WIDTH-10:
game_over = True
elif snake_pos[1] < 0 or snake_pos[1] > SCREEN_HEIGHT-10:
game_over = True
for block in snake_body[1:]:
if snake_pos == block:
game_over = True
show_score(len(snake_body)-3)
pygame.display.update()
# 设置游戏帧率
clock.tick(15)
# 显示游戏结束信息
game_over_msg()
# 等待用户关闭窗口
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
```
这是一个非常基本的贪吃蛇游戏,你可以根据自己的需求对其进行修改和扩展。
阅读全文