在Python Pygame中使用数组生成行

Car*_*arm 0 python arrays pygame lines

我试图通过调用数组索引中的点坐标来在Pygame中绘制线条.但是,这会返回错误:

回溯(最近一次调用最后一次):文件"C:/Python33/Games/lineTest.py",第33行,在pygame.draw.line中(windowSurface,BLACK,(0,0),(0,list [j]) ,3)IndexError:列表索引超出范围

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

我想知道是否有人可能有解决方案来解决这个错误?

jon*_*rpe 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
Run Code Online (Sandbox Code Playgroud)