用一个变量记录得分

1如何统计得分
先创建一个变量score用来统计得分 要先把score转换成字符串 然后如果蛇头碰到了食物那 score就加10
在使用score_font去选择一个你需要的的字体 然后再用screen.blit(text_surface, (20, 20))去把它创建在屏幕上

import pygame
import random
from helper import is_eat_self, get_next_pos
pygame.init()

size = (600, 400)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("生成食物, 让蛇变长")

clock = pygame.time.Clock()
body_size = 20
green = (0, 255, 0)#浅绿色
dark_grenn = (0, 204, 0)#深绿色
red = (255, 0, 0)#大红色
snake_body = [
    pygame.Rect(100, 100, body_size, body_size),#头部
    pygame.Rect(80, 100, body_size, body_size),
    pygame.Rect(60, 100, body_size, body_size)
]#初始状态下蛇的身体有 3 节
# 1 让蛇往上移动 如果旧的头部坐标(x y)那么新的坐标(x, y-20)
# 2 让蛇向右移动 旧头部的坐标(x y)那么新的坐标(x+20, y)
# 3 往下移动 但坐标是(x, y) 新坐标(x, y+20)
# 4 往左移动 旧坐标是(x, y) 新坐标(x-20, y)

direction = 1 # 右:1 下;2 左:3 上:4
running = True
# 把食物生成坐标对其到20的边界
# 列如(20, 40), (60, 100)
# 78//20*20 = 3*20  == 60
# N//20*20
food = pygame.Rect(random.randint(10,500)//20*20, random.randint(10, 380)//20*20, body_size, body_size)
score = 0#用来统计得分
# 加载系统字体,大小为16pt
score_font = pygame.font.SysFont("Academy Engraved LET", 32)
while running:
    screen.fill((0, 0, 0))
    pygame.draw.rect(screen, red, food)
    events = pygame.event.get()#获取所有事件
    for e in events:
        if e.type == pygame.QUIT:#响应退出时间
            running = False
        if e.type == pygame.KEYDOWN:
            if e.key == pygame.K_UP and direction!=2:
                direction = 4
            if e.key == pygame.K_DOWN and direction!=4:
                direction = 2
            if e.key == pygame.K_LEFT and direction!=1:
                direction = 3
            if e.key == pygame.K_RIGHT and direction!=3:

                direction = 1
    nx, ny = get_next_pos(direction, snake_body[0].x, snake_body[0].y, body_size)

    nh = pygame.Rect(nx, ny, body_size, body_size)  # 新头部的正方形
# 判断新生成的头部是否超过了边界
# 屏幕范围size(600, 400)
    if nx>size[0]-1 or ny >size[1]-1 or nx<0 or ny<0:
        running = False
#判断头部是否碰到身体a
    if is_eat_self(nh, snake_body):
        running = False
    snake_body.insert(0, nh)  # 插入新的头部
    if nh.colliderect(food):#如果碰到食物, 就生成新的事物, 而且不删除尾巴
        score += 10
        food = pygame.Rect(random.randint(10, 500 )//20*20, random.randint(10, 300)//20*20, body_size, body_size)
    else:
        snake_body.pop()  # 删除旧的尾巴
    for body in snake_body:#遍历每一个矩形(body)
        pygame.draw.rect(screen, green, body)#在screen上画出绿色的矩形
    score_text = str(score)# 把得分转换成字符串
    pygame.draw.rect(screen, dark_grenn, snake_body[0])#用深绿色画出头部矩形, 效果:覆盖刚出来的浅绿色头部
    text_surface = score_font.render(score_text, True, red)
    screen.blit(text_surface, (20, 20))#把字显示到屏幕上
    pygame.display.update()#刷新屏幕
    clock.tick(2)

pygame.quit() #释放资源


posted @ 2026-01-14 20:21  王奕健  阅读(3)  评论(0)    收藏  举报