2017-01-31 2 views
0

Это отличается от других вопросов, поскольку использует другой метод. У меня есть следующий код и его нужно изменить, чтобы он создавал сетку (все строки и столбцы заполнялись), как показано на рисунке 16.7 по этой ссылке: http://programarcadegames.com/index.php?chapter=array_backed_gridsСоздание сетки в pygame для петель

Следующий код дает полную строку и полный столбец, но Я не могу достаточно выяснить, как продлить его, чтобы заполнить весь экран прямоугольниками с соответствующим запасом, построенных в

код:.

""" 
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() 

ответ

0

проблема лежит во внутреннем цикле (for row in ...), , где прямоугольник рисуется с помощью:

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

Обратите внимание, что х всегда согласовываем не 0+margin, независимо от того, какой столбец в настоящее время обращается. Итак, код рисует 10 столбцов друг на друга. Как легко исправить, изменить линию:

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

Вы могли бы тогда заметить, что другой вызов метода вытяжки во внешнем контуре является совершенно ненужным. В конце концов, внутренний вызов теперь рисует прямоугольник для каждой строки в каждом столбце. Поэтому вы можете уменьшить код цикла до:

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]) 
Смежные вопросы