Prajjwal Pathak
Prajjwal Pathak

Reputation: 119

Generate tiles in piano tiles consecutively in pygame

I have created a simple piano tiles game clone in pygame.

Everything working fine except the way i am generating tiles after every certain interval, but as the game speed increases this leaves a gap between two tiles.

In the original version of the game, there's no lag (0 distance ) between two incoming tiles.

Here's a preview of the game:

Currently I am generating tiles like this:

ADDBLOCK = pygame.USEREVENT + 1
ADDTIME = 650
pygame.time.set_timer(ADDBLOCK, ADDTIME)

if event.type == ADDBLOCK:
    x_col = random.randint(0,3)
    block = Block(win, (67.5 * x_col, -120))
    block_group.add(block)

But with time, these tiles speed increase so there's remain a gap between generation of two tiles as shown by red line in the preview. Is there any way to generate tiles consecutively?

Source Code

Upvotes: 1

Views: 610

Answers (1)

D_00
D_00

Reputation: 1497

Use a variable number to know how many tiles have been generated since the start. This variable will start with 0, then you will add 1 to this variable every time a tile is generated.

Then, you can use a variable like scrolling which increases continuously. You will add this scrolling to every tile y pos to render them.

Now you just have to add a tile which y position is like -tile_height - tile_height * number.

If that doesn't make sense to you, look at this MRE:

import pygame
from pygame.locals import *
from random import randint
pygame.init()

screen = pygame.display.set_mode((240, 480))
clock = pygame.time.Clock()

number_of_tiles = 0
tile_height = 150
tile_surf = pygame.Surface((60, tile_height))
tiles = [] # [column, y pos]
scrolling = 0
score = 0
speed = lambda: 200 + 5*score # increase with the score

time_passed = 0
while True:
    click = None # used to click on a tile
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()
        if event.type == MOUSEBUTTONDOWN:
            click = event.pos

    screen.fill((150, 200, 255))

    if scrolling > number_of_tiles * tile_height:
        # new tile
        # use "while" instead of "if" if you want to go at really high speed
        tiles.append([randint(0, 3), -tile_height - number_of_tiles * tile_height])
        number_of_tiles += 1

    for x, y in tiles:
        screen.blit(tile_surf, (60 * x, y + scrolling))
        if y + scrolling > 480: # delete any tile that is no longer visible
            tiles.remove([x, y])
        if click is not None and Rect((60 * x, y + scrolling), tile_surf.get_size())
                                .collidepoint(click):
            tiles.remove([x, y]) # delete any tile that has been clicked
            score += 1 # used to calculate speed

    scrolling += speed() * time_passed
    pygame.display.flip()
    time_passed = clock.tick() / 1000

Upvotes: 1

Related Questions