2014-02-13 2 views
0

배열 색인에서 점 좌표를 호출하여 Pygame에서 선을 그립니다. 그러나이 오류 반환 : 여기Python에서 배열을 사용하여 선을 생성합니다.

Traceback (most recent call last): File "C:/Python33/Games/lineTest.py", line 33, in pygame.draw.line(windowSurface,BLACK,(0,0), (0, list[j]), 3) IndexError: list index out of range

을 내 코드 : 사람이 오류가 점점 과거에 대한 해결책이있을 수 있습니다 경우

import pygame, sys, random, time 
from pygame.locals import * 

# sets up pygame 
pygame.init() 

# sets up the window 
windowSurface = pygame.display.set_mode((500, 500), 0, 32) 
pygame.display.set_caption('Line Test') 

# sets up the colors 
BLACK = (0, 0, 0) 
WHITE = (255, 255, 255) 

# draw white background 
windowSurface.fill(WHITE) 

print('Please enter a number:') 
number = input() 

# generate random numbers for array 
i = 0 
list = [] 
while int(number) > i: 
    i = i+1 
    x = random.randint(1, 500) 
    list.append(x) 

# draw lines 
j = 0 
while int(number) > j: 
    j = j+1 
    pygame.draw.line(windowSurface,BLACK,(0,0), (0, list[j]), 3) 

# Draw the window to the screen 
pygame.display.update() 

궁금 해서요?

+1

스왑 'J = J + 1'과 'pygame.draw.line (windowSurface, BLACK, (0,0), (0,리스트 [J]) (3))'while 루프 대신 http://docs.python.org/2/tutorial/controlflow.html#the-range-function을 살펴보십시오. – Bonzo

+0

굉장, 그 두 라인을 전환했습니다. 고맙습니다! – Carm

답변

5

당신은 당신이 목록의 끝을지나 항목 하나의 인덱스에 액세스하려고 귀하의 카운터 i에 하나 전에 j이 그들을 사용하여 추가 할 수 있습니다. 또한

:

  1. 자신의 변수 list를 호출하지 마십시오;
  2. for 루프를 사용하십시오.

예 :

lst = [] 
for n in range(number): 
    lst.append(...) # or google "python list comprehension" 

for item in lst: 
    # use item 
+1

for 루프를 사용하는 경우 +1. 2014 년에는 어느 누구도 오프라인 오류를 처리하지 않아야합니다. – stewSquared

관련 문제