用python写一个贪吃蛇脚本
时间: 2024-01-07 11:04:54 浏览: 78
好的,关于Python编写贪吃蛇的脚本,我可以给您提供一些基础的代码模板,包括游戏的主要逻辑和图形化界面的实现,您可以根据需要进行修改和完善。以下是示例代码:
```
import pygame
import random
# 初始化pygame模块
pygame.init()
# 设置游戏窗口大小
width = 640
height = 480
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("贪吃蛇游戏")
# 设置游戏时钟
clock = pygame.time.Clock()
# 设置贪吃蛇的初始位置、身体长度和移动速度
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
snake_speed = 10
# 设置食物的初始位置和大小
food_position = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]
food_size = 10
# 设置方向
direction = "RIGHT"
change_to = direction
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont(None, 50)
text = font.render("游戏结束!", True, (255, 0, 0))
screen.blit(text, [width // 4, height // 4])
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
quit()
# 游戏循环
while True:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over()
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_position[0] += snake_speed
elif direction == "LEFT":
snake_position[0] -= snake_speed
elif direction == "UP":
snake_position[1] -= snake_speed
elif direction == "DOWN":
snake_position[1] += snake_speed
# 更新贪吃蛇的身体
snake_body.insert(0, list(snake_position))
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
food_position = [random.randrange(1, (width // 10)) * 10, random.randrange(1, (height // 10)) * 10]
else:
snake_body.pop()
# 游戏胜利条件
if snake_position[0] >= width or snake_position[0] < 0:
game_over()
elif snake_position[1] >= height or snake_position[1] < 0:
game_over()
for block in snake_body[1:]:
if snake_position[0] == block[0] and snake_position[1] == block[1]:
game_over()
# 绘制游戏场景
screen.fill((255, 255, 255))
for position in snake_body:
pygame.draw.rect(screen, (0, 255, 0), pygame.Rect(position[0], position[1], 10, 10))
pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(food_position[0], food_position[1], food_size, food_size))
pygame.display.update()
# 设置游戏时钟
clock.tick(20)
# 退出pygame模块
pygame.quit()
```
以上代码是一个基础的贪吃蛇模板,您可以根据需要进行进一步的完善和改进,例如添加渐变颜色、声音效果、排行榜等功能。希望对您有所帮助!
阅读全文