一、引言

前面教程中我们学会判断绿色方块接收红色方块,我们来增加一个功能,在屏幕左上角显示游戏的得分。

二、实现思路

目前我们只有一个红色方块,为了能有机会撞到多次好计分,红色方块掉到最下方或者被接住后,我们需要重新生成红色方块。代码上的实现比较简单,将红色方块的位置重新改变下就可以实现该需求了。另外,我们增加一个变量score,当红色方块被接住后,我们就让score增加1,就达到统计好分数的目的。
相关代码:


import pygame, sys

# 初始化
pygame.init()
SCREEN = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')

# 绿色方块固定在最下方,左右移动,y值不变
green_x = 110
# 红色方块从上往下移动,x值不变
red_y = 0
# 游戏主循环
score = 0
while True: 
    for event in pygame.event.get():
        # 处理退出事件
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # 键盘按下事件
        elif event.type == pygame.KEYDOWN:
            # 'a'键被按下
            if event.key == pygame.K_a:
                green_x -= 5
            elif event.key == pygame.K_d:
                green_x += 5
    red_y += 5
    green_rect = pygame.Rect(green_x, 250, 100, 50)
    if green_rect.colliderect(85, red_y, 20, 50):
        print('红色方块与绿色方块碰撞到了')
        # 为了方便看到碰撞结果,直接break返回
        score += 1
        red_y = 0
    if red_y >= 300:
        red_y = 0
    SCREEN.fill((255, 255, 255))
    # 调用 pygame.display.update() 方法更新整个屏幕的显示
    pygame.draw.rect(SCREEN, (255, 0, 0), (85, red_y, 20, 50))
    pygame.draw.rect(SCREEN, (0, 255, 0), (green_x, 250, 100, 50))
    pygame.display.update()
    pygame.time.delay(50)


游戏主要逻辑已经完成,我们只需要增加显示分数的功能。通过查文档(百度找个能看懂的例子学习),显示文字需要以下几行代码。


# 初始化


仿照以上的代码,我们将代码实现出来。需要注意的是,文字转为图片、图片显示出来两行代码是每个循环里都需要做的事情,所以必须加在while循环里,否则文字无法显示出来,会被后面的覆盖

最终代码如下:


import pygame, sys

# 初始化
pygame.init()
SCREEN = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')

# 绿色方块固定在最下方,左右移动,y值不变
green_x = 110
# 红色方块从上往下移动,x值不变
red_y = 0
# 游戏主循环
score = 0
pygame.font.init()
myfont = pygame.font.Font(None,60)

while True: 
    for event in pygame.event.get():
        # 处理退出事件
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # 键盘按下事件
        elif event.type == pygame.KEYDOWN:
            # 'a'键被按下
            if event.key == pygame.K_a:
                green_x -= 5
            elif event.key == pygame.K_d:
                green_x += 5
    red_y += 5
    green_rect = pygame.Rect(green_x, 250, 100, 50)
    if green_rect.colliderect(85, red_y, 20, 50):
        print('红色方块与绿色方块碰撞到了')
        # 为了方便看到碰撞结果,直接break返回
        score += 1
        red_y = 0
    if red_y >= 300:
        red_y = 0
    SCREEN.fill((255, 255, 255))
    # 调用 pygame.display.update() 方法更新整个屏幕的显示
    pygame.draw.rect(SCREEN, (255, 0, 0), (85, red_y, 20, 50))
    pygame.draw.rect(SCREEN, (0, 255, 0), (green_x, 250, 100, 50))
    textImage = myfont.render("score: " + str(score), True, (0, 0, 255))
    SCREEN.blit(textImage, (10,10))
    pygame.display.update()
    pygame.time.delay(50)


三、思考题

  1. 把文字的显示改成黄色,位置在右上角。