×

Discussion Board

Page 2 of 4 FirstFirst 1234 LastLast
Results 16 to 30 of 47
  1. #16
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Found another source code that I had to edit so it can be executed on my 5230 which should somewhat solve one of the previous conflicts...

    Code:
    # py60snowfall.py
    
    import e32,audio,appuifw,os,sys,key_codes,time,math,random,graphics,sensor
    import sysinfo
    
    xscr=sysinfo.display_pixels()[1]
    yscr=sysinfo.display_pixels()[0]
    nflakes=240
    imgSnow=8
    WHITE=0xffffff
    BLUE=0x000080
    
    moveX=range(nflakes)
    moveY=range(nflakes)
    XX=range(nflakes)
    YY=range(nflakes)
    
    for i in range(nflakes):
    	moveY[i]=random.randint(1,24)
    	dir=random.choice([-1,1])
    	moveX[i]=dir*random.randint(1,3)
    	XX[i]=random.randint(0,xscr)
    	YY[i]=random.randint(0,yscr)
    
    def falling():
    	global moveX,moveY,XX,YY
    	img.clear(BLUE)
    	for i in range(nflakes):
    		dir=random.choice([-1,1])
    		moveX[i]=dir*moveX[i]
    		XX[i]=XX[i]+moveX[i]
    		YY[i]=YY[i]+moveY[i]
    		if((XX[i]>xscr)or(XX[i]<0)):
    			moveX[i]=-moveX[i]
    		if(YY[i]>yscr):
    			moveY[i]=random.randint(1,24)
    			dir=random.choice([-1,1])
    			moveX[i]=dir*random.randint(1,3)
    			XX[i]=random.randint(0,xscr)
    			YY[i]=dir*random.randint(1,24)
    		img.ellipse([(XX[i],YY[i]),(XX[i]+imgSnow,YY[i]+imgSnow)],WHITE,fill=WHITE)
    	canvas.blit(img,(0,0))
    	timer.after(0.1,falling)
    	draw(img)
    
    def draw(rect):
    	appuifw.e32.reset_inactivity()
    
    def exit(pos):
    	app_lock.signal()
    
    img=graphics.Image.new((xscr,yscr))
    appuifw.app.directional_pad=False
    canvas=appuifw.Canvas(redraw_callback=draw)
    appuifw.app.body=canvas
    canvas.bind(key_codes.EButton1Down,exit)
    appuifw.app.screen='full'
    
    timer=appuifw.e32.Ao_timer()
    appuifw.app.orientation='portrait'
    falling()
    e32.ao_yield()
    
    app_lock=appuifw.e32.Ao_lock()
    app_lock.wait() 
    timer.cancel()
    Last edited by all2happy; 2012-09-06 at 03:25.

  2. #17
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    I'm guessing pys60 itself is quite limited to the 5230 model as "Rage Of Thunder" and "Speedfest" are the only two I found able to prove this phone should be very capable of handling the graphics fast enough which include transparencies. Oh well... I'll just keep trying to figure much of it out

    I really took a challenge to shorten the code below as to create starting points from where the circles could better transfer it's momentum while moving at new angle, which I might add later if I'd be lucky to find an algorithm that I can reasonably comprehend, therefore the static speed of them wouldn't really slow down the animation as it has demonstrated

    Code:
    # circlestouch.py
    
    from appuifw import *
    import e32,audio,appuifw,os,sys,key_codes,time,math,random,graphics,sensor
    
    running=1
    def quit():
    	global running
    	rgb_pt=9
    	running=0
    app.exit_key_handler=quit
    
    def handle_redraw(rect):
    	pass
    
    img=None
    app.screen='large'
    app.orientation='portrait'
    app.directional_pad=False
    app.body=canvas=Canvas(redraw_callback=handle_redraw)
    img=graphics.Image.new(canvas.size)
    res_x, res_y=canvas.size
    
    class z_Object(object):
    	x=0
    	y=0
    	speed=0,0
    	rad=0
    
    r_=z_Object()
    g_=z_Object()
    b_=z_Object()
    
    objA=z_Object()
    objB=z_Object()
    
    distance=0
    
    r_.x,r_.y=(100,100)
    g_.x,g_.y=(200,200)
    b_.x,b_.y=(300,300)
    r_.speed=(-3,5)
    g_.speed=(30,16)
    b_.speed=(-7,-9)
    r_.cz=(255,0,0)
    g_.cz=(0,255,0)
    b_.cz=(0,0,255)
    r_.rad=30
    g_.rad=30
    b_.rad=30
    r_.mass=1
    g_.mass=1
    b_.mass=1
    
    rgb_pt=0
    objects=[(r_),(g_),(b_)]
    
    dx,dy=0,0
    Xs=Ys=0.0000
    skip=0
    number_of_objs=3
    stat_msg=""
    
    def dist():
    	dx=abs(objB.x-objA.x)
    	dy=abs(objB.y-objA.y)
    	distance=int(math.sqrt(dx*dx+dy*dy))
    	return distance
    
    def isColliding():
    	if dist() < (objA.rad+objB.rad):
    		return True
    	return False
    
    def z_xy(pos):
    	if pos[1]>564:
    		z_notouch(pos)
    	elif rgb_pt==1:
    		objects.remove(r_)
    		r_.x,r_.y=pos[0],pos[1]
    		objects.append(r_)
    	elif rgb_pt==2:
    		objects.remove(g_)
    		g_.x,g_.y=pos[0],pos[1]
    		objects.append(g_)
    	elif rgb_pt==3:
    		objects.remove(b_)
    		b_.x,b_.y=pos[0],pos[1]
    		objects.append(b_)
    
    def z_dot(pos):
    	global rgb_pt,hSpeed
    	if img.getpixel(pos)[0]==r_.cz:
    		hSpeed=r_.speed
    		r_.speed=0,0
    		rgb_pt=1
    	elif img.getpixel(pos)[0]==g_.cz:
    		hSpeed=g_.speed
    		g_.speed=0,0
    		rgb_pt=2
    	elif img.getpixel(pos)[0]==b_.cz:
    		hSpeed=b_.speed
    		b_.speed=0,0
    		rgb_pt=3
    
    def z_notouch(pos):
    	global r_,g_,b_,rgb_pt
    	if rgb_pt==1:
    		r_.speed=hSpeed
    	elif rgb_pt==2:
    		g_.speed=hSpeed
    	elif rgb_pt==3:
    		b_.speed=hSpeed
    	rgb_pt=0
    
    def atColor(objAB):
    	global stat_msg
    	if objAB.cz==r_.cz:
    		stat_msg+="R "
    	elif objAB.cz==g_.cz:
    		stat_msg+="G "
    	elif objAB.cz==b_.cz:
    		stat_msg+="B "
    
    def atCircle(distance):
    	global stat_msg
    	incr=0.05
    	radA=objA.rad
    	radB=objB.rad
    	rad=radA+radB
    	Xo=objA.speed[0]
    	Yo=objA.speed[1]
    	objA.x=objA.x-Xo
    	objA.y=objA.y-Yo
    	distance=dist()
    	while distance > rad+1:
    		objA.x=objA.x+(Xo*incr)
    		objA.y=objA.y+(Yo*incr)
    		dx=abs(objB.x-objA.x)
    		dy=abs(objB.y-objA.y)
    		distance=dist()
    	objA.x=int(objA.x)
    	objA.y=int(objA.y)
    	skip=1
    	draw()
    
    def draw():
    	img.clear(0x000000)
    	for objA in objects:
    		img.ellipse(((objA.x-objA.rad,objA.y-objA.rad),(objA.x+objA.rad,objA.y+objA.rad)),objA.cz,objA.cz)
    	img.text( (20,30),'X:'+unicode(r_.x)+' Y:'+unicode(r_.y),(240,0,0))
    	img.text((130,30),'X:'+unicode(g_.x)+' Y:'+unicode(g_.y),(0,240,0))
    	img.text((240,30),'X:'+unicode(b_.x)+' Y:'+unicode(b_.y),(0,0,240))
    	img.text((20,50),'* '+unicode(stat_msg),(255,255,255))
    	canvas.blit(img)
    	z_draw(img)
    
    def z_draw(rect):
    	pass
    
    canvas.bind(key_codes.EButton1Up,z_notouch)
    canvas.bind(key_codes.EButton1Down,z_dot)
    canvas.bind(key_codes.EDrag,z_xy)
    
    while running:
    	if skip==0:
    		stat_msg=" ---"
    		draw()
    	skip=0
    	for objA in objects: # attempt to move all 3 before blitting
    		objA.x+=objA.speed[0]
    		objA.y+=objA.speed[1]
    
    		if objA.x<30:
    			objA.x=30
    			objA.speed=objA.speed[0]*-1,objA.speed[1]
    		elif objA.x>330:
    			objA.x=330
    			objA.speed=objA.speed[0]*-1,objA.speed[1]
    		if objA.y<80:
    			objA.y=80
    			objA.speed=objA.speed[0],objA.speed[1]*-1
    		elif objA.y>540:
    			objA.y=540
    			objA.speed=objA.speed[0],objA.speed[1]*-1
    		for objB in objects:
    			if objA <> objB:
    				if isColliding():
    					stat_msg=""
    					atColor(objA)
    					atColor(objB)
    					atCircle(distance)
    	e32.reset_inactivity()
    	e32.ao_yield()

  3. #18
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Except for two lines in the following... the filename and...

    objA.speed,objB.speed=objB.speed,objA.speed

    ... as an added line to the "circletouch" code... the effect from the detected overlap is "only" a static exchange of the set speeds where there isn't an attempt to find what would be a realistic "mirrored" angle perpendicular of in between objA and objB. Not trying to teach anybody how to do this the proper way, but just making notes of my own progress whenever I get the chance hoping somebody might want to help me out at least be able to access this info from a different computer if ever without the correct USB drive.

    Note: The momentum of the touched circle can become lost if an overlap of it gets detected during the exchange of the set speeds.

    Code:
    # pyseudocol.py
    
    from appuifw import *
    import e32,audio,appuifw,os,sys,key_codes,time,math,random,graphics,sensor
    
    running=1
    def quit():
    	global running
    	rgb_pt=9
    	running=0
    app.exit_key_handler=quit
    
    def handle_redraw(rect):
    	pass
    
    img=None
    app.screen='large'
    app.orientation='portrait'
    app.directional_pad=False
    app.body=canvas=Canvas(redraw_callback=handle_redraw)
    img=graphics.Image.new(canvas.size)
    res_x, res_y=canvas.size
    
    class z_Object(object):
    	x=0
    	y=0
    	speed=0,0
    	rad=0
    
    r_=z_Object()
    g_=z_Object()
    b_=z_Object()
    
    objA=z_Object()
    objB=z_Object()
    
    distance=0
    
    r_.x,r_.y=(100,100)
    g_.x,g_.y=(200,200)
    b_.x,b_.y=(300,300)
    r_.speed=(-3,5)
    g_.speed=(30,16)
    b_.speed=(-7,-9)
    r_.cz=(255,0,0)
    g_.cz=(0,255,0)
    b_.cz=(0,0,255)
    r_.rad=30
    g_.rad=30
    b_.rad=30
    r_.mass=1
    g_.mass=1
    b_.mass=1
    
    rgb_pt=0
    objects=[(r_),(g_),(b_)]
    
    dx,dy=0,0
    Xs=Ys=0.0000
    skip=0
    number_of_objs=3
    stat_msg=""
    
    def dist():
    	dx=abs(objB.x-objA.x)
    	dy=abs(objB.y-objA.y)
    	distance=int(math.sqrt(dx*dx+dy*dy))
    	return distance
    
    def isColliding():
    	if dist() < (objA.rad+objB.rad):
    		return True
    	return False
    
    def z_xy(pos):
    	if pos[1]>564:
    		z_notouch(pos)
    	elif rgb_pt==1:
    		objects.remove(r_)
    		r_.x,r_.y=pos[0],pos[1]
    		objects.append(r_)
    	elif rgb_pt==2:
    		objects.remove(g_)
    		g_.x,g_.y=pos[0],pos[1]
    		objects.append(g_)
    	elif rgb_pt==3:
    		objects.remove(b_)
    		b_.x,b_.y=pos[0],pos[1]
    		objects.append(b_)
    
    def z_dot(pos):
    	global rgb_pt,hSpeed
    	if img.getpixel(pos)[0]==r_.cz:
    		hSpeed=r_.speed
    		r_.speed=0,0
    		rgb_pt=1
    	elif img.getpixel(pos)[0]==g_.cz:
    		hSpeed=g_.speed
    		g_.speed=0,0
    		rgb_pt=2
    	elif img.getpixel(pos)[0]==b_.cz:
    		hSpeed=b_.speed
    		b_.speed=0,0
    		rgb_pt=3
    
    def z_notouch(pos):
    	global r_,g_,b_,rgb_pt
    	if rgb_pt==1:
    		r_.speed=hSpeed
    	elif rgb_pt==2:
    		g_.speed=hSpeed
    	elif rgb_pt==3:
    		b_.speed=hSpeed
    	rgb_pt=0
    
    def atColor(objAB):
    	global stat_msg
    	if objAB.cz==r_.cz:
    		stat_msg+="R "
    	elif objAB.cz==g_.cz:
    		stat_msg+="G "
    	elif objAB.cz==b_.cz:
    		stat_msg+="B "
    
    def atCircle(distance):
    	global stat_msg
    	incr=0.05
    	radA=objA.rad
    	radB=objB.rad
    	rad=radA+radB
    	Xo=objA.speed[0]
    	Yo=objA.speed[1]
    	objA.speed,objB.speed=objB.speed,objA.speed
    	objA.x=objA.x-Xo
    	objA.y=objA.y-Yo
    	distance=dist()
    	while distance > rad+1:
    		objA.x=objA.x+(Xo*incr)
    		objA.y=objA.y+(Yo*incr)
    		dx=abs(objB.x-objA.x)
    		dy=abs(objB.y-objA.y)
    		distance=dist()
    	objA.x=int(objA.x)
    	objA.y=int(objA.y)
    	skip=1
    	draw()
    
    def draw():
    	img.clear(0x000000)
    	for objA in objects:
    		img.ellipse(((objA.x-objA.rad,objA.y-objA.rad),(objA.x+objA.rad,objA.y+objA.rad)),objA.cz,objA.cz)
    	img.text( (20,30),'X:'+unicode(r_.x)+' Y:'+unicode(r_.y),(240,0,0))
    	img.text((130,30),'X:'+unicode(g_.x)+' Y:'+unicode(g_.y),(0,240,0))
    	img.text((240,30),'X:'+unicode(b_.x)+' Y:'+unicode(b_.y),(0,0,240))
    	img.text((20,50),'* '+unicode(stat_msg),(255,255,255))
    	canvas.blit(img)
    	z_draw(img)
    
    def z_draw(rect):
    	pass
    
    canvas.bind(key_codes.EButton1Up,z_notouch)
    canvas.bind(key_codes.EButton1Down,z_dot)
    canvas.bind(key_codes.EDrag,z_xy)
    
    while running:
    	if skip==0:
    		stat_msg=" ---"
    		draw()
    	skip=0
    	for objA in objects: # attempt to move all 3 before blitting
    		objA.x+=objA.speed[0]
    		objA.y+=objA.speed[1]
    
    		if objA.x<30:
    			objA.x=30
    			objA.speed=objA.speed[0]*-1,objA.speed[1]
    		elif objA.x>330:
    			objA.x=330
    			objA.speed=objA.speed[0]*-1,objA.speed[1]
    		if objA.y<80:
    			objA.y=80
    			objA.speed=objA.speed[0],objA.speed[1]*-1
    		elif objA.y>540:
    			objA.y=540
    			objA.speed=objA.speed[0],objA.speed[1]*-1
    		for objB in objects:
    			if objA <> objB:
    				if isColliding():
    					stat_msg=""
    					atColor(objA)
    					atColor(objB)
    					atCircle(distance)
    	e32.reset_inactivity()
    	e32.ao_yield()

  4. #19
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Attarisk*... which is actually "At-A-Risk"... was one of my own favorite of games that I made many years ago for the PalmOS, now missing quite a few lovely features so it took a very short while to write the code again. Just thought to share this one also, especially in being for two player unlike the others I've submitted. Feels like there's hardly anybody coding at this raw level of python... but perhaps sometime soon... when I can find a game engine to get much more work done.

    Code:
    ### attarisk.py
    
    from appuifw import *
    import e32,audio,appuifw,os,sys,key_codes,time,math,random,graphics,sensor
    
    xm=360 ### <<< ref
    ym=560 ### <<< ref
    
    def quit():
    	global gameRunning
    	msg=(u"Click OK if you really want to exit")
    	res=appuifw.query(msg,"query")
    	if(res == 1): 
    		gameRunning=0
    		print "ended"
    app.exit_key_handler=quit
    
    def draw(rect):
    	pass
    
    img=None
    app.screen='large'
    app.orientation='portrait'
    app.directional_pad=False
    app.body=canvas=Canvas(redraw_callback=draw)
    img=graphics.Image.new(canvas.size)
    res_x,res_y=canvas.size
    timer=e32.Ao_timer()
    COLOR_BLACK=(0,0,0)
    COLOR_GRAY=(128,128,128)
    COLOR_WHITE=(255,255,255)
    COLOR_GREEN=(0,204,0)
    COLOR_YELLOW=(255,255,0)
    img.clear(COLOR_BLACK)
    canvas.blit(img)
    timer=e32.Ao_timer()
    
    active=0
    bullet_1=' *****'
    bullet_2=''
    score=0
    
    InPlay=[[COLOR_GREEN,0],[COLOR_YELLOW,0]]
    
    timespan=1
    
    def tap(pos):
    	global timespan,abc
    	bb=time.time()
    	abc=cc=bb-aa
    	img.rectangle((340,0,xm,ym),fill=COLOR_BLACK)
    	if cc > 1:
    		cc=1
    	yy=ym*(1-cc)+20
    	img.rectangle((340,yy,360,ym),fill=InPlay[active][0])
    	canvas.blit(img)
    	timespan=0
    
    canvas.bind(key_codes.EButton1Down,tap)
    
    #===============================================================================
    # LOAD SCORING
    #===============================================================================
    
    dir_x=u"e:\\data\\Python\\attarisk.txt"
    if not os.path.isfile(dir_x):
    	f=open(dir_x,'w')
    	f.write('0')
    	f.close
    	
    f=open(dir_x,'r')
    db_x=f.readline()
    f.close		
    
    hscor_db=db_x
    print hscor_db
    
    hscor_db=int(hscor_db)
    
    #===============================================================================
    # EXECUTION LOOP
    #===============================================================================
    score=0
    
    gameRunning=0
    res=appuifw.query(u"**** ATTARISK ****\n\n        Start by pressing OK","query")
    aa=time.time()
    if(res == 1): gameRunning=1
    
    while(gameRunning):
    	rounds=4
    	turns=rounds*2
    	for round in xrange(turns):
    		img.clear(COLOR_BLACK)
    		img.text((20,30),'PLAYER 1'+unicode(bullet_1),font='title',fill=COLOR_GREEN)
    		img.text((20,60),unicode(InPlay[0][1]),font='title',fill=COLOR_WHITE)
    		img.text((20,120),'PLAYER 2'+unicode(bullet_2),font='title',fill=COLOR_YELLOW)
    		img.text((20,150),unicode(InPlay[1][1]),font='title',fill=COLOR_WHITE)
    		img.text((20,250),'ROUND '+unicode(int(round/2)+1)+' OF 4',font='title',fill=COLOR_WHITE)
    		img.text((20,330),u'HIGHSCORE ---',font='title',fill=COLOR_GRAY)
    		img.text((20,360),unicode(hscor_db),font='title',fill=COLOR_GRAY)
    		y2=ym
    		while timespan:
    			if gameRunning == 0:
    				break
    			bb=time.time()
    			cc=bb-aa
    			if cc < 0.2:
    				img.rectangle((340,0,xm,ym),fill=COLOR_BLACK)
    				y2=ym
    			if cc > 1:
    				aa=time.time()
    				cc=1
    			yy=ym*(1-cc)+20
    			img.rectangle((340,yy,360,y2),fill=InPlay[active][0])
    			y2=yy
    			canvas.blit(img)
    			e32.ao_yield() # bottom of _running_loop_
    		ka=pow(10,int(abc*0.25*10))
    		abc*=0.97
    		if abc > 1:
    			abc*=10
    		score=int(abc*100*ka)
    		
    		InPlay[active][1]+=score
    		if active == 0:
    			active=1
    		else:
    			active=0
    		msg=("\n\nSwitch Over For Player "+unicode(active+1)+" ...")
    		if round == turns-1:
    			msg=''
    		img.rectangle((0,0,200,180),fill=COLOR_BLACK)
    		img.text((20,30),'PLAYER 1'+unicode(bullet_1),font='title',fill=COLOR_GREEN)
    		img.text((20,60),unicode(InPlay[0][1]),font='title',fill=COLOR_WHITE)
    		img.text((20,120),'PLAYER 2'+unicode(bullet_2),font='title',fill=COLOR_YELLOW)
    		img.text((20,150),unicode(InPlay[1][1]),font='title',fill=COLOR_WHITE)
    		bullet_1,bullet_2=bullet_2,bullet_1
    		canvas.blit(img)
    		timer.after(2)
    		timer.cancel()
    		if gameRunning == 0:
    			break
    		else:
    			res=appuifw.query(u"You Scored "+unicode(score)+msg,"query")
    		timespan=1
    		aa=time.time()
    	if gameRunning == 0:
    		break
    	else:
    		img.rectangle((0,0,200,180),fill=COLOR_BLACK)
    		img.text((20,30),u'PLAYER 1',font='title',fill=COLOR_WHITE)
    		img.text((20,60),unicode(InPlay[0][1]),font='title',fill=COLOR_WHITE)
    		img.text((20,120),u'PLAYER 2',font='title',fill=COLOR_WHITE)
    		img.text((20,150),unicode(InPlay[1][1]),font='title',fill=COLOR_WHITE)
    		img.text((20,330),u'HIGHSCORE ---',font='title',fill=COLOR_WHITE)
    		img.text((20,360),unicode(hscor_db),font='title',fill=COLOR_WHITE)
    		timer.after(0.5)
    		timer.cancel()
    		if InPlay[0][1] > InPlay[1][1]:
    			player='One'
    			score=InPlay[0][1]
    		else:
    			player='Two'
    			score=InPlay[1][1]
    		appuifw.query(u'Player '+player+' Is The Champion !!!',"query")
    		if score > hscor_db:
    			appuifw.query(u"Congratulations !!!\nYou Have Set A New Rank!" ,"query")
    			msg=(u'*** %s ***\nPrev Highscore: %s\n\nPlay again?"' %(score,hscor_db))
    			hscor_db=score
    			f=open(dir_x,'w')
    			f.write('%s' %(hscor_db))
    			f.close()
    			print hscor_db
    		else:
    			msg=(u"Score: "+unicode(score)+"\n\nPlay again?")
    
    		res=appuifw.query(msg,"query")
    		if(res != 1): 
    			gameRunning=0
    			print "ended"
    			
    		else:
    			img.clear(COLOR_BLACK)
    			canvas.blit(img)
    			timespan=1
    			InPlay=[[COLOR_GREEN,0],[COLOR_YELLOW,0]]
    			aa=time.time()
    			score=0
    
    #sound_bell.close()
    e32.ao_yield()
    appuifw.app.body=None
    Last edited by all2happy; 2012-10-07 at 02:47. Reason: Was shown a slight miscalculation and suggested how to optimize such graphic output relays

  5. #20
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Had about 30 minutes to get some more info from a very busy friend who also believes my 5230 seems rather too "permission" limited, but figured it's quite flexible enough to create a variety a great projects. Anyhow... I was given the following snippet that should help a beginner like me troubleshoot codes way more proficiently in Python at it's minimal.

    Code:
    # linedebug.py
    
    def tr(msg=None):
    	import inspect
    	trk = str(inspect.currentframe().f_back.f_lineno)
    	# in case there is no trk_on variable
    	try:
    		if trk_on == 1 or trk_on == True:
    			print 'Line Number: ' + trk
    			if msg!=None: #+++ or msg!='': <- didn't work ???
    				if msg!='':
    					if msg!=1:
    						print str(msg)
    					else:
    						print "***" ### represents a checkmark
    	except:
    			pass
    
    if __name__ == '__main__':
    	pass
    
    # * snippet as it is, should print --
    
    tr()				#
    tr("hello #1") 			#
    trk_on = 1 
    tr()				# Line Number: 27
    tr("hello #2")			# Line Number: 28
    				# hello #2
    trk_on = 2 
    tr()				# 
    tr("hello #3")			# 
    trk_on = True 
    hello="hello #4" 
    tr(hello)			# Line Number: 35
    				# hello #4
    hello=5 
    tr('')				# Line Number: 38
    tr(hello)			# Line Number: 39
    				# 5
    tr(1) 				# Line Number: 41
    				# ***
    Was told the original had a bit more to offer, so I tried to figure out what sort of other features could there be in regards and add a few, then realized it would be really nice to have it not lose the previous relay from being in loops.

    Code:
    # example attempt...
    def tr(msg=None,trkxtrk=None):
    # with or without returns trkxtrk to None
    try:
        if trk!=trkxtrk:
            try:
                ...
                    trkxtrk=trk
            except:
                pass
    except:
        pass
    Oh... and just in case...
    TAG: code tracking, print lineno, code tracing, print backtrace, print current line, debug line, stack tracing, print script line
    Last edited by all2happy; 2012-10-01 at 19:07. Reason: Went to improve the original code a bit more

  6. #21
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Thought to take a look at what has been posted throughout this forum and saw an excellent snippet post by Bogdan Galiceanu, who I hereby thank thee for this contribution provided with a few modifications.

    Code:
    import appuifw, e32, graphics, os
    
    #Define the exit function
    def quit():app_lock.signal()
    appuifw.app.exit_key_handler=quit
    
    appuifw.app.orientation='portrait' # portrait, landscape or None
    appuifw.app.screen='large' # large, full, or normal
    appuifw.app.directional_pad=False # hides directional pad
    
    canvas=appuifw.Canvas()
    appuifw.app.body=canvas
    
    PYTHON_ROOT=u"E:\\data\\Python\\"
    
    img1=graphics.Image.open(PYTHON_ROOT+u"a.png")
    img2=graphics.Image.open(PYTHON_ROOT+u"b.png")
    canvas.clear(0x000000) # black background
    # blits are instantaneous
    canvas.blit(img1, (0,0), (20,100))
    canvas.blit(img2, (0,0), (200,300))
    
    app_lock=e32.Ao_lock()
    app_lock.wait()
    Last edited by all2happy; 2012-10-05 at 05:55. Reason: img2=graphics.Image.open("C:\\b.jpg") was img1

  7. #22
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Found this game somewhere on the internet and had just made a few changes for it to fit in the 5230 properly and went to correct an unexpected float error by making the f variable an integer --

    Code:
    # UfoZapper.py
    import key_codes, appuifw, e32, graphics, random
    
    MAX_UFO_SIZE = 50
    MAX_UFOS = 7
    UFO_TIME = 100.0
    
    PAD_W = 40
    PAD_H = 15
    PAD_COLOR = (12, 116, 204)
    PAD_SPEED = 7
    LASER_COLOR = (255, 0, 204)
    TIME = 1000
    
    def handle_redraw(rect):
            global shoot, sleep, ufos, timer
            buf.clear((0, 0, 0))
            buf.rectangle((pad_x, H - PAD_H, pad_x + PAD_W, H),\
                    fill = PAD_COLOR)
    
            if shoot:
                    x = pad_x + PAD_W / 2
                    buf.line((x, H - PAD_H, x, 0),\
                            width = 4, outline = LASER_COLOR)
                    shoot = False
                    sleep = 0.1
                    check_hits(x)
            else:
                    sleep = 0.01
            
            for x, y, s, t, hit in ufos:
                    f = 1.0 - (timer - t) / UFO_TIME
                    if hit:
                            c = (255, 0, 0)
                    else:
                            c = (0, int(f * 255), 0)
                    buf.ellipse((x, y, x + s, y + s), fill = c)
    
            buf.text((10, 40), u"%d" % score,
                    fill = LASER_COLOR, font = "title")
            
            buf.text((W - 70, 40), u"%d" % (TIME - timer),
                    fill = LASER_COLOR, font = "title")
            
            canvas.blit(buf)
    
    def check_hits(laser_x):
            global ufos, score
            i = 0
            ok_ufos = []
            for x, y, s, t, hit in ufos:
                    if laser_x > x and laser_x < x + s:
                            ok_ufos.append((x, y, s, t, True))
                            score += MAX_UFO_SIZE*5 - (s - 1)
                    else:
                            ok_ufos.append((x, y, s, t, False))
                            score -= 10
            ufos = ok_ufos
    
    def update_ufos():
            global ufos, timer
            ok_ufos = []
            for x, y, s, t, hit in ufos:
                    if not hit and timer < t + UFO_TIME:
                            ok_ufos.append((x, y, s, t, False))
            ufos = ok_ufos
            
            if len(ufos) < MAX_UFOS:
                    s = random.randint(10, MAX_UFO_SIZE)
                    x = random.randint(0, W - s)
                    y = random.randint(0, H - PAD_H * 3)
                    t = random.randint(0, UFO_TIME)
                    ufos.append((x, y, s, timer + t, False))
    
    
    def handle_event(event):
            global direction, shoot
            if event['keycode'] == key_codes.EKeyLeftArrow:
                    direction = -PAD_SPEED
            elif event['keycode'] == key_codes.EKeyRightArrow:
                    direction = PAD_SPEED
            elif event['keycode'] == key_codes.EKeySelect or event['keycode'] == key_codes.EKeyUpArrow:
                    shoot = True
    
    def quit():
            global timer
            timer = TIME
    
    ufos = []
    shoot = False
    direction = pad_x = score = timer = 0
    appuifw.app.exit_key_handler = quit
    appuifw.app.screen = 'large'
    canvas = appuifw.Canvas(event_callback = handle_event,\
                            redraw_callback = handle_redraw)
    W, H = canvas.size
    H=(H/4*3)+5
    buf = graphics.Image.new((W, H))
    appuifw.app.body = canvas
    
    while timer < TIME:
            pad_x += direction
            pad_x = min(pad_x, W - PAD_W)
            pad_x = max(pad_x, 0)
    
            update_ufos()
            handle_redraw((W, H))
            e32.ao_sleep(sleep)
            timer += 1
    
    print "Score: %d!" % score

  8. #23
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    A previous code of this was submitted by somebody else...

    Code:
    # randomcircles.py
    
    # Modules
    import e32, time
    from random import randint, choice
    from appuifw import *
     
    # Define exit function
    def quit():
    		App_lock.signal()
    app.exit_key_handler = quit
    
    def draw(rect):
    	pass
    
     
    app.directional_pad = False
    app.screen = 'large' # Screen size set to 'large'
    c = Canvas(redraw_callback=draw)
    app.body = c
    c=Canvas(redraw_callback=draw)
    
    COLOR_BLACK=(0,0,0)
    COLOR_GRAY=(128,128,128)
    COLOR_WHITE=(255,255,255)
    COLOR_YELLOW=(255,255,0)
    COLOR_RED=(255,0,0)
    COLOR_ORANGE=(255,165,0)
    COLOR_GREEN=(0,255,0)
    COLOR_BLUE=(0,0,255)
    COLOR_CYAN=(0,255,255)
    COLOR_PURPLE=(128,0,128)
    COLOR_BROWN=(139,69,19)
    
    colors = [COLOR_RED, COLOR_ORANGE, COLOR_YELLOW, COLOR_GREEN, COLOR_BLUE, COLOR_PURPLE]
    
    # Function which draws circle with given radius at given co-ordinate
    def circle(x,y,radius=5, outline=0, fill=COLOR_BLACK, width=1):
    	c.ellipse((x-radius, y-radius, x+radius, y+radius), outline, fill, width)
    
    def rand_circle():
    	c.clear()
    	for i in range(4):
    		circle(randint(0,360), randint(100,500), randint(30,120), fill=choice(colors))
    	timer.after(0.25,rand_circle)
    	e32.ao_yield()
    
    timer=e32.Ao_timer()
    
    def draw(rect):
    	pass
    
    def exit(pos):
    	app_lock.signal()
    
    e32.ao_yield()
    
    rand_circle()
    App_lock = e32.Ao_lock()
    App_lock.wait()	# Wait for exit event
    
    timer.cancel()

  9. #24
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    -- Pylattyplus.py [1 of 2]

    Thought the name would be quite fitting as much of it were from several examples. It's still a work in progress, especially to add my Pytemple.py which is a template module, then a Pydemos.py module.

    Code:
    ### Pylattyplus.py -- An On-The-Go Basic Editor For The Pys60
    
    # modules
    from graphics import *
    from sensor import *
    import os,appuifw,e32,sensor,sys,graphics,codecs,sysinfo,time,re,dir_iter,key_codes,math,random
    
    trk_on=1
    img=None
    
    main_loop=1
    settxt=0
    
    # [[][][]] are Nested Lists
    # (()()()) are Nested Tuples 
    def handle_redraw(rect):
    	if img: ### Skips only at first pass as 'None'
    		canvas.blit(img)
    def gfx_on(mode): # actually took me a long while to figure out how to come up with this
    	global canvas,txt
    	if mode == 1:
    		appuifw.app.body=canvas
    	else:
    		txt=appuifw.Text()
    		appuifw.app.body=txt
    
    appuifw.app.directional_pad=False
    txt=appuifw.Text()
    appuifw.app.body=txt
    appuifw.app.title=u"Pylattyplus Pys60 Editor"
    canvas=appuifw.Canvas(redraw_callback=handle_redraw)
    appuifw.app.body=canvas
    img=Image.new(canvas.size)
    timer=e32.Ao_timer()
    gfx_on(0)
    
    intro=u"\nThank You for taking an interest in one of my first attempts at creating a very basic pys60 Editor that is a work in progress.\n\n\
    		A Hobby Project by\n\
    		Kirk Lawrence\n\n"
    
    txt.clear()
    txt.set(unicode(intro))
    
    process=u'\n\n\nThis might take quite a while to process...'
    
    COLOR_BLACK=(0,0,0)
    COLOR_GRAY=(128,128,128)
    COLOR_WHITE=(255,255,255)
    COLOR_GREEN=(0,204,0)
    COLOR_YELLOW=(255,255,0)
    COLOR_RED=(255,0,0)
    COLOR_BLOODRED=(102,0,0)
    
    class Movement(object):
    	x=0
    	y=0
    
    slide=0.97654321
    vx=Movement()
    vy=Movement()
    mdet=0
    
    # screen boundary
    vx,vy=0,0
    xm,ym=0,60
    view_xx,view_yy=1208,4105
    accel=0,0
    exitmark=2
    
    def exit():
    	global exitmark
    	exitmark=1
    appuifw.app.exit_key_handler=exit
    
    def z_quit():
    	global main_loop
    	quit_x=appuifw.query(u'To Confirm Exiting... Select The OK','query')
    	if quit_x == True:
    		main_loop=0
    
    def z_info():
    	appuifw.note(u'ZZZ','info')
    
    def z_msg(msg):
    	appuifw.note(unicode(msg),'info')
    
    def z_xy(pos):
    	global xm,ym,vx,vy,accel
    	aa=abs(pos[0])-xm
    	bb=abs(pos[1])-ym
    	vx,vy=(vx+aa,vy+bb)
    	if vx < -border[0]:
    		vx=-border[0]
    	elif vx > 0:
    		vx=0
    	if vy < -border[1]:
    		vy=-border[1]
    	elif vy > 0:
    		vy=0
    	if not ym-vy < 40 or not ym-vy > 40*(maxline+1):
    		accel=0,bb
    	if abs(accel[1]) < 5:
    		accel=0,0
    	xm,ym=pos[0],pos[1]
    
    def z_dot(pos):
    	global xm,ym,accel,mdet
    	mdet=1
    	xm,ym=pos[0],pos[1]
    	accel=0,0
    
    def z_notouch(pos):
    	global mdet
    	mdet=0
    
    canvas.bind(key_codes.EButton1Up,z_notouch)
    canvas.bind(key_codes.EButton1Down,z_dot)
    canvas.bind(key_codes.EDrag,z_xy)
    
    def filewr(selected):
    	gfx_on(0)
    	txt.clear()
    	txt.set(unicode(process))
    	appuifw.app.title=u'Sel:' + selected;
    	f=open('e:\\data\\python\\' + selected,'r+')
    	f2=f.read()
    	f.close()
    	txt.clear()
    	f2=unicode(f2)
    	txt.set(unicode(f2))
    	TEMP_FILE='e:\\data\\python\\temp.py'
    	f=open(unicode(TEMP_FILE),'w')
    	f.write('e:\\data\\python\\' + selected)
    	f.close()
    	tr(1)
    
    def flist():
    	global settxt
    	filenames=[]
    	for filename in os.listdir('e:\data\python'):
    		if filename.endswith('.py'):
    			filename=filename.decode('utf-8')
    			filenames.append(filename)
    	for filename in os.listdir('c:\data\python'):
    		if filename.endswith('.py'):
    			filename=filename.decode('utf-8')
    			filenames.append(filename)
    	filenames.reverse()
    	index=appuifw.selection_list(filenames,1)
    	tr()
    	m=settxt
    	try:
    		if appuifw.query(u'Open ' + filenames[index] + '?','query') == True:
    			settxt=1
    			selected=filenames[index]
    			go(selected)
    	except:
    		settxt=m
    
    def opentxt():
    	global settxt
    	filenames=[]
    	for filename in os.listdir('e:\data\python'):
    		if filename.endswith('.txt'):
    			filename=filename.decode('utf-8')
    			filenames.append(filename)
    	filenames.reverse()
    	index=appuifw.selection_list(filenames,1)
    	tr()
    	m=settxt
    	try:
    		if appuifw.query(u'Open ' + filenames[index] + '?','query') == True:
    			settxt=1
    			selected=filenames[index]
    			go(selected)
    	except:
    		settxt=m
    
    def sel2canv():
    	tr("sel2canv")
    	selected=linesoftxt[inline]
    	gfx_on(0)
    	exitmark=0
    	txt.clear()
    	txt.set(unicode(selected))
    
    def canv2sel():
    	global settxt
    	txt=appuifw.app.body.get()
    	txt=txt.replace(u'\u2029','\n').encode('utf8') # fix newline characters
    	txt=txt.replace("\t","     ") ###ZZZ substitute whitespace
    	linesoftxt.pop(inline)
    	linesoftxt.insert(inline,txt)
    	gfx_on(1)
    	z_mainmenu()
    	
    def z_save2db(TEMP_FILE):
    	linesoftxt2=linesoftxt[1:maxline]
    	try:
    		f=open(unicode(TEMP_FILE),'w')
    		for txt in linesoftxt2:
    			#txt=txt.replace("     ","\t") ###ZZZ substitute whitespace
    			txt=txt+"\n"
    			f.write(txt)
    		f.close()
    		appuifw.note(u'Saved','conf')
    	except:
    		appuifw.note(u'Unable To Save!','error')
    
    def z_save_01():
    	TEMP_FILE=u'c:\\data\\python\\000_000_000_temp.py'
    	z_save2db(TEMP_FILE)
    	
    def z_save_02():
    	TEMP_FILE=u'c:\\data\\python\\100_000_000_temp.py'
    	z_save2db(TEMP_FILE)
    	
    def z_saveas():
    	newname=appuifw.query(u'Enter The New Filename','text')
    	TEMP_FILE=unicode('e:\\data\\python\\'+newname+'.py')
    	z_save2db(TEMP_FILE)
    
    def z_fileopen01():
    	CONFIG_DIR='c:\\data\python'
    	CONFIG_FILE=os.path.join(CONFIG_DIR,'000_000_000_temp.py')
    	appuifw.app.title=u'Sel: Temp 01';
    	z_db2canvas(CONFIG_FILE)
    
    def z_fileopen02():
    	CONFIG_DIR='c:\\data\python'
    	CONFIG_FILE=os.path.join(CONFIG_DIR,'100_000_000_temp.py')
    	appuifw.app.title=u'Sel: Temp 02';
    	z_db2canvas(CONFIG_FILE)
    
    def z_template():
    	gfx_on(0)
    	txt.set(unicode(process))
    	CONFIG_FILE=os.path.join(CONFIG_DIR,'pyup_lib.py')
    	f=open(unicode(CONFIG_FILE),'r')
    	z_libr=unicode(f.read())
    	f.close
    	appuifw.app.title=u'New: Template';
    	txt.clear()
    	txt.set(unicode(z_libr))
    
    def z_db2canvas(CONFIG_FILE):
    	gfx_on(0)
    	txt.clear()
    	txt.set(unicode(process))
    	f=open(unicode(CONFIG_FILE),'r')
    	f2=unicode(f.read())
    	f.close
    
    def canv2list(): ###ZZZ will reference body.get elsewhere
    	global linesoftxt
    	linesoftxt=[]
    	txt=appuifw.app.body.get()
    	txt=txt.replace(u'\u2029', '\n')
    	txt=txt.decode('utf8') 
    	linesoftxt.append(u'**** HEAD OF ENTRY ****')
    	for z_line in txt.split('\n'):
    		linesoftxt.append(z_line)
    	linesoftxt.append(u'**** LAST OF ENTRY ****')
    	gfx_on(1)
    	img.clear(COLOR_BLOODRED)
    	canvas.blit(img)
    	tr(1)
    
    def z_find(reverse=False,beginning=False):
    	'''find text within a document'''
    	string=appuifw.query(u'Find text:','text',unicode(last_find))
    	saved_string=string[:]
    	if (string != None):
    		try:
    			text=text.get()
    			if settings.config['casesensitive'][0] == 'no':
    				text=text.lower()
    				string=string.lower()
    			if beginning:
    				if reverse:
    					cur_pos=text.rindex(string)
    				else:
    					cur_pos=text.index(string)
    			else:
    				if reverse:
    					cur_pos=text.rindex(string,0,(text.get_pos() -1))
    				else:
    					cur_pos=text.index(string,(text.get_pos() +1))
    			text.set_pos(cur_pos)
    		except:
    			appuifw.note(u'Search string not found.','info')
    			last_find=saved_string
    
    def z_replace():
    	'''find and replace all instances of a given string'''
    	replace=appuifw.multi_query(u'Replace :',u'with : ')
    	if replace != None:
    		text=text.get()
    		cur_pos=text.get_pos()
    		text.set(text.replace(replace[0],replace[1]))
    		text.set_pos(cur_pos + text[0:cur_pos].count(replace[0])*(len(replace[1])-len(replace[0])))
    		appuifw.note(unicode(text.count(replace[0])) + ' instances replaced')
    
    def z_line():
    	global ym,vy,inline
    	'''move the cursor to a particular line no.'''
    	inline=appuifw.query(u'Line number:','number',maxline)
    	tr((int(ym/40)*40,int(vy/40)*40))
    	if (inline == None):
    		pass
    	elif (inline <= maxline):
    		if inline < 4:
    			vy=0
    			ym=inline*40+20
    			tr((ym,vy))
    		else:
    			ym=120
    			vy=inline*40*-1+ym
    			tr((ym,vy))
    		if settxt == 0:
    			sel2canv()
    	else:
    		appuifw.note(u'Line does not exist!','info')
    
    def _rename():
    	'''rename a file/folder'''
    	path=dir_iter.entry(browse.current())
    	filename=unicode(os.path.basename(path))
    	if appuifw.query(u'Rename ' + filename + ' ?','query'):
    		newname=appuifw.query(u'Rename ' + filename,'text',filename)
    		if newname != None:
    			try:
    				os.rename(path,os.path.dirname(path) + str(newname))
    				appuifw.note(u'File renamed','info')
    			except:
    				appuifw.note(u'Error renaming file!','error')
    
    def z_font(): ### ???
    	'''change the display font'''
    	fonts = appuifw.available_fonts()
    	fonts.sort()
    	index=appuifw.selection_list(choices=fonts,search_field=1)
    	fontsize=appuifw.query(u'Font Size: 9 to 36','number',16)
    	if fontsize < 9 or fontsize > 36:
    		fonsize = 16
    	if index != None:
    		txt.font=(unicode(fonts[index]),fontsize)
    	else:
    		pass
    
    def z_mainmenu():
    	appuifw.app.menu=[(u'Open/Save',
    						((u'Open File...',z_canv2list),
    						(u'Open TXT',opentxt),
    						(u'Save 01',z_save_01),
    						(u'Save 02',z_save_02),
    						(u'Save As...',z_saveas),
    						(u'Open Temp 1',z_fileopen01),
    						(u'Open Temp 2',z_fileopen02),
    						(u'Open Template',z_template))),
    						(u'Edit Script',z_writemenu),
    						(u'Change Font',z_font),
    						(u'Info',z_info),
    						(u'Quit',z_quit)]
    
    def z_canv2list():
    	flist() # sets to def go
    
    def go(selected):
    	global accel,vx,vy,ym
    	filewr(selected)
    	canv2list()
    	ym=60
    	accel=0,0
    	vx,vy=0,0	
    
    def z_writemenu(): ### ZZZ a whole lot more to be added here
    	appuifw.app.menu=[(u'Select Line...',z_line),
    						(u'*** Main Menu',z_mainmenu),
    						(u'Quit',z_quit)]
    
    CONFIG_DIR='e:\\data\python'
    
    def tr(msg=None):
    	import inspect
    	trk = str(inspect.currentframe().f_back.f_lineno)
    	# in case there is no trk_on variable
    	try:
    		if trk_on == 1 or trk_on == True:
    			print 'Line Number: ' + trk
    			if msg!=None: # or msg!='': <- didn't work ???
    				if msg!='':
    					if msg!=1:
    						print str(msg)
    					else:
    						print "***"
    	except:
    			pass
    
    if __name__ == '__main__':
    	pass
    Last edited by all2happy; 2012-10-10 at 19:03.

  10. #25
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    -- Pylattyplus.py [2 of 2]

    Code:
    z_mainmenu()
    
    while main_loop:
    	while settxt and main_loop:
    		border=700,0
    		yy=0
    		maxline=len(linesoftxt)-2
    		if ym-vy < 40:
    			ym=60-vy
    		elif ym-vy > 40*(maxline+1):
    			ym=40*(maxline)+vy+20
    		inline=int(abs(ym-vy))/40
    		topline=int(abs(0-vy))/40
    		btmline=int(abs(440-vy))/40-1
    		if topline < 1:
    			topline=1
    		elif btmline > maxline:
    			btmline=maxline
    		img.clear(COLOR_BLOODRED)
    		#linesoftxt2=linesoftxt[topline-1:btmline+1] ### ZZZ
    		for txt in linesoftxt:
    			txt=txt.replace(u'\t', '     ') ###ZZZ substitute whitespace
    			y2=yy+vy+40
    			if y2 > -40 and y2 < 480: # display range
    				if ym > y2-1 and ym < y2+40 and ym < maxline*40:
    					img.rectangle((0,y2,360,y2+40),fill=COLOR_RED)
    				img.text((12+vx,y2-8),unicode(txt),font="title",fill=COLOR_WHITE)
    			else:
    				pass
    			yy+=40
    		border=border[0],border[1]+yy-440
    		img.rectangle((0,442,360,500),fill=COLOR_BLACK)
    		img.text((204,462),unicode("max: "+str(maxline)),COLOR_WHITE)
    		img.text((204,482),unicode("line: "+str(topline)+" to "+str(btmline)),COLOR_WHITE)
    		img.text((20,482),unicode("highlighted: "+str(inline)),COLOR_WHITE)
    		canvas.blit(img)
    		y2=vy
    		if mdet == 0:
    			accel=0,accel[1]*slide
    			vy+=accel[1]
    		if vy < -border[1]:
    			vy=-border[1]
    		elif vy > 0:
    			vy=0
    		ym+=abs(y2)-abs(vy)
    		if exitmark == 1:
    			settxt=0
    			exitmark=0
    			z_writemenu()
    			sel2canv()
    		e32.ao_yield()
    	if exitmark == 1:
    		settxt=1
    		exitmark=0
    		canv2sel()
    	
    	e32.ao_yield()

  11. #26
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Found this in Mobile_Python.pdf which I haven't yet tried which seems less intrusive as opposed to a well known pixel by pixel method...

    Image Masks –

    When you copy one image to another using the blit() function, the shape of the source image is rectangular by default. In some cases, this is not desirable and you would like to mask out certain parts of the source
    image. For this purpose, you need a black and white mask image with the visible parts painted in white. Then, you can load and use the mask to copy only the visible parts, defined by the mask, mask img, of the source image, src img, to the canvas as follows:

    mask_img = Image.new(size = (50, 50), mode = '1')
    mask_img.load('e:\\Images\\mask_img.png')
    src_img = graphics.Image.open('e:\\Images\\orig_img.png')
    canvas.blit(src_img, target=(0,0), source=(0,0), mask = mask_img)

    The parameter mode = "1" specifies that the new image, mask img, has only two colors, black and white. This mode is required for masks.

  12. #27
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Just learned to blit a screenshot right after making a Text Mode output. The Option to refer png images might soon be added.
    Instead of only have 5 choices, each might soon vary in accordance. The txt format at the moment will not apparently accept any
    quotation marks... which has sadly taken up most of my free time already, which is no longer a top priority. I haven't yet taken a
    course to learn how to code and has hardly found the time to do a proper structuring, so please forgive me for whatever wrong
    there is. To me, all criticisms are welcomed, because especially as a community... we can get a whole lot more accomplished.

    Code:
    # MultipleChoice.py
    
    import os,appuifw,e32,sensor,sys,graphics,codecs,sysinfo,time,re,dir_iter,key_codes,math,random,audio
    
    EXT_DIR='e:\\data\\python\\'
    sys.path.append(EXT_DIR)
    
    img=None
    
    def exit_key_handler():
    	global main_loop
    	main_loop=0
    appuifw.app.exit_key_handler=exit_key_handler
    
    def handle_redraw(rect):
    	if img: ### Skips only at first pass as 'None'
    		canvas.blit(img)
    def gfx_on(mode): # actually took me a long while to figure out how to come up with this
    	global canvas,txt
    	if mode == 1:
    		appuifw.app.body=canvas
    	else:
    		txt=appuifw.Text()
    		appuifw.app.body=txt
    
    def pad():
    	txt.font=("dense",4)
    	txt.add(u'\n\n')
    	txt.font=("dense",24)
    
    appuifw.app.directional_pad=False
    appuifw.app.orientation='portrait'
    appuifw.app.screen='large'
    txt=appuifw.Text()
    appuifw.app.body=txt
    canvas=appuifw.Canvas(redraw_callback=handle_redraw)
    appuifw.app.body=canvas
    img=graphics.Image.new(canvas.size)
    timer=e32.Ao_timer()
    gfx_on(0)
    
    txt.clear()
    txt.style=(appuifw.STYLE_BOLD)
    COLOR=txt.color
    
    intro=u'\n\nThis is a Multiple Choice application which is still very much in the works that I decided to write as a mean to study in hopes of becoming, in a few years from now, an expert mobile developer.\n\n -- Kirk Lawrence'
    
    txt.font=("dense",32)
    txt.add(intro)
    capture = graphics.screenshot()
    img.blit(capture, target=(0,0))
    gfx_on(1)
    canvas.blit(img)
    
    COLOR_BLACK=(0,0,0)
    COLOR_GRAY=(128,128,128)
    COLOR_WHITE=(255,255,255)
    COLOR_GREEN=(0,204,0)
    COLOR_YELLOW=(255,255,0)
    COLOR_RED=(255,0,0)
    COLOR_ORANGE=(255,165,0)
    COLOR_BLOODRED=(102,0,0)
    
    def z_tdown(pos):
    	global xm,ym
    	xm,ym=pos[0],pos[1]
    
    def z_notouch(pos):
    	pass
    
    canvas.bind(key_codes.EButton1Up,z_notouch)
    canvas.bind(key_codes.EButton1Down,z_tdown)
    
    def opt_1():
    	global opt
    	opt=0
    def opt_2():
    	global opt
    	opt=1
    def opt_3():
    	global opt
    	opt=2
    def opt_4():
    	global opt
    	opt=3
    def opt_5():
    	global opt
    	opt=4
    
    opt= -1
    
    flashcard=0
    init_loop=0
    main_loop=1
    
    def open_x():
    	global init_loop
    	init_loop=1
    
    options5=[(u"A",opt_1),(u"B",opt_2),(u"C",opt_3),(u"D",opt_4),(u"E",opt_5)]
    appuifw.app.menu=[(u"Select A File",open_x)]
    mainmenu=appuifw.app.menu
    
    '''
    appuifw.note(u"Cancelled",'info')
    appuifw.app.menu=mainmenu
    exit=True
    txt.clear()
    '''
    
    while main_loop:
    	if init_loop == 1:
    		init_loop = 0
    		score=0
    		opt= -1
    		filenames=[]
    		for filename in os.listdir(EXT_DIR):
    			if filename.endswith('_multi.txt'):
    				filename=filename.decode('utf-8')
    				filename=filename.replace(u'_multi', '')
    				filename=filename.replace(u'.txt', '')
    				filename=filename.replace(u'_', ' ')
    				filenames.append(filename)
    		filenames.reverse()
    		index=appuifw.popup_menu(filenames,u'Select Quiz')
    		YorN=False
    		try:
    			YorN=appuifw.query(u'Open '+filenames[index]+'?','query')
    		except:
    			appuifw.note(u"Cancelled",'info')
    		if YorN == True:
    			selected=filenames[index]
    			f=open(unicode(EXT_DIR+selected+'_multi.txt'),'r+')
    			appuifw.app.title=unicode(selected)
    			lines=f.read()
    			f.close()
    			try:
    				lines=unicode(lines)
    				flashcard=1
    			except:
    				appuifw.note(u"Data Is Incompatible","error")
    			QA=[]
    			QuesAns=[]
    			k=1
    			for line in lines.split('\n'):
    				if line == '':
    					k=0
    				else:
    					QA.append(line)
    					if k > 5:
    						QuesAns.append(QA)
    						QA=[]
    						k=0				
    				k+=1
    			qCount=str(len(QuesAns))
    			random.shuffle(QuesAns)
    			cc=0
    
    	if flashcard:
    		opt = -1
    		if cc > int(qCount)-1:
    			gfx_on(0)
    			txt.clear()
    			appuifw.app.menu=mainmenu
    			msg=u'You Scored %s Out Of %s' % (score, qCount)
    			appuifw.note(msg,'info')
    			txt.font=("dense",32)
    			txt.add(msg)
    			b=time.time()
    			msg2=u'the elapsed time is: %d' %(b-a)
    			appuifw.note(msg2,'info')
    			capture = graphics.screenshot()
    			img.blit(capture, target=(0,0))
    			gfx_on(1)
    			canvas.blit(img)
    		else:
    			k=QuesAns[cc]
    			gfx_on(0)
    			txt.clear()
    			txt.font=("dense",32)
    			txt.add(u"Question "+str(cc+1)+" out of "+qCount)
    			pad()
    			corr=k[1] # The Correct Answer
    			txt.add(k[0]) # Questions
    			k.pop(0)
    			a=time.time()
    			### random.shuffle(k) # not needed anymore
    			k=sorted(k)
    			txt.color=COLOR_ORANGE
    			for line in k: # Choices
    				pad()
    				pad()
    				txt.add(unicode(line))
    			txt.color=COLOR
    			capture = graphics.screenshot()
    			img.blit(capture, target=(0,0))
    			gfx_on(1)
    			canvas.blit(img)
    			appuifw.app.menu=options5
    		flashcard=0
    		cc+=1
    	if opt!= -1:
    		if k[opt] == corr:
    			score+=1
    			appuifw.note(u"That Is Correct","conf")
    		else:
    			appuifw.note(u"Sorry... Wrong Answer","error")
    		flashcard=1
    
    	e32.ao_yield()

  13. #28
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    # To be saved as... PythonTest_multi.txt for the MultipleChoice.py application

    Having searched around the internet, there were several MCQ I had personally selected, but could also be incorrect from trying to make this completion. Oh yeah... and I should also allow a broader scope to place minimal examples of code that might even need the modules to be shown.

    Code:
    A GUI:
    d.) Both a and b.
    a.) uses buttons, menus, and icons.
    b.) should be easy for a user to manipulate.
    c.) stands for Graphic Use Interaction.
    e.) All are correct.
    
    What does IDE stand for? 
    a.) Integrated Development Environment
    b.) Integrated Design Environmente 
    c.) Immersive Development Environment
    d.) Immersive Debugging Environment
    e.) None are correct.
    
    For which task does the IDE provide multiple ways to accomplish the task? 
    e.) All are correct. 
    a.) Putting a control on the form.
    b.) Running the program.
    c.) Activating the property window for a control.
    d.) Both a and b.
    
    Which task is accomplished in the Code editor? 
    c.) Adding event procedures to the form.
    a.) Adding forms to the project.
    b.) Adding controls to the form.
    d.) Both a and b.
    e.) All are correct.
    
    Which is NOT a feature of a GUI that makes learning a program easy for users? 
    d.) Commands
    a.) Online help
    b.) WYSIWYG formatting
    c.) Dialog boxes
    e.) Icons
    
    Which of the following is correct about Python?
    e.) All are correct.
    a.) Python is a byte-code compiled programming language.
    b.) Python uses a virtual machine to run machine-abstracted instructions.
    c.) Python is an object-oriented language.
    d.) Python is a declarative programming language.
    
    An object is composed of: 
    e.) All are correct.
    a.) properties.
    b.) methods.
    c.) events.
    d.) Both a and b.
    
    Which statement about objects is true? 
    d.) One class can create many objects.
    a.) One object is used to create one class. 
    b.) One class is used to create one object.
    c.) One object can create many classes.
    e.) There is no relationship between objects and classes.
    
    The exit_key_handler property belongs to which object? 
    b.) Form
    a.) Button
    c.) Label
    d.) TextBox
    e.) Timer
    
    A click event procedure stud for the label control can be created by: 
    e.) All are correct.
    a.) selecting the object and event from the code editor window's drop-down boxes.
    b.) typing the code in the code editor window.
    c.) by double clicking the control.
    d.) Both a and b.
    
    In event-driven programming an event is generated by: 
    e.) All are correct. 
    a.) the system.
    b.) a user's action.
    c.) the program itself.
    d.) Both a and b.
    
    The Tick event is found only in which object? 
    e.) Timer
    a.) Form
    b.) Button 
    c.) TextBox
    d.) Label
    
    The Activated event is found only in which object?
    a.) Form
    b.) Button 
    c.) TextBox
    d.) Label
    e.) Timer
    
    The Rnd statement will generate a(n): 
    e.) decimal value between 0.0 and up to 1.0, but NOT including 1.0.
    a.) decimal value between 0.01 and 1.00.
    b.) integer value between 0.01 and 1.00.
    c.) decimal value between 0.0 and 1.0.
    d.) integer value between 0.0 and 1.0.
    
    Which is NOT an integer data type?
    a.) Single
    b.) Byte
    c.) Short
    d.) Integer
    e.) Long
    
    Which is a numeric data type? 
    d.) Both a and b.
    a.) Floating point
    b.) Integer
    c.) Boolean
    e.) All are correct. 
    
    The name of a constant: 
    d.) does NOT have to begin with a letter and can be either upper or lower case.
    a.) must both begin with a letter and be all upper case.
    b.) does NOT have to begin with a letter but must be all upper case.
    c.) must begin with a letter but can be upper or lower case.
    e.) None are correct.
    
    The left side of an assignment statement will hold: 
    d.) Both a and b.
    a.) a variable.
    b.) an object property.
    c.) an expression.
    e.) All are correct.
    
    The right side of an assignment statement will hold: 
    c.) an expression.
    a.) a variable.
    b.) an object property.
    d.) Both a and b.
    e.) All are correct.
    
    The Items property of a ComboBox:
    a.) is a collection of items.
    b.) is the same as the Items property of a ListBox.
    c.) contains methods and properties.
    d.) Both a and b.
    e.) All are correct. 
    
    A Loop is an iterative statement because it: 
    b.) runs the same block of statements repeatedly.
    a.) selects a block of statements to run.
    c.) selects a block of statements and runs it repeatedly.
    d.) selects a block of statements and runs it a specified number of times.
    e.) All are correct. 
    
    An Exception is another name for a: 
    c.) runtime error.
    a.) compile error.
    b.) logic error. 
    d.) superficial error.
    e.) syntax error.
    
    The methodology where code is broken into small, logical procedures is called: 
    d.) modular programming.
    a.) event-driven programming.
    b.) functional programming.
    c.) granular programming.
    e.) procedural programming.
    
    Why should a variable NOT be declared as a module variable? 
    e.) All are correct.
    a.) It prevents a procedure from being self contained.
    b.) It makes it easier to document the code.
    c.) Local variable names can be reused in other procedures.
    d.) Both a and b. 
    
    Which method will arrange the elements of an array in alphabetical order?
    e.) Sorted
    a.) Arrange
    b.) Assemble
    c.) Order
    d.) Seq
    
    Where is a single element of data stored?
    a.) Field
    b.) Record
    c.) Table
    d.) Both a and b.
    e.) All are correct.
    
    Which of the following is part of an object? 
    d.) Both a and b.
    a.) Methods
    b.) Properties
    c.) Instances
    e.) All are correct. 
    
    Properties are used to represent: 
    c.) data. 
    a.) actions.
    b.) classes.
    d.) events.
    e.) instances.
    
    Methods are used to represent: 
    a.) actions.
    b.) classes.
    c.) data.
    d.) events.
    e.) instances.
    
    A method in a class is: 
    d.) Both a and b.
    a.) a sub procedure.
    b.) a function.
    c.) an event.
    e.) All are correct.
    Last edited by all2happy; 2012-11-06 at 18:51.

  14. #29
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Re: Maybe We Should Have A Pys60 Game Engine

    Hmmm... seems like nobody is reading any of these newer posts in thread... or not interested in them... or just not willing to respond... or don't like me for some reason unknown to me, but never-the-less... being all too happy to make and and share my progress, I'll just continue on.

    There was an interactive Galactic Screensaver that really inspire me to replicate several decades ago, but I wasn't quite sure how to achieve that desired effect until after having studied the XYZircle.py and py60snowfall.py code. It's still not quite what I aimed for, but at least it's a start. I should be able to make a whole lot of various games from this.

    Code:
    # 3D Interstellar.py
    
    import e32,audio,appuifw,os,sys,key_codes,time,math,random,graphics,sensor
    import sysinfo
    
    xm,ym,zm=(0,0,0)
    
    xscr=sysinfo.display_pixels()[0]
    yscr=sysinfo.display_pixels()[1]
    ofstars=600
    sz=1
    WHITE=0xffffff
    BLACK=0x000000
    
    spanse = 700 # 700 should be the minimum
    xv=xscr/2
    yv=yscr/2
    slow = 800
    
    moveX=range(ofstars)
    moveY=range(ofstars)
    moveZ=range(ofstars)
    XX=range(ofstars)
    YY=range(ofstars)
    ZZ=range(ofstars)
    
    for i in range(ofstars):
    	XX[i]=random.randint(0,spanse)
    	YY[i]=random.randint(0,spanse)
    	ZZ[i]=random.randint(0,slow)
    
    def sector():
    	global moveX,moveY,moveZ,XX,YY,ZZ
    	img.clear(BLACK)
    	for i in range(ofstars):
    		XX[i]+=int(xm*3.2)
    		YY[i]+=int(ym*3.2)
    		ZZ[i]+=int(zm*3.2)
    		if(XX[i]>spanse):
    			XX[i] -= spanse
    		elif(XX[i]<0):
    			XX[i] += spanse
    		if(YY[i]>spanse):
    			YY[i] -= spanse
    		elif(YY[i]<0):
    			YY[i] += spanse
    		if(ZZ[i]>slow):
    			ZZ[i] -= slow
    			XX[i]=random.randint(0,spanse)
    			YY[i]=random.randint(0,spanse)
    		elif(ZZ[i]<0):
    			ZZ[i] += slow
    			XX[i]=random.randint(0,spanse)
    			YY[i]=random.randint(0,spanse)
    
    		### start of main 3D effect
    		sz=ZZ[i]*0.07
    		px=XX[i]+((XX[i]-xv)*(ZZ[i]/100.0))
    		py=YY[i]+((YY[i]-yv)*(ZZ[i]/100.0))
    
    		### line ended of main 3D effect
    
    		img.ellipse([(px,py),(px+sz,py+sz)],WHITE,fill=WHITE)
    	img.text((20,40),'X:'+unicode(xm),(WHITE))
    	img.text((20,80),'Y:'+unicode(ym),(WHITE))
    	canvas.blit(img,(0,0))
    	timer.after(0.02,sector)
    	draw(img)
    
    def draw(rect):
    	appuifw.e32.reset_inactivity()
    
    def exit(pos):
    	app_lock.signal()
    
    def redraw():
    	global xm,ym,zm
    	ym,xm,zm=(sens.x/5,sens.y/5,sens.z/5)
    	'''
    	ym+=40
    	if ym > 25:
    		ym = 25
    	if ym < -25:
    		ym = -25
    	'''
    	draw(canvas.size)
    
    '''
    def forLight():
    	appuifw.e32.reset_inactivity()
    	timer.after(10,forLight)
    
    timer=appuifw.e32.Ao_timer()
    forLight()
    '''
    
    img=graphics.Image.new((xscr,yscr))
    appuifw.app.directional_pad=False
    canvas=appuifw.Canvas(redraw_callback=draw)
    appuifw.app.body=canvas
    canvas.bind(key_codes.EButton1Down,exit)
    sens=sensor.AccelerometerXYZAxisData(data_filter=sensor.LowPassFilter())
    sens.set_callback(data_callback=redraw)
    sens.start_listening()
    appuifw.app.screen='full'
    
    timer=appuifw.e32.Ao_timer()
    appuifw.app.orientation='landscape'
    sector()
    e32.ao_yield()
    
    app_lock=appuifw.e32.Ao_lock()
    app_lock.wait()
    sens.stop_listening()
    timer.cancel()
    Last edited by all2happy; 2012-11-10 at 21:43.

  15. #30
    Super Contributor
    Join Date
    Jan 2009
    Location
    Melbourne, Australia
    Posts
    2,578

    Re: Maybe We Should Have A Pys60 Game Engine

    Hi all2happy
    Quote Originally Posted by all2happy View Post
    Hmmm... seems like nobody is reading any of these newer posts in thread... or not interested in them... or just not willing to respond... or don't like me for some reason unknown to me, but never-the-less... being all too happy to make and and share my progress, I'll just continue on.
    A few years ago this site had a very active Python on Symbian community - some of the (current) moderators even joined together to write (and print) the book Python_on_Symbian (originally hosted on the Symbian Foundation wiki).

    The problem is that Symbian is no longer a high priority platform for Nokia, and even if it was, Python is not a priority runtime on Symbian. In essence we're now at the point that Python on Symbian can still be used for prototyping and is quite fun to play with, but it no longer has sufficient momentum to support a community. Hence no real responses to your messages. Sorry!

    In any case, we certainly don't dislike you :-) I wish you the very best with your development efforts. If you move to Windows Phone or Series 40 I think you'll find a much bigger community to be part of.

    Regards
    Hamish

Similar Threads

  1. 3D Game engine for MIDP/M3G
    By mcwo in forum Mobile Java General
    Replies: 8
    Last Post: 2010-05-28, 03:24
  2. HandleKeyEventL Game Engine
    By TheCyclops in forum Symbian
    Replies: 4
    Last Post: 2003-08-06, 09:45
  3. Game engine coming along nicely...
    By aehrath in forum Symbian
    Replies: 0
    Last Post: 2003-07-08, 18:53
  4. Replies: 0
    Last Post: 2003-07-02, 17:44

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •