I'm trying to implement Tetris in Pygame. I wanted to test out an algorithm involving arrays that would in theory draw boxes in a grid. Instead, whenever I run the code, the window pops up and only one square is drawn in the corner of the window.
So I started by making a 2d array -- 20 arrays each with 10 zeros, each zero representing a cell in the game board. Then i used a for loop to iterate through each cell, theoretically drawing a square for each zero in the array. I'm still at the stage where I'm trying to iterate through each zero in a sub-array.
game.py:
import pygame
board_arr = [[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
def iterate_board(screen, rect):
for i in board_arr:
for j in i:
pygame.draw.rect(screen, "red", rect)
rect.x += rect.width
and then I call the "iterate_board" function inside of main.py.
The problem with this is that only one square seems to get drawn.
import pygame
import game
pygame.init()
screen = pygame.display.set_mode((600,600))
#screen = game.screen
bg_hue = "black"
run = True
clock = pygame.time.Clock()
squ = pygame.Rect(0, 10, 20, 20)
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.fill(bg_hue)
game.iterate_board(screen,squ)
pygame.display.update()
clock.tick(60)
pygame.quit()
EDIT: By request, here's the rest of the code. I tweaked it a little, but it's still generally the same
You paint all the blocks in one row because you never change
rect.y. Then, in the next run of thewhileloop, you overwrite everything withscreen.fill(bg_hue)and try to paint again, but the position ofrect.xis now on the right outside the window area. This means that you actually paint, but no one can see it anymore.I added the change to the y-position, the reset of the x-position for a new row, and made sure to not overwrite the initial square.
I also added a function to alter random blocks of the board, so that you can see that it works.
A small hint: If you use
rect.x += rect.width + 1andrect.y += rect.height + 1you can see the grid.