Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
← Step 1 · Tutorial 1.1 · Step 3 →
Add a Piece class and a way to store both the locked blocks (the board) and the current falling piece. By the end of this step you should have:
"location" (column, row) and optionally "image" (we can use a coloured rect for now).[x, y] in grid cells) and a list of offsets - each offset is a list of (dx, dy) positions that form the shape. For example, an L might have one list of four (dx, dy) pairs. The piece is drawn by drawing a cell at (origin[0] + dx, origin[1] + dy) for each offset.We’re not moving or rotating yet - we’re deciding how we represent the board and the piece so that moving and rotating are easier later.
origin. Rotation later will be “switch to a different list of offsets” (we’ll add that in Step 4).Game, ensure you have a board list (from Step 1) and a pieces list. Create one Piece and append it to pieces.Piece class that takes the game (e.g. self.game) and a simple type (e.g. "L" or "O"). In __init__, set:
self.origin = [x, 0] (e.g. x in the middle of the game area).self.offsets = [...] - one list of (dx, dy) tuples for that shape (e.g. four cells for an L or a square).self.offset_num = 0 (which rotation we’re using; for now there’s only one).render method on Piece that draws the piece: for each offset in self.offsets[self.offset_num], draw a cell at (origin[0] + dx, origin[1] + dy) in pixel coordinates (using self.game.grid_size and self.game.game_location).self.pieces[0].render() so the current piece is visible.Run your game. You should see the game area and one piece (e.g. an L or a square) drawn inside it. Once you’re happy, compare with the solution.
Then go to Step 3 - Moving pieces and collision.