• FEATURED

View more

View more

View more

### Image of the Day Submit

IOTD | Top Screenshots

### The latest, straight to your Inbox.

Subscribe to GameDev.net Direct to receive the latest updates and exclusive content.

# Solid Objects in Pygame

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

5 replies to this topic

### #1Pneum  Members

Posted 11 May 2014 - 12:21 AM

Hello, everyone. I have a little bit of programming experience, having messed with Python on and off over the years. I'm just now getting my feet wet in game development, and I've already run into a problem.

I want to make a simple maze game. The object of the game will be to navigate a white square from the upper-left corner of the screen to the bottom-right corner, through a simple maze. The problem I am having is this: how can I prevent the square from simply passing through the walls of the maze? Clearly, I need some way to make the walls "solid" so that the square cannot pass through them.

My first solution was this: every pixel occupied by a wall is stored in a huge list, as is every pixel occupied by the square. Each time the player presses an arrow key, the game checks to see if the pixel that the square is about to move into is occupied by a wall. It does this by taking each pixel occupied by the square, and checking it against each pixel occupied by any wall. If there are no "matches," the square moves. So, in pseudocode:

list1 = list of all pixels occupied by square

list2 = list of all pixels occupied by maze walls

if the user presses the "left" button:

Check to see if there are any "matches" between any pixel to the left of a pixel in list 1 and any pixel in list2

If there are any matches: the square stays stationary

Otherwise: the square moves

Although I got it to work, it was very slow. Can anyone give me a better method to keep track of where the walls and square are? More importantly, can anyone share some general principles for keeping track of objects on screen?

Edited by Pneum, 14 May 2014 - 06:43 PM.

### #2dr01d3k4  Members

Posted 11 May 2014 - 03:00 AM

If the walls are all square, then you can just use a tile grid.

grid = [
[True, True, True, True],
[True, False, True, True],
[True, False, False, True],
[True, True, True, True]
];

In a way, this is similar to storing the actual pixels, but using 16/32/64...(whatever your tile size is) times less space. This does mean that when rendering you need to make sure to multiply by tile size:

TILE_SIZE = 16;

for y in range(grid):
for x in range(grid[y]):
# isSolid for here could just return the cell because the true/false represents its solidity
# But if you want to change what data you store about each cell, then it's good to already have this in its own function
if (isSolid(grid[y][x])):
# I don't know Pygame's API
drawRectangle(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE, CELL_COLOUR);

For the physics, you need to step x and y individually. A good guide for this is in "the guide to implementing 2d platformers" (although it says platformers, it still works in top down, and it's a good read too if you want to make a platformer next).

Falling block colour flood game thing I'm making: http://jsfiddle/dr01d3k4/JHnCV/

### #3SeraphLance  Members

Posted 11 May 2014 - 02:01 PM

If the user moves exactly one tile every move, all you need to do is check if a wall is in the way.  If not, it's a bit more complicated, but you still don't need to check per-pixel.  Don't think of things in terms of physical "pixels".  Try to distinguish between the visual representation and logical representation.  A wall looks like a bunch of pixels, but really it's just a block of a certain width and height.

### #4Pneum  Members

Posted 13 May 2014 - 05:45 AM

Thanks for the advice, both abstract (SeraphLance) and concrete (dr01d3k4). I'll take it on board.

### #5Pneum  Members

Posted 14 May 2014 - 06:47 PM

Hello, all. I've taken your advice on board and found some success with it, but I've had a new problem. I created a game where one could move a rectangle around by pressing up, down, left, or right. The floor is "solid," and I successfully programmed the game to stop the rectangle from moving through the floor. However, I've run into a problem again: the movement works fine for the first few button presses or so, but after that, a glitch happens where the rectangle will refuse to move at all. Here's the code, if anyone can take a look at it:

import pygame

# Define some colors
BLACK    = (   0,   0,   0)
WHITE    = ( 255, 255, 255)
GREEN    = (   0, 255,   0)
RED      = ( 255,   0,   0)

pygame.init()

#Set the width and height of the screen [width,height]
size = (700,500)
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Jumping Square!")

#Loop until the user clicks the close button
done = False

#Used to manage how fast the screen updates
clock = pygame.time.Clock()

def generatetiles(x,y): #Generates a tile grid, implemented by a matrix
countx = 0
county = 0
indices = []
while countx < x:
indices.append([])
countx += 1
county = 0 #reset y coordinate count each time
while county < y:
indices[countx - 1].append(0) #0 means an unnoccupied tile. Initialize to an empty grid.
county += 1
return indices

Tiles = generatetiles(70,50)

class stationaryobject: #Hitbox for anything that stays still
def __init__(self,x1,x2,y1,y2): #x1/x2 and y1/y2 specify corners of hitbox
countx = x1
county = y1
while countx <= x2: #Since x2 is counted up before it's used, we use <=
county = y1
countx += 1
while county < y2 + 1:
Tiles[countx-1][county] = 1
county += 1

class moveableobject:
def __init__(self,x1,x2,y1,y2):
self.occupiedtiles = {}
countx = x1
county = y1
while countx <= x2:
self.occupiedtiles[countx]=[]
countx += 1
county = y1
while county < y2:
self.occupiedtiles[countx-1].append(county)
Tiles[countx-1][county] = 1
county += 1

#define methods to scan the top, bottom, left and right sides of the object's hitbox to return data for movement.
def scanleftside(self):
firstxcoordinate = self.occupiedtiles.keys()[0]
return {self.occupiedtiles.keys()[0]:self.occupiedtiles[firstxcoordinate]}
def scanrightside(self):
lastxcoordinate = self.occupiedtiles.keys()[-1]
return {self.occupiedtiles.keys()[-1]:self.occupiedtiles[lastxcoordinate]}
def scantop(self):
top = {}
for xcoordinate in self.occupiedtiles:
top[xcoordinate] = self.occupiedtiles[xcoordinate][0]
def scanbottom(self):
bottom = {}
for xcoordinate in self.occupiedtiles:
bottom[xcoordinate] = self.occupiedtiles[xcoordinate][-1]
return bottom

def moveleft(self):
leftside = self.scanleftside()
xcoordinate = leftside.keys()[0]
blockedflag = 0
for ycoordinate in leftside[xcoordinate]:
if Tiles[xcoordinate-1][ycoordinate] == 1: blockedflag = 1
if blockedflag == 0:
rightmostxcoordinate = self.occupiedtiles.keys()[-1]
leftmostxcoordinate  = self.occupiedtiles.keys()[0]
del self.occupiedtiles[rightmostxcoordinate]
for ycoordinate in Tiles[rightmostxcoordinate]: ycoordinate = 0
self.occupiedtiles[leftmostxcoordinate-1] = self.occupiedtiles[leftmostxcoordinate]
def moveright(self):
rightside = self.scanrightside()
xcoordinate = rightside.keys()[0]
blockedflag = 0
for ycoordinate in rightside[xcoordinate]: #Check coordinates to the right of the current right side to see if they're occupied
if Tiles[xcoordinate+1][ycoordinate] == 1: blockedflag = 1
if blockedflag == 0:
rightmostxcoordinate = self.occupiedtiles.keys()[-1]
leftmostxcoordinate = self.occupiedtiles.keys()[0]
del self.occupiedtiles[leftmostxcoordinate]
for ycoordinate in Tiles[leftmostxcoordinate]: ycoordinate = 0
self.occupiedtiles[rightmostxcoordinate+1] = self.occupiedtiles[rightmostxcoordinate]
def moveup(self):
top = self.scantop()
ycoordinate = top.keys()[0]
blockedflag = 0
for xcoordinate in top:
if Tiles[xcoordinate][ycoordinate-1] == 1: blockedflag = 1
if blockedflag == 0:
for xcoordinate in self.occupiedtiles:
del self.occupiedtiles[xcoordinate][-1]
Tiles[xcoordinate][-1] = 0
self.occupiedtiles[xcoordinate].append(ycoordinate-1)
self.occupiedtiles[xcoordinate] = sorted(self.occupiedtiles[xcoordinate])
def movedown(self):
bottom = self.scanbottom()
ycoordinate = bottom[bottom.keys()[0]]
blockedflag = 0
for xcoordinate in bottom:
if Tiles[xcoordinate][ycoordinate+1] == 1: blockedflag = 1
if blockedflag == 0:
for xcoordinate in self.occupiedtiles:
del self.occupiedtiles[xcoordinate][0]
Tiles[xcoordinate][0] = 0
self.occupiedtiles[xcoordinate].append(ycoordinate+1)
self.occupiedtiles[xcoordinate] = sorted(self.occupiedtiles[xcoordinate])

player = moveableobject(1,2,3,6)
square = stationaryobject(34,39,44,49)
floor = stationaryobject(0,69,48,49)

# -------- Main Program Loop -----------
while not done:
# --- Main event loop
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT: player.moveleft()
if event.key == pygame.K_RIGHT: player.moveright()
if event.key == pygame.K_UP: player.moveup()
if event.key == pygame.K_DOWN: player.movedown()
# --- Game logic should go here

# --- Drawing code should go here

# First, clear the screen to white. Don't put other drawing commands
# above this, or they will be erased with this command.
screen.fill(BLACK)

pygame.draw.line(screen,GREEN,[0,490],[700,490],1)
pygame.draw.rect(screen,GREEN,[350,441,50,50],1)
pygame.draw.rect(screen,WHITE,[player.occupiedtiles.keys()[0]*10,player.occupiedtiles[player.occupiedtiles.keys()[0]][0]*10,20,40],1)

# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()

# --- Limit to 60 frames per second
clock.tick(60)

# Close the window and quit.
# If you forget this line, the program will 'hang'
# on exit if running from IDLE.
pygame.quit()

I've tried to solve this problem by setting the movement methods to print the value of "blockedflag" each time the user presses a button, to make sure that the rectangle was not being blocked unnecessarily. No such luck: "blockedflag" always returned 0, unless the square was pressing against a hard surface (which means that the blockedflag value is working the way it should). I also tried printing the global tile matrix ("Tiles", defined on line 36) each time the user moved, to make sure that the values stored in that matrix were being deleted correctly (they were). So what gives? Can anyone point to a flaw in this code that my dumb eyes seem to have missed?

Edited by Pneum, 14 May 2014 - 09:47 PM.

### #6dr01d3k4  Members

Posted 15 May 2014 - 12:58 PM

I'm not entirely sure what you're doing. Your code is hard to read and follow, and has lots of duplicated code.

I made this example that shows moving the player 1 tile at a time (the collision for this is a lot easier).

import pygame;
from random import randint;

BLACK = (  0,   0,   0);
WHITE = (255, 255, 255);
GREEN = (  0, 255,   0);
RED   = (255,   0,   0);

BACKGROUND_COLOUR = BLACK;
TILE_COLOUR = GREEN;
PLAYER_COLOUR = WHITE;

TILE_NONE = False;
TILE_SOLID = True;

SCREEN_WIDTH = 700;
SCREEN_HEIGHT = 500;
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT);

MAP_WIDTH = 64;
MAP_HEIGHT = 32;
TILE_SIZE = 16;

TITLE = "Maze Game";

FPS = 60;

def sign(x):
return (x < 0) and -1 or (x > 0) and 1 or 0;

class Player(object):
def __init__(self, x, y):
self.x = x;
self.y = y;

def move(self, dx, dy, tiles):
if (dx != 0):
if (dy != 0):
return;

newX = self.x + sign(dx);
if (not isSolidTile(tiles, newX, self.y)):
self.x = newX;

elif (dy != 0):
if (dx != 0):
return;

newY = self.y + sign(dy);
if (not isSolidTile(tiles, self.x, newY)):
self.y = newY;

def generateTiles(width, height):
tiles = [ ];

for x in range(0, width):
tiles.append([ ]);

for y in range(0, height):
tileType = TILE_NONE;

if ((x == 0) or (y == 0) or (x == width - 1) or (y == height - 1) or (randint(0, 10) < 2)):
tileType = TILE_SOLID;

tiles[x].append(tileType);

return tiles;

def isSolidTile(tiles, x, y):
return ((x < 0) or (y < 0) or (x >= MAP_WIDTH) or (y >= MAP_HEIGHT) or (tiles[x][y] == TILE_SOLID));

def renderTiles(screen, tiles):
for x in range(0, len(tiles)):
for y in range(0, len(tiles[x])):
if (isSolidTile(tiles, x, y)):
pygame.draw.rect(screen, TILE_COLOUR, [x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE], 0);

def renderPlayer(screen, player):
pygame.draw.rect(screen, PLAYER_COLOUR, [player.x * TILE_SIZE, player.y * TILE_SIZE, TILE_SIZE, TILE_SIZE], 0);

def playGame():
pygame.init();
screen = pygame.display.set_mode(SCREEN_SIZE);
pygame.display.set_caption(TITLE);
clock = pygame.time.Clock();

playing = True;

tiles = generateTiles(MAP_WIDTH, MAP_HEIGHT);
player = Player(2, 2);

while (playing):
for event in pygame.event.get():
if (event.type == pygame.QUIT):
playing = False;

if (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_LEFT):
player.move(-1, 0, tiles);
if (event.key == pygame.K_RIGHT):
player.move(1, 0, tiles);
if (event.key == pygame.K_UP):
player.move(0, -1, tiles);
if (event.key == pygame.K_DOWN):
player.move(0, 1, tiles);

screen.fill(BACKGROUND_COLOUR);

renderTiles(screen, tiles);
renderPlayer(screen, player);

pygame.display.flip();
clock.tick(FPS);

pygame.quit();

if (__name__ == "__main__"):
playGame();

The way it works is:

• There is a 2 dimensional array of booleans - true for tile being there; false if there isn't
• When rendering, iterate through these and if there's a tile, draw it at that location * TILE_SIZE (in a real game you may want to account for camera moving and only thinking about what is actually on screen)
• Player's position is (x, y), which is the location of the top left corner in tile space. The size of the player is assumed to be 1x1. Just like with tiles, when rendering need to scale by TILE_SIZE
• When the player attempts to move, +- 1 in the direction they want to move, if there isn't a tile there then it's safe to move, else do nothing

Falling block colour flood game thing I'm making: http://jsfiddle/dr01d3k4/JHnCV/

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.