给我一个贪吃蛇代码
时间: 2024-02-15 07:02:06 浏览: 106
贪吃蛇代码
这里是一个简单的Python贪吃蛇游戏代码,可以供您参考:
```python
import pygame
import random
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 设置屏幕大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode([screen_width, screen_height])
# 设置字体
font = pygame.font.SysFont(None, 25)
# 设置贪吃蛇的块大小
block_size = 10
# 定义函数,用于显示文字
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [screen_width/2, screen_height/2])
# 定义函数,用于绘制贪吃蛇
def draw_snake(snake_list, block_size):
for x in snake_list:
pygame.draw.rect(screen, BLACK, [x[0], x[1], block_size, block_size])
# 设置游戏循环
def gameLoop():
gameExit = False
gameOver = False
# 初始化贪吃蛇的位置和长度
lead_x = screen_width / 2
lead_y = screen_height / 2
lead_x_change = 0
lead_y_change = 0
snake_list = []
snake_length = 1
# 初始化食物的位置
rand_food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
rand_food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
# 设置游戏循环
while not gameExit:
# 如果游戏结束,显示游戏结束信息并等待玩家重新开始游戏
while gameOver == True:
screen.fill(WHITE)
message_to_screen("Game over, press C to play again or Q to quit", RED)
pygame.display.update()
# 监听事件
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
# 监听事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# 边界判断
if lead_x >= screen_width or lead_x < 0 or lead_y >= screen_height or lead_y < 0:
gameOver = True
# 移动贪吃蛇
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制背景色
screen.fill(WHITE)
# 绘制食物
pygame.draw.rect(screen, RED, [rand_food_x, rand_food_y, block_size, block_size])
# 更新贪吃蛇列表
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# 判断贪吃蛇是否吃到食物
for eachSegment in snake_list[:-1]:
if eachSegment == snake_head:
gameOver = True
# 绘制贪吃蛇
draw_snake(snake_list, block_size)
# 更新分数
text = font.render("Score: " + str(snake_length - 1), True, BLACK)
screen.blit(text, [0, 0])
# 更新屏幕
pygame.display.update()
# 判断是否吃到食物
if lead_x == rand_food_x and lead_y == rand_food_y:
rand_food_x = round(random.randrange(0, screen_width - block_size) / 10.0) * 10.0
rand_food_y = round(random.randrange(0, screen_height - block_size) / 10.0) * 10.0
snake_length += 1
# 设置游戏帧率
clock = pygame.time.Clock()
clock.tick(15)
# 退出游戏
pygame.quit()
quit()
# 开始游戏
gameLoop()
```
希望对您有帮助!
阅读全文