尝试使用字典为Barnsley's Fern定义参数时遇到问题

时间:2019-07-06 10:05:10

标签: python pygame

我已经使用Python和Pygame绘制了Barnsley Fern的渲染图,并希望将所有参数都包含在字典中以便于访问,但这是行不通的。

我编写的原始代码按预期工作。我尝试对Barnsley Fern生成中的所有参数使用键为'a','b','c','d','e','f'和'p'的字典,如{{ 3}}。

当我运行代码时,窗口冻结,并且:

Traceback (most recent call last):  
  File "C:/Users/owner/Desktop/Will's Stuff/Python/Pygame/Bransley'sFernDictionary.py", line 105, in <module>
    DrawPoint(fernx,ferny)  
  File "C:/Users/owner/Desktop/Will's Stuff/Python/Pygame/Bransley'sFernDictionary.py", line 47, in DrawPoint
    pygame.gfxdraw.pixel(screen,cartesianx,cartesiany,white)
OverflowError: signed short integer is less than minimum

我期望Wikipedia文章中显示的Bransley Fern,hich是在没有字典的情况下在代码中创建的,但是绘制了一些像素后,窗口只是崩溃了。

import pygame  
import random  
import pygame.gfxdraw  
import math  
import sys  
pygame.init()  

def GeneralAlgorithm(a,b,c,d,e,f,x,y):  
    outputx = a*x + b*y + e  
    outputy = c*x + d*y + f  
    return outputx,outputy  

def GenerateNextPoint(x,y,constants):  
    randompercentage = random.randint(0,100)  
    for n in constants['p']:  
        if randompercentage <= n:  
            i = constants['p'].index(n)  
            print(i)  
            break  
    nextx, nexty = GeneralAlgorithm(constants['a'][i],constants['b'][i],constants['c'][i],constants['d'][i],constants['e'][i],constants['f'][i],x,y)  
    return nextx, nexty  

def DrawPoint(fernx,ferny):  
    cartesianx = int((fernx+2.1820+margin) * (width /(2.1820+2.6558+2*margin)))  
    cartesiany = int((ferny*-1+9.9983+margin) * (height/(9.9983+2*margin)))  
    pygame.gfxdraw.pixel(screen,cartesianx,cartesiany,white)  
    pygame.display.update()  


white = 255,255,255  
background = 20,40,100  

variables1 = {  
    'a':[0   ,0.85 ,0.2  ,-0.15],  
    'b':[0   ,0.04 ,-0.26,0.28 ],  
    'c':[0   ,-0.04,0,23 ,0.26 ],  
    'd':[0.16,0.85 ,0.22 ,0.24 ],  
    'e':[0   ,0    ,0    ,0    ],  
    'f':[0   ,1.6  ,1.6  ,0.44 ],  
    'p':[1   ,86   ,93   ,100  ]  
}  

fernx = 0  
ferny = 0  
width = int(500)  
height = int(500)  
margin = 0.5  

screen = pygame.display.set_mode((width,height))  
screen.fill(background)  
pygame.display.update()  

while True:  

    fernx,ferny = GenerateNextPoint(fernx,ferny,variables1)
    DrawPoint(fernx,ferny)

1 个答案:

答案 0 :(得分:0)

天哪,我是个傻瓜。

variables1 = {  
    'a':[0   ,0.85 ,0.2  ,-0.15],  
    'b':[0   ,0.04 ,-0.26,0.28 ],  
    'c':[0   ,-0.04,0,23 ,0.26 ],  
    'd':[0.16,0.85 ,0.22 ,0.24 ],  
    'e':[0   ,0    ,0    ,0    ],  
    'f':[0   ,1.6  ,1.6  ,0.44 ],  
    'p':[1   ,86   ,93   ,100  ]  
}  

仔细看看'c'

    'c':[0   ,-0.04,0,23 ,0.26 ],

在应该放置句点的地方,我用逗号

只需更改即可修复我的算法。

variables1 = {  
    'a':[0   ,0.85 ,0.2  ,-0.15],  
    'b':[0   ,0.04 ,-0.26,0.28 ],  
    'c':[0   ,-0.04,0.23 ,0.26 ],  
    'd':[0.16,0.85 ,0.22 ,0.24 ],  
    'e':[0   ,0    ,0    ,0    ],  
    'f':[0   ,1.6  ,1.6  ,0.44 ],  
    'p':[1   ,86   ,93   ,100  ]  
}  

答案就这么简单。

FML