问题描述
我只是在鬼混,决定对高斯分布进行可视化处理,并且以某种方式出现了该错误。我以前从未见过此错误,而最奇怪的部分是,每次循环运行时它都不会发生。这是完全随机的。有时它在循环的第一次迭代中出错,有时它根本不出错。 print()
函数在传递int时如何返回索引错误。
这是所有代码:
import math
import pygame
import os
wS = 500
n = 50
os.environ["SDL_VIDEO_WINDOW_POS"] = "%d,%d" % (5,5)
pygame.init()
window = pygame.display.set_mode((wS,wS),0)
li = [math.floor(random.gauss(350,20)) for i in range(50)]
lmax = 0
lmin = 1000
off = wS/2
leng = len(li)
for i in range(len(li)):
if li[i] > lmax:
lmax = li[i]
xV = wS/n
xV2 = wS/lmax
print(li)
def run():
global li
global xV
global lmax
global off
keys = pygame.key.get_pressed()
count = 0
p = pygame.PixelArray(window)
while not keys[pygame.K_ESCAPE] and not keys[pygame.K_SPACE] and count < (leng - 1):
print(count)
event = pygame.event.get()
keys = pygame.key.get_pressed()
x = int(xV * count)
y = int(off + ((li[count]/lmax) * off))
p[x][y] = (255,255,255)
count+=1
print("done")
pygame.display.update()
keys = pygame.key.get_pressed()
while not keys[pygame.K_ESCAPE] and not keys[pygame.K_SPACE]:
event = pygame.event.get()
keys = pygame.key.get_pressed()
run()
错误:
Traceback (most recent call last):
File "*redacted*",line 58,in <module>
run()
File "*redacted*",line 41,in run
print(count)
IndexError: array index out of range
解决方法
使用pygame.PixelArray
时,os事件被阻止。 pygame.event.get()
和pygame.key.get_pressed()
都将在像素阵列表面被锁定时返回错误。
这是更新的代码。我从循环中删除了事件。我还添加了对x,y坐标的检查,以确保它们在数组中。
import math
import pygame
import os
import random
wS = 500
n = 50
os.environ["SDL_VIDEO_WINDOW_POS"] = "%d,%d" % (5,5)
pygame.init()
window = pygame.display.set_mode((wS,wS),0)
li = [math.floor(random.gauss(350,20)) for i in range(50)]
lmax = 0
lmin = 1000
off = wS/2
leng = len(li)
for i in range(len(li)):
if li[i] > lmax:
lmax = li[i]
xV = wS/n
xV2 = wS/lmax
print(li)
def run():
global li,xV,lmax,off
count = 0
p = pygame.PixelArray(window) # lock surface for drawing
while count < (leng - 1):
x = int(xV * count)
y = int(off + ((li[count]/lmax) * off))
if x < wS and y < wS: p[x,y] = (255,255,255)
count+=1
p.close() # unlock surface
print("done")
pygame.display.update()
keys = pygame.key.get_pressed()
while not keys[pygame.K_ESCAPE] and not keys[pygame.K_SPACE]:
event = pygame.event.get()
keys = pygame.key.get_pressed()
run()