Reputation: 89
I am currently working on writing a function as part of a functions assignment. I am using python 2.7.5 and pygame. We are supposed to write a recursive function that draws lighting. I am currently having an error with my code but I do not know what it is. Here is my code:
from math import *
from pygame import *
from random import *
screen=display.set_mode((800,600))
def lightning(screen,x,y,size,ang):
if size > 5:
rang = radians(ang)
x2 = x-size*cos(rang)
y2 = y+size*sin(rang)
draw.line(screen,(200,180,0),(x,y),(x2,y2))
lightning(screen,x2,y2,size-randint(1,10),ang-randint(-20,10))
lightning(screen,x2,y2,size-randint(1,10),ang+randint(-10,30))
lightning(screen,400,0,100,randint(60,100))
running=True
while running:
for evt in event.get():
if evt.type==QUIT:
runnning=False
screen.fill((0,0,0))
lightning(screen,400,0,100,randint(60,100))
time.wait(500)
display.flip()
quit()
Currently, when I try to add another line of lightning (the "lightning(...)") it does not display any error in the shell and also does not display anything in the pygame window. When I have only one line, the lightning functions properly. I would just like to know where my error is and reasons to why it is causing the error. Any help is appreciated. Thanks.
Upvotes: 0
Views: 899
Reputation: 142651
For size=100
function ligthning()
is call 800 000 to 3 500 000 times.
If you add another line of lightning it gives you even 7 000 000 calls.
Maybe You don't see result because it works too long. Try your code for smaller size
.
My code to count ligthning()
calls.
from math import *
from pygame import *
from random import *
#---------------------------------------------------------------------
def lightning(screen, x, y, size, ang, count):
if size > 5:
rang = radians(ang)
x2 = x-size*cos(rang)
y2 = y+size*sin(rang)
draw.line(screen,(200,180,0),(x,y),(x2,y2))
count = lightning(screen,x2,y2,size-randint(1,10),ang-randint(-20,10), count)
count = lightning(screen,x2,y2,size-randint(1,10),ang+randint(-10,30), count)
return count + 1
#---------------------------------------------------------------------
screen = display.set_mode((800,600))
#lightning(screen,400, 0, 100, randint(60,100))
running = True
while running:
for evt in event.get():
if evt.type == QUIT:
running = False
elif evt.type == KEYDOWN:
if evt.key == K_ESCAPE:
running = False
screen.fill((0,0,0))
print 'count: ', lightning(screen, 400, 0, 100, randint(60,100), 0)
display.flip()
#time.wait(500)
quit()
EDIT:
Theoretically radint(1,10)
can always give 1
so you can always have lightning(...,size-1, ...)
and for size=100
it can give 2**95 calls.
2**95 = 39 614 081 257 132 168 796 771 975 168L
Upvotes: 1