2017-01-31 1 views
0

다른 방법을 사용하기 때문에 다른 질문과 다릅니다. 다음 코드는 있고이 링크의 그림 16.7에 따라 격자 (모든 행과 열이 채워짐)가 생성되도록 변경해야합니다. http://programarcadegames.com/index.php?chapter=array_backed_gridsfor 루프를 사용하여 파이 게임에 격자 만들기

다음 코드는 전체 행과 전체 열을 생성하지만 꽤 내장 적절한 마진 사각형으로 전체 화면을 채우기 위해 확장하는 방법을 작동하지 않을 수

코드 :.

""" 
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에있다를 ...), rect가 그려지는 곳 :

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

현재 그려지는 열의 x 좌표는 항상 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]) 
관련 문제