Menu
CoddyTech

Puntuación y velocidad

Parte de la sección Reglas del juego del Journey de Pygame de Coddy. Lección 28 de 30.

La puntuación de un juego de carrera infinita se basa en la distancia. Un temporizador suma un punto cada 100 ms, así que un segundo corriendo vale 10:

POINT = pygame.USEREVENT + 2
pygame.time.set_timer(POINT, 100)

Muéstrala en la parte superior derecha con ceros, 00042, como en Meteor Dodge.

El juego se vuelve más difícil a medida que avanzas. Vincula la velocidad a la puntuación: 6 píxeles por fotograma al principio, uno más cada 100 puntos, nunca más de 14:

speed = min(14, 6 + score // 100)

Obstacle.update() lee speed en cada fotograma, así que la nueva velocidad también llega a los obstáculos que ya están en pantalla. min es el límite: a 14, un obstáculo cruza la ventana en menos de un segundo; a cualquier velocidad mayor, el jugador no podría reaccionar.

challenge icon

Desafío

Intermedio

Puntúa la distancia y aumenta la velocidad del juego.

  1. Añade POINT = pygame.USEREVENT + 2, un temporizador para este cada 100 ms y score = 0.
  2. Durante la partida, cuando se produzca POINT, suma 1 a la puntuación.
  3. Durante la partida, establece speed = min(14, 6 + score // 100) antes de actualizar.
  4. Muestra la puntuación con cinco dígitos en (40, 50, 80) con topright=(630, 10).

Pulsa «Jugar»: la puntuación aumenta. Después, pulsa «Comprobar».

Pruébalo tú mismo

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 320))
pygame.display.set_caption("Sky Runner")
clock = pygame.time.Clock()
font = pygame.font.Font("assets/fonts/pixel.ttf", 32)

SKY = (140, 200, 240)
GROUND = (90, 160, 80)
GROUND_Y = 260
GRAVITY = 1
SPAWN = pygame.USEREVENT + 1


class Runner(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.frames = [
            pygame.image.load("assets/images/player.png").convert_alpha(),
            pygame.image.load("assets/images/player_walk.png").convert_alpha(),
        ]
        self.image = self.frames[0]
        self.step = 0
        self.rect = self.image.get_rect(midbottom=(100, GROUND_Y))
        self.vy = 0

    def jump(self):
        if self.rect.bottom == GROUND_Y:
            self.vy = -16

    def update(self):
        self.vy += GRAVITY
        self.rect.y += self.vy
        if self.rect.bottom >= GROUND_Y:
            self.rect.bottom = GROUND_Y
            self.vy = 0
        if self.rect.bottom == GROUND_Y:
            self.step += 1
            self.image = self.frames[self.step // 8 % 2]
        else:
            self.image = self.frames[1]


class Obstacle(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = random.choice(obstacle_images)
        self.rect = self.image.get_rect(midbottom=(664, GROUND_Y))

    def update(self):
        self.rect.x -= speed
        if self.rect.right < 0:
            self.kill()


obstacle_images = [
    pygame.image.load("assets/images/spike_ball.png").convert_alpha(),
    pygame.image.load("assets/images/blob.png").convert_alpha(),
]
runner = Runner()
obstacles = pygame.sprite.Group()
speed = 6
pygame.time.set_timer(SPAWN, 1500)
state = "play"

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
            if state == "play":
                runner.jump()
        if event.type == SPAWN and state == "play":
            obstacles.add(Obstacle())
            pygame.time.set_timer(SPAWN, random.randint(1000, 2000))

    if state == "play":
        runner.update()
        obstacles.update()
        if pygame.sprite.spritecollideany(runner, obstacles, pygame.sprite.collide_mask):
            state = "over"

    screen.fill(SKY)
    pygame.draw.rect(screen, GROUND, (0, GROUND_Y, 640, 60))
    screen.blit(runner.image, runner.rect)
    obstacles.draw(screen)
    if state == "over":
        message = font.render("Game over", True, (40, 50, 80))
        screen.blit(message, message.get_rect(center=(320, 140)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

Todas las lecciones de Reglas del juego

Practica por tu cuenta: Playground de Pygame