【问题标题】:Creating a grid in pygame using for loops使用 for 循环在 pygame 中创建网格
【发布时间】:2017-01-31 14:43:39
【问题描述】:

这与其他问题不同,因为它使用了另一种方法。我有以下代码,需要对其进行更改,以便根据此链接上的图 16.7 生成一个网格(填充所有行和列):http://programarcadegames.com/index.php?chapter=array_backed_grids

下面的代码产生一整行和一整列,但我不知道如何扩展它以用内置适当边距的矩形填充整个屏幕。

代码:

    """
 Create a grid with rows and colums
"""

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 = (255, 255)
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()

width=20
height=20
margin=5
# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             done = True

    # --- Game logic should go here

    # --- Screen-clearing code goes here

     # Here, we clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.

    # If you want a background image, replace this clear with blit'ing the
    # background image.
    screen.fill(BLACK)

    # --- Drawing code should go here
    #for column (that is along the x axis) in range (0 = starting position,     100=number to go up to, width+margin =step by (increment by this number)
    #adding the 255 makes it fill the entire row, as 255 is the size of the screen (both ways)
    for column in range(0+margin,255,width+margin):
        pygame.draw.rect(screen,WHITE, [column,0+margin,width,height])
        for row in range(0+margin,255,width+margin):
            pygame.draw.rect(screen,WHITE,[0+margin,row,width,height])
        #This simply draws a white rectangle to position (column)0,(row)0 and of size width(20), height(20) to the screen



    # --- 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.
pygame.quit()

【问题讨论】:

    标签: python grid pygame


    【解决方案1】:

    问题在于内部循环(for row in...), 绘制矩形的位置:

    pygame.draw.rect(screen,WHITE,[0+margin,row,width,height])
    

    请注意,x 坐标始终为0+margin, 无论当前绘制的是哪一列。所以 该代码在彼此之上绘制了 10 列。 作为一个简单的修复,将行更改为:

    pygame.draw.rect(screen,WHITE,[column,row,width,height])
    

    然后您可能会注意到,在外循环中对 draw 方法的其他调用是完全没有必要的。毕竟,内部调用现在为每列中的每一行绘制一个矩形。所以你可以将循环代码减少到:

    for column in range(0+margin, 255, width+margin):
        for row in range(0+margin, 255, height+margin):
            pygame.draw.rect(screen, WHITE, [column,row,width,height])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多