我正在尝试使用pygame中的递归创建一个看起来相似的Excel文档。我得到了第一个if语句来填充屏幕的第一行,并希望它每次下降50(矩形的高度),并一直继续下去直到它再次击中屏幕边缘,以完全填充屏幕。我做了另一个for循环来尝试此操作,但它停止并错过了(0,0)处的一个矩形,有没有办法在一个循环中执行此操作,以便屏幕将填充并形成一堆列和行?谢谢。
"""
Recursively draw rectangles.
Sample Python/Pygame Programs
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
"""
import pygame
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
def recursive_draw(x, y, width, height):
""" Recursive rectangle function. """
pygame.draw.rect(screen, BLACK,
[x, y, width, height],
1)
# Is the rectangle wide enough to draw again?
if(x < 750):
# Scale down
x += 150
y = 0
width = 150
height = 50
# Recursively draw again
recursive_draw(x, y, width, height)
if (x < 750):
# Scale down
x += 0
y += 50
width = 150
height = 50
# Recursively draw again
recursive_draw(x, y, width, height)
pygame.init()
# Set the height and width of the screen
size = [750, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Set the screen background
screen.fill(WHITE)
# ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT
recursive_draw(0, 0, 150, 50)
# ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Limit to 60 frames per second
clock.tick(60)
# Be IDLE friendly. If you forget this line, the program will 'hang'
# on exit.
pygame.quit()
答案 0 :(得分:2)
我首先添加一个基本情况,以便在到达屏幕底部时该函数返回。将width
添加到x
直到到达右侧,当它到达右侧时,递增y += height
并重置x = 0
以开始绘制下一行。
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
def recursive_draw(x, y, width, height):
"""Recursive rectangle function."""
pygame.draw.rect(screen, BLACK, [x, y, width, height], 1)
if y >= 500: # Screen bottom reached.
return
# Is the rectangle wide enough to draw again?
elif x < 750-width: # Right screen edge not reached.
x += width
# Recursively draw again.
recursive_draw(x, y, width, height)
else:
# Increment y and reset x to 0 and start drawing the next row.
x = 0
y += height
recursive_draw(x, y, width, height)
pygame.init()
size = [750, 500]
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
screen.fill(WHITE)
recursive_draw(0, 0, 150, 50)
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.flip()
clock.tick(60)
pygame.quit()
使用嵌套的for循环绘制网格会更容易:
def draw_grid(x, y, width, height, size):
for y in range(0, size[1], height):
for x in range(0, size[0], width):
pygame.draw.rect(screen, BLACK, [x, y, width, height], 1)