×

Discussion Board

Page 1 of 3 123 LastLast
Results 1 to 15 of 47

Hybrid View

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    36

    Maybe We Should Have A Pys60 Game Engine

    I'm still rather new to programming aside from the ancient GWBASICS... however, the best way I've learned to structure my own unique games was mostly from extremely simplifing pyWuzzler which has many of the key functions -- animating image transparency, XY tilt, sound effects, ball collisions, has an algorithm to slow the ball movement and gravity to send the ball back to the player section, keep the background light on while playing, ends the game after the set amount of time, records the high score into an encrypted db, and whatever else there is. The original version would not work on my 5230, so an affiliate took a little bit of his spare time to make several changes that got it executing properly.

    Just for now, perhaps we can have a similar gaming code structure with every kind of basic function where even in the Options will readily show "Start Game", "Sound Off/On", "Settings", "About"... editing can be easy as drawing boundary lines, boxes or ellipses... each section in the recommended order of flow.

    Hopefully enough to rather quickly layout multiplayer 3D tunnel racing games

  2. #2
    Nokia Developer Expert
    Join Date
    Sep 2011
    Posts
    382

    Re: Maybe We Should Have A Pys60 Game Engine

    Excellent idea!

    /0

  3. #3
    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()

  4. #4
    Registered User
    Join Date
    Feb 2005
    Location
    Belgium (Europe)
    Posts
    1,352

    Re: Maybe We Should Have A Pys60 Game Engine

    Hello all2happy,

    pygame has been ported to PyS60 since many years !

    It's a special PyS60 version for creating games and PyBox2D for 2D physics library.

    BR
    Cyke64

    link : http://code.google.com/p/pygame-symbian-s60/
    pys60 1.4.5 and 2.0.0, pygame, PyS60 CE on E90 and 5800 !

    Find my pys60 extension modules on cyke64.googlepages.com

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

    Re: Maybe We Should Have A Pys60 Game Engine

    Quote Originally Posted by cyke64 View Post
    Hello all2happy,

    pygame has been ported to PyS60 since many years !

    It's a special PyS60 version for creating games and PyBox2D for 2D physics library.

    BR
    Cyke64

    link : http://code.google.com/p/pygame-symbian-s60/
    Ahhh, okay... please forgive me then and thank you. Knowing myself, it's probably because I got all too excited to start programming right aways that I somehow didn't notice.

    So far, I did figure out how to very much change several shared source codes to make 2 games that don't seem to already be available... the first utilizes the tilt motion sensor in which the player can look at the x:y co-ordinates to determine where the random seeded 10x10p target is within a 1200x1200p boundary scoring from 0-2400 per frame the closer to the centre or 5000 when collision detected... the second game requires either touching in correspondance the 'yes' or 'no' sections if the 'word' matches its color, although there came about a glitch from the image mask affiliated right after the initialization process, both given a one minute time limit... and that I would like to share these code completely with the png and wav files. Most likely there's still plenty of poor editing on my part in not having a generic base structure, so do feel free to constructively criticize.

    I haven't yet made the effort to learn how to generate SIS standalones, but already drew a shiny 72x72p BMP icon.

    Had only been able to test them through my Nokia 5230 soon to also be tried on the 500 model once I clear up enough space off my laptop, especially to install the Window version Symbian/Nokia emulator.

    Will definately give pygame-symbian-s60 and the OpenGL a go... but I noticed the 'simple cube' after an approximate half hour uninterupted execution... will reveal an error.

  6. #6
    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

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

    Re: Maybe We Should Have A Pys60 Game Engine

    Hello Marcelo and again to Hamish, I certainly do appreciate both of your messages. Had been quite worried that is was over for Pythonic coding the Nokia mobiles... although rather recently curious about how much more dynamic HTML5 is and if it's far easier to learn. Speaking of which, seen an awesome Nokia interactive slide show that I believe YouTube should adopt this feature so that tutorials can look way more professional and load up a whole lot quicker... at least for mobiles. Tried to find a few on how to make a standalone or SISX a long time ago, but got no actual results.

    Went about to download QT, then saw somebody post that the full commercial version was 1'500 USD per year, which will take me way too long to save up for, especially to soon start in college...to discover if mobile programming should be my pursuit, but I'm still not sure being unable to complete my personal samples of every code and other challenges like direct pixel allotments to provide fast enough image overlap color transitions of maybe 32 bytes in an selective ASCII format --

    ASCZ = r'0123456789abc...'
    RGBZ = red01,red02,red03,red04,red05...]
    Explosion = [r'...',r'...',r'...'...]
    Bkgrnd = [r'...',r'...',r'...',r'...'...]
    def fade(x,y,topobj,btmobj):
    ...

    Read that Qt will no longer be the future of Nokia and wonder which will compile python codes. Is there a list of quality YouTube videos I can look at to comparitively see which direction I should go?

  8. #8
    Registered User
    Join Date
    Jan 2009
    Location
    Melbourne, Australia
    Posts
    2,571

    Re: Maybe We Should Have A Pys60 Game Engine

    Hi all2happy

    Qt can be licensed for free under LPGL. The full commercial license does cost 1500 but that really isn't needed by almost anyone. You do need windows to run the SDK though (remote compiling is no longer supported). It is a great platform for Symbian and N9 devices, and also for desktop. I've heard it can also be used on Android, but not tried it. It is however true that this is not a future platform for Nokia (at least at this point) because it does not run on Windows Phone or Series 40, which are our main platforms. Neither of these support Python either.

    In terms of recommendations, it depends on where you want to go.
    * Series 40 supports Java, which is not too dissimilar to C# or the programming framework used on WP (and Android if you were to move away from Nokia). It also has "Web Apps" - which rely on your HTML and CSS skills, but this is very much intended for accessing existing web based services and is not ideal for high performance graphical software.
    * Windows Phone allows development in C# and HTML, and with WP8 also C++ (a windows flavour of APIs though) and HTML5.

    As a developer I think you need to accept that you will need to be multi-lingual. If I was starting right now I'd learn the web technologies first to get the greatest "breadth" of where I could program - ie this works with minor mods on most platforms. I'd then probably learn Java ME as this has the next greatest market penetration and is better for games etc than web technologies currently. Everyone will have their own opinion on this though!

    Good luck

    H
    Last edited by hamishwillee; 2012-11-15 at 01:04.

  9. #9
    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()

  10. #10
    Registered User
    Join Date
    Dec 2005
    Posts
    49

    Re: Maybe We Should Have A Pys60 Game Engine

    pygame is not working with me on symbian, giving import errors for joystick, cdrom and mouse LOL

    i tried to fix those imports by creating dummy joystick, cdrom and mouse but still no fun..

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

    Re: Maybe We Should Have A Pys60 Game Engine

    Quote Originally Posted by anees042 View Post
    pygame is not working with me on symbian, giving import errors for joystick, cdrom and mouse LOL

    i tried to fix those imports by creating dummy joystick, cdrom and mouse but still no fun..
    Oh, haha... I couldn't even get pygame.sisx or PyBox2D to load for some unknown reason, so I might have to start developing another template type game engine which would be so easy to make almost entirely through the phone in hardly ever needing to type any code. At the moment, I want to learn how to get image objects to fade and suspect it's related to the masking method.

    Code:
    ### modeswitch.py
    
    import e32, audio, appuifw, graphics, os, sys, key_codes, time, math, random
    
    app_lock=e32.Ao_lock()
    appuifw.app.orientation='landscape'
    appuifw.app.directional_pad=False
    appuifw.app.screen='large' # 'large' for testing
    appuifw.app.title=u"Text and Graphic Mode Toggle"
    
    btn_t,btn_b=270,360
    btn01=(20,btn_t,120,btn_b) # YES
    btn02=(120,btn_t,220,btn_b) # NO
    btn03=(520,0,640,69) # quit button
    
    def e_callback(event):
    	global select,btn_t
    	if event['type'] == key_codes.EButton1Down:
    		if event['pos'][1] > btn_t:
    			if event['pos'][0] > 20 and event['pos'][0] < 120:
    				select=0 # means NO
    			elif event['pos'][0] > 120 and event['pos'][0] < 220:
    				select=1 # means YES
    		elif event['pos'][0] > 520 and event['pos'][1] < 69:
    			quit()
    
    def quit():
    	gfx_on(0)
    appuifw.app.exit_key_handler=quit
    
    canvas=img=None
    
    def cb_resize(aSize=(0,0,0,0)):
    	global img
    	img=graphics.Image.new((640,360)) ### ZZZ to be canvas.size instead of 640:360
    
    def handle_redraw(rect):
    	if img: ### Skips only at first pass as "None"
    		canvas.blit(img)
    canvas=appuifw.Canvas(resize_callback=cb_resize,
    		event_callback=e_callback,redraw_callback=handle_redraw)
    appuifw.app.body=canvas
    txt=appuifw.Text()
    appuifw.app.body=txt
    
    txt.clear()
    txt.set(u"'Select Option' > 'Graphic Mode' to activate the graphics mode \
    and then the green rectangle at the top left should switch it right back to \
    this unaltered 'Text Mode'\n\n")
    
    COLOR_BLACK=(0,0,0)
    COLOR_WHITE=(255,255,255)
    COLOR_GRAYLIGHT=(211,211,211)
    COLOR_GRAY=(128,128,128)
    COLOR_GRAYDARK=(169,169,169)
    COLOR_REDDARK=(169,0,0)
    COLOR_RED=(255,0,0)
    COLOR_ORANGE=(255,165,0)
    COLOR_YELLOW=(255,255,0)
    COLOR_GREEN=(0,128,0)
    COLOR_BLUE=(0,0,255)
    COLOR_CYAN=(0,255,255)
    COLOR_PURPLE=(128,0,128)
    COLOR_DARKBLUE=(0,0,139)
    COLOR_DARKGREEN=(0,100,0)
    COLOR_DEEPPINK=(255,20,147)
    COLOR_PINK=(255,192,203)
    COLOR_INDIGO=(75,0,130)
    COLOR_LIGHTBLUE=(173,216,230)
    COLOR_LIME=(0,255,0)
    COLOR_OLIVE=(107,142,35)
    
    COLOR_TAN=(210,180,140)
    COLOR_BROWN=(139,69,19)
    COLOR_GOLD=(255,215,0)
    COLOR_SILVER=(192,192,192)
    
    def circle(x,y,radius=5,outline=0,fill=0xffff00,width=1):
    	c.ellipse((x-radius,y-radius,x+radius,y+radius),outline,fill,width)
    
    PYTHON_ROOT=u"e:\\data\\Python\\000misc\\"
    BkgdImage=graphics.Image.open(PYTHON_ROOT+u"640x360img.png")
    
    def gfx_on(mode):
    	if mode == 1:
    		appuifw.app.screen='full'
    		appuifw.app.body=canvas
    	if mode == 0:
    		appuifw.app.screen='large'
    		appuifw.app.body=txt
    
    def star5pt((x,y),size,outline=None,fill=None,width=1):
    	s=size
    	img.polygon(((0+x,0.7*s+y),(0.75*s+x,0.7*s+y),(1*s+x,0+y),(1.25*s+x,0.7*s+y),(2*s+x,0.7*s+y),
    			(1.4*s+x,1.15*s+y),(1.65*s+x,1.95*s+y),(1*s+x,1.45*s+y),(0.35*s+x,1.95*s+y),(0.6*s+x,1.15*s+y)),
    			outline,fill,width)
    
    def exit():
    	app_lock.signal()
    def graphics_mode():
    	gfx_on(1)
    	img.blit(BkgdImage,target=(0,0))
    	img.rectangle((btn03),outline=None,fill=COLOR_GREEN)
    	img.line((250,250,480,320),COLOR_PURPLE,width=5)
    	star5pt((390,5),60,fill=COLOR_GOLD)
    	img.point((140,50),COLOR_BLACK,width=80)
    	img.ellipse((520,210,620,340),outline=COLOR_DARKBLUE,fill=COLOR_CYAN,width=2)
    	img.line(((40,275),(200,152),(174,259),(320,80),(374,240),(400,152),(569,274)),
    			outline=COLOR_ORANGE,width=2)
    	img.pieslice((200,20,320,80),0,320,width=1,outline=COLOR_BROWN,fill=COLOR_TAN)
    	img.arc((60,180,180,300),320,90,width=10,outline=COLOR_DARKBLUE) # ??? *
    	### * re: arc/pieslice -- for bypassing the zero degree mark... 90 degrees as to what?
    	### may have to write a method to correct this
    	img.text((100,320),u"Sample Text On Canvas",fill=(255,0,0),font='title')
    	img.text((536,30),u"Touch Here")
    	img.text((536,50),u"To Switch")
    	handle_redraw(())
    appuifw.app.menu=[(u"Graphic On",graphics_mode),(u"Exit",exit)]
    
    app_lock.wait()
    Last edited by all2happy; 2012-07-07 at 01:03.

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

    Re: Maybe We Should Have A Pys60 Game Engine

    Code:
    # rgbtouch2move.py
    
    import appuifw, graphics, key_codes, math
    
    r_dot=(100,100)
    g_dot=(200,200)
    b_dot=(300,300)
    cr=(255,0,0)
    cg=(0,255,0)
    cb=(0,0,255)
    overlap=''
    rgb_pt=0
    layer=[(r_dot, cr), (g_dot, cg), (b_dot, cb)]
    vr=60
    
    def z_draw(rect):
    	global img
    	img=graphics.Image.new(canvas.size)
    	img.clear(0x000000)
    	img.ellipse(((layer[2][0][0]-vr,layer[2][0][1]-vr),(layer[2][0][0]+vr,layer[2][0][1]+vr)),layer[2][1],layer[2][1])
    	img.ellipse(((layer[1][0][0]-vr,layer[1][0][1]-vr),(layer[1][0][0]+vr,layer[1][0][1]+vr)),layer[1][1],layer[1][1])
    	img.ellipse(((layer[0][0][0]-vr,layer[0][0][1]-vr),(layer[0][0][0]+vr,layer[0][0][1]+vr)),layer[0][1],layer[0][1])
    	img.text( (20,30),'X:'+unicode(r_dot[0])+' Y:'+unicode(r_dot[1]),(240,0,0))
    	img.text((130,30),'X:'+unicode(g_dot[0])+' Y:'+unicode(g_dot[1]),(0,240,0))
    	img.text((240,30),'X:'+unicode(b_dot[0])+' Y:'+unicode(b_dot[1]),(0,0,240))
    	img.text( (20,50),unicode(overlap),(0xFFFFFF))
    	canvas.blit(img,(0,0))
    
    def backlight():
    	appuifw.e32.reset_inactivity()
    	timer.after(20,backlight)
    
    def z_xy(pos):
    	global r_dot, g_dot, b_dot, prev_xy, overlap, layer
    	if rgb_pt==1:
    		prev_xy=r_dot
    		layer.remove((r_dot, cr))
    		r_dot=pos
    		layer.insert(0,(pos, cr))
    	if rgb_pt==2:
    		prev_xy=g_dot
    		layer.remove((g_dot, cg))
    		g_dot=pos
    		layer.insert(0,(pos, cg))
    	if rgb_pt==3:
    		prev_xy=b_dot
    		layer.remove((b_dot, cb))
    		b_dot=pos
    		layer.insert(0,(pos, cb))
    	objects = [circle("R", r_dot[0], r_dot[1], vr), circle("G", g_dot[0], g_dot[1], vr), circle("B", b_dot[0], b_dot[1], vr)]
    	rm_objects = objects
    	objx=""
    	overlap=""
    	for obj in objects:
    		for obj2 in rm_objects:
    			if obj <> obj2:
    				if obj.isColliding(obj2):
    					objx=objx+unicode('  '+obj.name+":"+obj2.name)
    					overlap='Overlap Detected:'+objx
    		rm_objects.pop(0)
    	z_draw(canvas.size)
    
    def z_dot(pos):
    	global r_dot, g_dot, b_dot, rgb_pt, layer
    	if img.getpixel(pos)[0]==cr:
    		rgb_pt=1
    	elif img.getpixel(pos)[0]==cg:
    		rgb_pt=2
    	elif img.getpixel(pos)[0]==cb:
    		rgb_pt=3
    	elif pos[1]<30:
    		if pos[0]<130:
    			layer.remove((r_dot, cr))
    			layer.insert(0,(r_dot, cr))
    		elif pos[0]>130 and pos[0]<240:
    			layer.remove((g_dot, cg))
    			layer.insert(0,(g_dot, cg))
    		elif pos[0]>240:
    			layer.remove((b_dot, cb))
    			layer.insert(0,(b_dot, cb))
    	z_draw(canvas.size)
    
    
    def z_notouch(pos):
    	global rgb_pt
    	z_xy(pos)
    	rgb_pt=0
    
    # This is the generic circle class.
    class circle:
      # Initialize with a name, the position in cartesian coordinates x, y and its radius
      def __init__(self, name, x, y, radius):
        self.name = name
        self.x = x
        self.y = y
        self.radius = radius
      
      def isColliding(self, obj2):
        distance = self.distanceTo(obj2)
        if distance < (self.radius + obj2.radius):
          return True
        return False
    
      def distanceTo(self, obj2):
        dx = abs(obj2.x - self.x)
        dy = abs(obj2.y - self.y)
        return ( math.sqrt( pow(dx, 2) + pow(dy, 2) ) )
    
    def exit():
    	app_lock.signal()
    
    appuifw.app.directional_pad=False
    canvas=appuifw.Canvas(redraw_callback=z_draw)
    appuifw.app.body=canvas
    appuifw.app.exit_key_handler=exit
    canvas.bind(key_codes.EButton1Up,z_notouch)
    canvas.bind(key_codes.EButton1Down,z_dot)
    canvas.bind(key_codes.EDrag,z_xy)
    
    timer=appuifw.e32.Ao_timer()
    timer.after(1,backlight)
    
    app_lock=appuifw.e32.Ao_lock()
    app_lock.wait()
    timer.cancel()

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

    Re: Maybe We Should Have A Pys60 Game Engine

    # bountyhunter.py

    Code:
    ### bountyhunter.py
    
    from graphics import *
    from sensor import *
    import e32,audio,appuifw,os,sys,key_codes,time,math,random
    
    max_x=500 ### <<< ref
    max_y=360 ### <<< ref
    canvasImage=None
    xm,ym=max_x,max_y
    
    def handle_redraw(rect):
    	if canvasImage: ### Skips only at first pass as "None"
    		canvas.blit(canvasImage)
    
    COLOR_BLACK=(0,0,0)
    COLOR_WHITE=(255,255,255)
    COLOR_GRAYLIGHT=(211,211,211)
    COLOR_GRAY=(128,128,128)
    COLOR_GRAYDARK=(169,169,169)
    COLOR_RED=(255,0,0)
    COLOR_ORANGE=(255,165,0)
    COLOR_YELLOW=(255,255,0)
    COLOR_GREEN=(0,128,0)
    COLOR_BLUE=(0,0,255)
    COLOR_CYAN=(0,255,255)
    COLOR_PURPLE=(128,0,128)
    
    COLOR_DARKBLUE=(0,0,139)
    COLOR_DARKGREEN=(0,100,0)
    COLOR_DEEPPINK=(255,20,147)
    COLOR_INDIGO=(75,0,130)
    COLOR_LIGHTBLUE=(173,216,230)
    COLOR_LIME=(0,255,0)
    COLOR_OLIVE=(107,142,35)
    
    COLOR_BROWN=(139,69,19)
    COLOR_GOLD=(255,215,0)
    COLOR_SILVER=(192,192,192)
    
    COLOR_MIDGREEN=(0,204,0) # ***
    
    appuifw.app.orientation='landscape'
    appuifw.app.screen='large'
    appuifw.app.directional_pad=False
    loadingStatusLine=1
    canvas=appuifw.Canvas(redraw_callback=handle_redraw)
    appuifw.app.body=canvas
    canvasImage=Image.new(canvas.size)
    
    def quit():
    	global running
    	running=0
    appuifw.app.exit_key_handler=quit
    canvasImage.clear(COLOR_BLACK)
    handle_redraw(())
    
    obj=20
    x2,y2=xm/2-obj/2,ym/2-obj/2
    rec_x=1
    rec_y=1
    x_incr=0
    y_incr=0
    
    boundary=max_x
    
    class SensorConnection():
    	xAxis=0
    	yAxis=0
    	def __init__(self):
    		"""Connect to the sensor."""
    		self.accelerometer=AccelerometerXYZAxisData(data_filter=LowPassFilter())
    		self.accelerometer.set_callback(data_callback=self.sense_conn)
    
    	def sense_conn(self):
    		self.xAxis=self.accelerometer.x*-1
    		self.yAxis=self.accelerometer.y*-1
    
    	def run(self):
    		self.accelerometer.start_listening()
    
    	def cleanup(self):
    		"""Cleanup after yourself. *Must be called* before exiting."""
    		self.accelerometer.stop_listening()
    
    running=1
    accl=SensorConnection()
    accl.run()
    
    '''
    def playSoundShoot():
    	if sound_gunshot.state() != audio.EPlaying:
    		sound_gunshot.play()
    def statusupdate(im,status,progress):
    	global loadingStatusLine
    	im.text((10,20),u"Initialising..."+progress,fill=COLOR_BLACK)
    	im.text((10,50+loadingStatusLine*20),u" > "+status,fill=COLOR_BLACK)
    	loadingStatusLine+=1
    	handle_redraw(())
    	e32.ao_yield()
    '''
    
    def doGoalAchieved():
    	global goalsAchieved,statusImage,timeLeft
    	goalsAchieved+=5000
    	statusImage=createStatusBox(goalsAchieved,timeLeft)
    	###ZZZ <<< playSoundShoot()
    
    def reset():
    	global xx,yy,goalsAchieved,timeLeft,timePassed,timeLimit,startTime,redx,redy
    	random.seed(123456789) # example sequencing
    	redx=random.randrange(0,(xm-200)-obj) # to place a min distance of x 100 pixels away from the center
    	if redx>(xm-obj)/2-100:
    		redx+=200
    	redy=random.randrange(0,(ym-200)-obj) # to place a min distance of y 100 pixels away from the center
    	if redy>(xm-obj)/2-100:
    		redy+=200
    	timePassed=0
    	timeLeft=timeLimit
    	startTime=time.time()
    	goalsAchieved=0
    	xx=100
    	yy=100
    
    def createStatusBox(count,timeleft):
    	statImg=Image.new((180,60),'RGB16')
    	statImg.clear(COLOR_ORANGE)
    	statImg.rectangle((0,0,180,60),width=4,outline=COLOR_BLACK)
    	### initial halfway markings both minus zero
    	statImg.text((10,25),u"Goals: "+unicode(count),font='dense',fill=COLOR_BLACK)
    	statImg.text((10,48),u"Time Left: "+unicode(timeleft)+" s",font='dense',fill=COLOR_BLACK)
    
    	return statImg ### >>> statImg.transpose(ROTATE_90)
    
    # determine python root (where the script is located)
    # this has to be c:\\...python... or e:\\...python...
    if(os.path.exists("C:\\data\\Python\\bountyhunter.py")):
    	PYTHON_ROOT=u"C:\\data\\Python\\bountyhunter\\"
    elif(os.path.exists("E:\\data\\Python\\bountyhunter.py")):
    	PYTHON_ROOT=u"E:\\data\\Python\\bountyhunter\\"
    else:
    	appuifw.query(u"couldn't determine python source directory" ,"query") # interupt to debug code
    
    startTime=time.time()
    prevTime=startTime
    totalTime=0
    timePassed=0
    timeLimit=60
    timeLeft=timeLimit
    
    '''
    if(os.path.exists(PYTHON_ROOT+u"gunshot.wav")):
    	statusupdate(canvasImage,"loading sounds","......")
    	sound_gunshot=audio.Sound.open(PYTHON_ROOT+u"gunshot.wav")
    else:
    	appuifw.query(u"missing audio file","query")
    '''
    dir_x=u"e:\\data\\Python\\bntyhntr.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)
    
    xx=100
    yy=100
    goalsAchieved=0
    random.seed(123456789) # example sequencing as for fairness
    redx=random.randrange(0,(xm-200)-obj) # to place a min distance of x 100 pixels away from the center
    if redx>(xm-obj)/2-100:
    	redx+=200
    redy=random.randrange(0,(ym-200)-obj) # to place a min distance of y 100 pixels away from the center
    if redy>(xm-obj)/2-100:
    		redy+=200
    	
    gameRunning=0
    res=appuifw.query(u"Start by pressing the -OK- button","query")
    if(res == 1):gameRunning=1
    startTime=time.time()
    statusImage=createStatusBox(goalsAchieved,timeLeft)
    
    # Function which draws circle with given radius at given co-ordinate
    def circle(x,y,radius=10,outline=0,fill=COLOR_GRAYLIGHT,width=1):
    	canvasImage.ellipse((x-radius,y-radius,x+radius,y+radius),outline,fill,width)
    goalrange=2500.0
    byGoal=goalrange/abs((xm/2-obj/2)+abs(ym/2-obj/2))
    while(gameRunning):
    	while running:
    		if(time.time()-startTime-timePassed>1):# over one second passed
    			timePassed=timePassed+1
    			timeLeft=timeLimit-timePassed
    			goalsAchieved+=int(goalrange-(byGoal*(abs((xm/2-xx)-obj/2)+abs((ym/2-yy)-obj/2))))
    			statusImage=createStatusBox(goalsAchieved,timeLeft)
    			if timeLeft %25 == 0:
    				e32.reset_inactivity()
    			if(timeLeft<=0):
    				running=0
    
    		y=accl.xAxis*-1 # -1 switches motion orientation
    		x=accl.yAxis*-1
    
    		x_incr=x*2
    		xx=xx+x_incr
    		y_incr=y*2
    		yy=yy+y_incr
    
    		if xx+obj>x2 and xx<x2+obj:
    			if yy+obj>y2 and yy<y2+obj:
    				xx=redx
    				redx=random.randrange(0,(xm-200)-obj) # to place a min distance of x 100 pixels away from the center
    				if redx>(xm-obj)/2-100:
    					redx+=200
    				yy=redy
    				redy=random.randrange(0,(ym-200)-obj) # to place a min distance of y 100 pixels away from the center
    				if redy>(xm-obj)/2-100:
    					redy+=200
    				doGoalAchieved()
    
    		if xx<xm/2-boundary/2:
    			xx=xm/2-boundary/2
    		elif xx>xm/2+boundary/2-obj:
    			xx=xm/2+boundary/2-obj
    		if yy<ym/2-max_y/2:
    			yy=ym/2-max_y/2
    		elif yy>ym/2+max_y/2-obj:
    			yy=ym/2+max_y/2-obj
    
    		# initial halfway markings both minus zero
    		canvasImage=Image.new((xm,ym),'RGB16')
    		canvasImage.rectangle((redx,redy,redx+obj,redy+obj),outline=COLOR_RED,fill=COLOR_RED)
    		canvasImage.rectangle((x2,y2,x2+obj,y2+obj),outline=COLOR_MIDGREEN,fill=COLOR_MIDGREEN)
    		canvasImage.rectangle((xx,yy,xx+obj,yy+obj),outline=COLOR_BLUE,fill=COLOR_BLUE)
    		canvasImage.text((374,30),unicode(hscor_db),font='title',fill=COLOR_GRAYDARK)
    		canvasImage.blit(statusImage,target=(0,canvasImage.size[1]-statusImage.size[1]))
    		handle_redraw(())
    
    		e32.ao_yield() # bottom of _running_loop_
    
    	if (goalsAchieved>hscor_db):
    		appuifw.query(u"Congratulations !!!\nYou Have Set A New Rank!" ,"query")
    		msg=(u'New Highscore: %s\nPrev Highscore: %s\n\n Play again?"' %(goalsAchieved,hscor_db))
    		hscor_db=goalsAchieved
    		f=open(dir_x,'w')
    		f.write('%s' %(hscor_db))
    		f.close()
    		print hscor_db
    	else:
    		msg=(u"TIME'S UP! \nYou have scored " + unicode(goalsAchieved) + " given " +
    				unicode(timeLimit) + " seconds \n\n Play again?")
    
    	res=appuifw.query(msg,"query")
    	if(res != 1):
    		gameRunning=0
    		print "ended"
    		
    	else:
    		running=1
    		reset()
    
    # sound_gunshot.close()
    appuifw.app.body=None
    accl.cleanup()
    Last edited by all2happy; 2012-10-24 at 11:04. Reason: cleaned up the code a little

  14. #14
    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()

  15. #15
    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

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
  •  
×