Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
← Step 3 · Tutorial 1.1 · Step 5 →
Add rotation: when the player presses a key (e.g. W or Up), the current piece should rotate 90° clockwise. We already have the right data structure: each piece has several lists of offsets (one per rotation state). Rotating means switching to the next list and wrapping (e.g. 0 → 1 → 2 → 3 → 0).
By the end of this step you should have:
self.offsets - one for each rotation (e.g. 4 for L, 2 for O).rotate() (or rotate(1)): set offset_num = (offset_num + 1) % len(offsets) so the piece uses the next rotation. Drawing and collision already use offsets[self.offset_num], so the piece will look and collide correctly.pieces[0].rotate() (or rotate(1)).We are not yet preventing rotation when it would overlap a wall or the board - that’s Step 5. Here we only add the rotation logic and more offset lists.
Each rotation of a piece is a different set of cells relative to the origin. For example, an L can have four rotations; each is a list of four (dx, dy) pairs. Storing them as offsets[0], offsets[1], … means rotating is just changing the index - no need to compute new coordinates with math.
self.offsets. For L you need 4 lists; for O you need 1 (or 4 identical); for T, S, Z you need 2 or 4 depending on symmetry.rotate(self, n=1): set self.offset_num = (self.offset_num + n) % len(self.offsets).self.pieces[0].rotate(1).Pressing the rotate key should cycle the piece through its rotations. (It may still rotate into walls or the board - we fix that in Step 5.) Compare with the solution when ready.
Then go to Step 5 - Preventing rotation into walls and other pieces.