如何用递归函数绘制5个方块堆叠?求draw_stack函数编写思路
Hey there! Let's break this down step by step—recursion can feel a bit abstract at first, but once you nail the base case and recursive step, it'll make perfect sense.
First: Recursion Core Mindset
Recursion works by splitting a big problem into smaller, identical subproblems until you hit a "base case" (a problem so small you can solve it immediately with no more recursion). For stacking 5 blocks:
- Big problem: Draw 5 blocks anchored at (100, 200)
- Subproblem: Draw 1 block, then stack 4 blocks on top of it
- Even smaller subproblem: Draw 1 block, then stack 3 blocks...
- Base case: Draw 0 blocks (do nothing, just return)
Second: Clarify Coordinate Logic
First, let's assume your draw_block(screen, x, y) function draws a block with its top-left corner at (x, y). Most graphics libraries (like Pygame) use a coordinate system where y increases downward, so stacking blocks upward means decreasing the y-value by the block's height each time.
Let's define a constant for block height first (adjust this to your desired size):
BLOCK_HEIGHT = 50 # Height of each individual block
Third: Write the Recursive Function
Here's how to implement draw_stack to handle stacking 5 blocks at your anchor point:
def draw_stack(screen, x, y, count): # Base case: Stop recursion if we don't need to draw any more blocks if count <= 0: return # Step 1: Draw the current (bottom-most) block at the given coordinates draw_block(screen, x, y) # Step 2: Recursively draw the remaining blocks stacked above this one # We adjust the y-coordinate upward by subtracting the block height draw_stack(screen, x, y - BLOCK_HEIGHT, count - 1)
To draw 5 blocks anchored at (100, 200), call it like this:
draw_stack(screen, 100, 200, 5)
Let's Walk Through the Execution
For clarity, here's how the recursion plays out when count=5:
- First call: Draws a block at (100, 200), then calls
draw_stack(screen, 100, 150, 4) - Second call: Draws at (100, 150), calls
draw_stack(screen, 100, 100, 3) - Third call: Draws at (100, 100), calls
draw_stack(screen, 100, 50, 2) - Fourth call: Draws at (100, 50), calls
draw_stack(screen, 100, 0, 1) - Fifth call: Draws at (100, 0), calls
draw_stack(screen, 100, -50, 0) - Sixth call: Hits the base case (
count=0), returns, and the recursion unwinds to finish.
Adjustments If Needed
- If your
heightparameter was meant to be the block's height (not the count), modify the function to accept both:
Call it with:def draw_stack(screen, x, y, block_height, count=5): if count <= 0: return draw_block(screen, x, y) draw_stack(screen, x, y - block_height, block_height, count - 1)draw_stack(screen, 100, 200, 50) - If you want to stack downward instead of upward, change
y - BLOCK_HEIGHTtoy + BLOCK_HEIGHT.
内容的提问来源于stack exchange,提问作者user14050624

