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 :D
Re: Maybe We Should Have A Pys60 Game Engine
[URL="http://www.mobilenin.com/pys60/ex_3d_cube_simple.php"]Excellent[/URL] idea! :)
/0
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 : [url]http://code.google.com/p/pygame-symbian-s60/[/url]
Re: Maybe We Should Have A Pys60 Game Engine
[QUOTE=cyke64;892712]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 : [url]http://code.google.com/p/pygame-symbian-s60/[/url][/QUOTE]
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. :D
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.
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..
Re: Maybe We Should Have A Pys60 Game Engine
[QUOTE=anees042;895090]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..[/QUOTE]
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()[/CODE]
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()[/CODE]
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()
[/CODE]
Re: Maybe We Should Have A Pys60 Game Engine
pyWuzzler_5230_editon.py -- section 1 of 2
Most of the changes made were from a friend of mine made within the hour while teaching me how it all works. For the png images... please let me know where they can "remain" uploaded.
[CODE]# pyWuzzler_5230_editon.py -- edited to also execute on the Nokia Nuron
# The ORIGINAL version of this game was developed for the course
# "interaction technologies" of the master course "mobile computing"
# at the University of Applied Sciences Hagenberg by Benjamin Gmeiner
# and Yen-Chia Lin
#
# Special thanks to Christopher Schmidt (http://crschmidt.net/), who's
# open source project "Accelball" made it a lot easier and faster to
# access the Accelerometer data
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Copyright (c) 2008 Gmeiner Benjamin, benjamin.gmeiner@fh-hagenberg.at
# Yen-Chia Lin, yen-chia.lin@fh-hagenberg.at
#
'''
from graphics import *
from sensor import *
import e32,audio,appuifw,os,sys,key_codes,time,math,random
boundary_width=492
max_x=500
max_y=360
canvasImage=None
class GameObject(object):
x=0
y=0
width=0
height=0
imgX=0
imgY=0
def getPoint(self):
return [self.x,self.y]
def getMaxX(self):
return self.x+self.width+self.imgX
def getMaxY(self):
return self.y+self.height+self.imgY
def getInX(self):
return self.x+self.imgX
def getInY(self):
return self.y+self.imgY
def drawBoundingBox(self,image):
image.rectangle((self.getInX(),self.getInY(),self.getMaxX(),self.getMaxY()),outline=COLOR_BLUE)
class SensorConnection():
xAxis=0
yAxis=0
def __init__(self):
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):
self.accelerometer.stop_listening()
def handle_redraw(rect):
if canvasImage:
canvas.blit(canvasImage)
def quit():
global running
running=0
def playSoundShoot():
global sound_hit,PLAY_SOUNDS
if(PLAY_SOUNDS==1):
if sound_hit.state()!=audio.EPlaying:
sound_hit.play()
def automask(im):
width,height=im.size
mask=Image.new(im.size,'1')
tran=im.getpixel((0,0))[0]
for y in range(height):
line=im.getpixel([(x,y)for x in range(width)])
for x in range(width):
if line[x]==tran:
mask.point((x,y),0)
return mask
def automaskArea(im,area):
width=area[2]-area[0]
height=area[3]-area[1]
startX=area[0]
startY=area[1]
mask=Image.new((width,height),'1')
tran=im.getpixel((startX,startY))[0]
for y in range(height):
for x in range(width):
if im.getpixel((startX+x,startY+y))[0]==tran:
mask.point((x,y),0)
return mask
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 checkWallBoundary():
global m_ball,m_goalObject,boundary_width
return m_ball.y<=14 and (
(m_ball.x>=0 and m_ball.x+m_ball.width< m_goalObject.x) or
(m_ball.x>m_goalObject.getMaxX() and m_ball.x<=boundary_width))
def checkSideBoundary():
global m_ball
if m_ball.x<0:
m_ball.x=0
return True
elif m_ball.getMaxX()>boundary_width:
m_ball.x=boundary_width-m_ball.width
return True
return False
def checkBackWallBoundary():
global m_ball
if m_ball.y>max_y-m_ball.height:
m_ball.y=max_y-m_ball.height
return True
return False
def checkCollision(objA,objB):
return ((objA.getInX()<objB.getMaxX())and(objB.getInX()<objA.getMaxX())and
(objA.getInY()<objB.getMaxY())and(objB.getInY()<objA.getMaxY()))
def doGoalAchieved():
global goalsAchieved,statusImage,timeLeft
goalsAchieved+=1
statusImage=createStatusBox(goalsAchieved,timeLeft)
playSoundShoot()
resetBall()
def resetBall():
global m_ball,ballSpeed,ball_reset ### ball_reset won't execute?
m_ball.x,m_ball.y=[random.randrange(30,420),270]
ballSpeed=[10,-0.05] ### >>> ball_reset
def isSameDirection(v1,v2):
return (v1<0 and v2<0 and v2<v1)or(v1>0 and v2>0 and v2>v1)
def updateFPS():
global prevTime,totalTime,fpsResult,fpsCounter
curTime=time.time()
frameTime=curTime-prevTime
prevTime=curTime
totalTime+=frameTime
if totalTime>=1:
fpsResult=fpsCounter+1
fpsCounter=0
totalTime=0
fpsCounter+=1
def createStatusBox(count,timeleft):
statImg=Image.new((172,60),'RGB16')
statImg.clear(COLOR_ORANGE)
statImg.rectangle((0,0,172,60),width=4,outline=COLOR_BLACK)
statImg.text((10,25),u"Goals: "+unicode(count),font='dense',fill=COLOR_BLACK)
statImg.text((10,48),u"Timeleft: "+unicode(timeleft)+"s",font='dense',fill=COLOR_BLACK)
return statImg ### >>> statImg.transpose(ROTATE_90)
def calibrateNeutralValue():
global accl,neutralValue
neutralValue=accl.yAxis
COLOR_BLACK=0x000000
COLOR_BLUE=0x0000ff
COLOR_ORANGE=0xffcc00
m_goalie=GameObject()
m_attackPlayer1=GameObject()
m_attackPlayer2=GameObject()
m_goalObject=GameObject()
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)
appuifw.app.exit_key_handler=quit
running=1
accl=SensorConnection()
accl.run()
if(os.path.exists("C:\\private\\a000902D\\default.py")):
PYTHON_ROOT=u"C:\\private\\a000902D\\pyWuzzler\\"
elif(os.path.exists("E:\\private\\a000902D\\default.py")):
PYTHON_ROOT=u"E:\\private\\a000902D\\pyWuzzler\\"
elif(os.path.exists("C:\\data\\Python\\pyWuzzler.py")):
PYTHON_ROOT=u"C:\\data\\Python\\pyWuzzler\\"
elif(os.path.exists("E:\\data\\Python\\pyWuzzler.py")):
PYTHON_ROOT=u"E:\\data\\Python\\pyWuzzler\\"
else:
exitLoading(u"couldn't determine python source directory")
if(os.path.exists(PYTHON_ROOT+u"initBackground.png")):
initBackroundImage=Image.open(PYTHON_ROOT+u"initBackground.png")
else:
exitLoading(PYTHON_ROOT+u"initBackground.png missing!");
canvasImage.blit(initBackroundImage,target=(0,0))
statusupdate(canvasImage,"starting initialisation","...")
statusupdate(canvasImage,"initialising basic properties","...")
PLAY_SOUNDS=1
acceleration=0.5
neutralValue=42
noOfAnimations=37
frontArea=[0,1,2,3,4,5]
neutralArea=[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
backArea=[32,33,34,35,36,37]
lastState=0
player_speed=[0,0]
goalsAchieved=0
m_ball=GameObject()
ball_reset=[10,-0.05]
ballSpeed=ball_reset
BALL_MAX_SPEED=12
ballFriction=0.995
x_gravity=0.2
y_gravity=0.025
shootForce=0
startTime=time.time()
prevTime=startTime
totalTime=0
timePassed=0
timeLimit=180
timeLeft=timeLimit
[/CODE]
Re: Maybe We Should Have A Pys60 Game Engine
pyWuzzler_5230_editon.py -- section 2 of 2
[CODE]if(os.path.exists(PYTHON_ROOT+u"hit.wav") and
os.path.exists(PYTHON_ROOT+u"hit.wav")):
statusupdate(canvasImage,"loading sounds","...")
sound_hit=audio.Sound.open(PYTHON_ROOT+u"hit.wav")
sound_bounce=audio.Sound.open(PYTHON_ROOT+u"hit.wav")
else:
exitLoading(u"some audio files are missing");
statusupdate(canvasImage,"loading player models, will take ","...")
statusupdate(canvasImage,"a while on first run","...")
if(os.path.exists(PYTHON_ROOT+u"playerSprites.png")):
playerImage=Image.open(PYTHON_ROOT+u"playerSprites.png")
else:
exitLoading(u"player sprites-file is missing");
playerImageMasks=[]
for val in range(noOfAnimations):
fName=PYTHON_ROOT+u"playerMask_"+unicode(val)+".png"
if(os.path.exists(fName)):
maskImg=Image.new(size=(34,100),mode='1')
maskImg.load(fName)
playerImageMasks.append(maskImg)
else:
playerImageMasks.append(automaskArea(playerImage,(0,val*34,100,(val+1)*34)))
playerImageMasks[val].save(fName,format='PNG',compression='no',quality=1,bpp=1)
imgName=PYTHON_ROOT+u"defenderSprites.png"
maskName=PYTHON_ROOT+u"defenderSprites_mask.png"
if(os.path.exists(imgName)):
defenderImage=Image.open(imgName)
else:
exitLoading(u"goalie sprites-file is missing");
if(os.path.exists(maskName)):
defenderImageMask=Image.new(defenderImage.size,mode='1')
defenderImageMask.load(maskName)
else:
defenderImageMask=automask(defenderImage);
defenderImageMask.save(maskName,format='PNG',compression='no',quality=1,bpp=1)
statusupdate(canvasImage,"loading ball sprites and creating mask","...")
imgName=PYTHON_ROOT+u"sprites_ballV2.png"
maskName=PYTHON_ROOT+u"sprites_ballV2_mask.png"
if(os.path.exists(imgName)):
ballImage=Image.open(imgName)
else:
exitLoading(u"ball sprites-file is missing");
if(os.path.exists(maskName)):
ballImageMask=Image.new(ballImage.size,mode='1')
ballImageMask.load(maskName)
else:
ballImageMask=automask(ballImage);
ballImageMask.save(maskName, format='PNG',compression='no',quality=1,bpp=1)
statusupdate(canvasImage,"loading pole sprites and creating mask","...")
imgName=PYTHON_ROOT+u"pole.png"
maskName=PYTHON_ROOT+u"pole_mask.png"
if(os.path.exists(imgName)):
poleImage=Image.open(imgName)
else:
exitLoading(u"pole sprites-file is missing");
if(os.path.exists(maskName)):
poleImageMask=Image.new(poleImage.size,mode='1')
poleImageMask.load(maskName)
else:
poleImageMask=automask(poleImage);
poleImageMask.save(maskName,format='PNG',compression='no',quality=1,bpp=1)
statusupdate(canvasImage,"loading background","...")
if(os.path.exists(PYTHON_ROOT+u"background.png")):
bgImage=Image.open(PYTHON_ROOT+u"background.png")
else:
exitLoading(u"background file is missing");
statusupdate(canvasImage,"initialising some properties, almost done","...")
prev_locf=0
prev_locb=0
dist_players=180
playerHeight=14
m_attackPlayer1.width=m_attackPlayer2.width=16
m_attackPlayer1.height=m_attackPlayer2.height=playerHeight
m_attackPlayer1.x=132
m_attackPlayer1.y=m_attackPlayer2.y=200
m_attackPlayer1.imgX=m_attackPlayer2.imgX=9
m_attackPlayer1.imgY=m_attackPlayer2.imgY=14
m_attackPlayer2.x=m_attackPlayer1.x+dist_players
m_ball.x,m_ball.y=[random.randrange(25,250),320]
m_ball.width=ballImage.size[1]
m_ball.height=ballImage.size[0]
m_goalie.x=240
m_goalie.y=24
m_goalie.width=16
m_goalie.height=14
m_goalie.imgX=8
m_goalie.imgY=16
m_goalObject.x=164
m_goalObject.y=0
m_goalObject.width=136
m_goalObject.height=12
speedAttackPlayer=[0,0]
defSpeed=0
leftGoalMargin=164
rightGoalMargin=284
gameRunning=0
prev_force=0
res=appuifw.query(u"Start by pressing the OK","query")
if(res==1):gameRunning=1
startTime=time.time()
framedelay=0
while(gameRunning):
statusImage=createStatusBox(goalsAchieved,timeLeft)
while running:
if(time.time()-startTime-timePassed>1):
timePassed=timePassed+1
timeLeft=timeLimit-timePassed
statusImage=createStatusBox(goalsAchieved,timeLeft)
if timeLeft%25==0:
e32.reset_inactivity()
if(timeLeft<=0):
running=0
indexRaw=accl.xAxis
indexRaw=int(indexRaw*2)
force_index=indexRaw+neutralValue
if(force_index<0):
force_index=0
elif(force_index>noOfAnimations-1):
force_index=noOfAnimations-1
src=((force_index*34,0),((force_index+1)*34,100))
canvasImage.clear(COLOR_BLACK)
canvasImage.blit(bgImage,target=(0,0))
canvasImage.blit(ballImage,target=m_ball.getPoint(),mask=ballImageMask,scale=0)
canvasImage.blit(poleImage,target=(0,0),mask=poleImageMask)
canvasImage.blit(poleImage,target=(0,200),mask=poleImageMask)
canvasImage.blit(statusImage,target=(0,canvasImage.size[1]-statusImage.size[1]))
canvasImage.blit(playerImage,target=m_attackPlayer1.getPoint(),source=src,mask=playerImageMasks[force_index],scale=0)
canvasImage.blit(playerImage,target=m_attackPlayer2.getPoint(),source=src,mask=playerImageMasks[force_index],scale=0)
canvasImage.blit(defenderImage,target=m_goalie.getPoint(),mask=defenderImageMask)
if(m_goalie.x<m_ball.x):
if(m_goalie.x>=rightGoalMargin+10 or m_ball.x-m_goalie.x<10):
defSpeed=0
else:
defSpeed=2
if(m_goalie.x>m_ball.x):
if(m_goalie.x<leftGoalMargin-20 or m_goalie.x-m_ball.x<10):
defSpeed=0
else:
defSpeed=-2
m_goalie.x+=defSpeed
PlayerSpeed=accl.yAxis*acceleration
m_attackPlayer1.x-=PlayerSpeed
m_attackPlayer2.x-=PlayerSpeed
if m_attackPlayer1.x<10:
m_attackPlayer1.x=10
m_attackPlayer2.x=10+dist_players
if m_attackPlayer1.x>=268:
m_attackPlayer1.x=268
m_attackPlayer2.x=268+dist_players
##### +++++ getting a "kick" out of this game
shootForce=(prev_force-force_index)*1.25
if shootForce==0:shootForce=1
if shootForce>prev_force and shootForce>7:
shootForce=BALL_MAX_SPEED
prev_locf=10
elif shootForce<prev_force and shootForce<-7:
shootForce=-BALL_MAX_SPEED
prev_locb=-10
else:
prev_locf,prev_locb=0,0
if abs(shootForce)==0:
shootForce=BALL_MAX_SPEED
prev_force=force_index
m_attackPlayer1.height=playerHeight+prev_locf
m_attackPlayer2.height=playerHeight+prev_locf
m_attackPlayer1.imgY=14+((force_index-8)*2.725)+prev_locb
m_attackPlayer2.imgY=14+((force_index-8)*2.725)+prev_locb
boundaryBounce=False
if m_ball.y<60:
if checkCollision(m_ball,m_goalObject):
doGoalAchieved()
if checkWallBoundary():
m_ball.y=14
ballSpeed[1]*=-1
if checkCollision(m_goalie,m_ball):
ballSpeed[1]=4
playSoundShoot()
if force_index in neutralArea:
player1Shoot=checkCollision(m_attackPlayer1,m_ball)
player2Shoot=checkCollision(m_attackPlayer2,m_ball)
if player1Shoot or player2Shoot:
if abs(shootForce)>7:
playSoundShoot()
ballCenter=m_ball.x+m_ball.width/2
playerX=0
if player1Shoot:
playerX=m_attackPlayer1.getMaxX()
else:
playerX=m_attackPlayer2.getMaxX()
playerHalfWidth=m_attackPlayer1.width/2
_res=playerX-ballCenter-playerHalfWidth
vx=((shootForce/3)/playerHalfWidth)*abs(_res)
if _res<0:
ballSpeed=[-vx,-shootForce]
else:
ballSpeed=[vx,-shootForce]
boundaryBounce=checkSideBoundary()
if m_ball.x+m_ball.width<m_attackPlayer1.x+m_attackPlayer1.width and m_ball.x+m_ball.width>m_attackPlayer1.x:
m_ball.x=m_attackPlayer1.x-m_ball.width
ballSpeed[0]=(abs(PlayerSpeed)+abs(ballSpeed[0]))*-1
if boundaryBounce:
m_ball.x=1
m_attackPlayer1.x=m_ball.x+m_ball.width
ballSpeed[0]=0
elif m_ball.x>m_attackPlayer1.x and m_ball.x<m_attackPlayer1.x+m_attackPlayer1.width:
m_ball.x=m_attackPlayer1.x+m_attackPlayer1.width
ballSpeed[0]=(abs(PlayerSpeed)+abs(ballSpeed[0]))
if m_ball.x>m_attackPlayer2.x and m_ball.x<m_attackPlayer2.x+m_attackPlayer2.width:
m_ball.x=m_attackPlayer2.x+m_attackPlayer2.width
ballSpeed[0]=(abs(PlayerSpeed)+abs(ballSpeed[0]))
if boundaryBounce:
m_ball.x=boundary_width-m_ball.width
m_attackPlayer2.x=m_ball.x-m_attackPlayer2.width
ballSpeed[0]=0
elif m_ball.x+m_ball.width<m_attackPlayer2.x+m_attackPlayer2.width and m_ball.x+m_ball.width>m_attackPlayer2.x:
m_ball.x=m_attackPlayer2.x-m_ball.width
ballSpeed[0]=(abs(PlayerSpeed)+abs(ballSpeed[0]))*-1
m_attackPlayer1.x=m_attackPlayer2.x-dist_players
else:
m_attackPlayer1.height=-1
m_attackPlayer2.height=-1
if checkSideBoundary():
ballSpeed[0]*=-1
if checkBackWallBoundary():
ballSpeed[1]=(ballSpeed[1]/1.25)*-1
ballSpeed[1]*=ballFriction
ballSpeed[0]*=ballFriction
m_ball.x+=ballSpeed[0]
m_ball.y+=ballSpeed[1]
if ballSpeed[0]>BALL_MAX_SPEED:
ballSpeed[0]=BALL_MAX_SPEED
elif ballSpeed[0]<-BALL_MAX_SPEED:
ballSpeed[0]=-BALL_MAX_SPEED
if ballSpeed[1]>BALL_MAX_SPEED:
ballSpeed[1]=BALL_MAX_SPEED
elif ballSpeed[1]<-BALL_MAX_SPEED:
ballSpeed[1]=-BALL_MAX_SPEED
if m_ball.x<12:
ballSpeed[0]+=x_gravity
elif m_ball.x>456:
ballSpeed[0]-=x_gravity
if m_ball.y<196:
if m_ball.y<120 and (m_ball.x+m_ball.width<m_goalObject.x-20) or (m_ball.x>m_goalObject.getMaxX()+20):
ballSpeed[1]+=y_gravity+0.1
else:
ballSpeed[1]+=y_gravity
elif m_ball.y>240:
ballSpeed[1]-=y_gravity
framedelay+=1
if framedelay>2:
handle_redraw(())
framedelay=0
e32.ao_yield()
res=appuifw.query(u"TIME'S UP! \nYou have shot "+unicode(goalsAchieved)+" goals in "+
unicode(timePassed)+" seconds \n\n Play again?","query")
if(res!=1):
gameRunning=0
print "ended"
else:
running=1
startTime=time.time()
timePassed=0
timeLeft=timeLimit
goalsAchieved=0
resetBall()
sound_hit.close()
sound_bounce.close()
e32.ao_yield()
appuifw.app.body=None
accl.cleanup()[/CODE]
Re: Maybe We Should Have A Pys60 Game Engine
Have decided to look for very informative (quality) videos, especially as how to install every type of application, how to make the SIS standalones including how to create the icons for them... and provide whichever links to where the downloads can be found... also those that are demos --
Developing with Qt: Nokia Smart Installer --
[url]http://www.youtube.com/watch?v=PNwNlPoObvI[/url] [url]http://wiki.forum.nokia.com/index.php/Nokia_Smart_Installer_for_Symbian[/url]
Creating Qt Apps for Symbian using the Nokia Qt SDK --
[url]http://www.youtube.com/watch?v=Sd_079HoRPE[/url]
How to create a Symbian launcher icon with your own icon and background in Adobe Illustrator --
[url]http://www.youtube.com/watch?v=1D0lH_4QiMo[/url]
How to create a Symbian launcher icon with your own icon and your own background in Inkscape --
[url]http://www.youtube.com/watch?v=TvrICzjTkn0[/url]
Qt SDK 1.1: Developing with Nokia's Qt Creator --
[url]http://www.youtube.com/watch?v=h0TxFBCyMWo[/url] [url]http://forum.nokia.com/Develop/Qt/[/url]
How to: Create a simple prototype for your next Nokia app --
[url]http://www.youtube.com/watch?v=a9vaTPbO354[/url] Balsamiq [url]http://www.balsamiq.com/[/url] [url]http://www.adobe.com/products/illustrator.html[/url]
Be sure to check out the Nokia Icon Toolkit [url]http://nokia.ly/Aj0pR8[/url] and Visual design stencils [url]http://nokia.ly/w5hqIO[/url]
Qt Quick Designer 2.2 with Qt Components for Symbian --
[url]http://www.youtube.com/watch?v=G5Q4mrq2hl8[/url] [url]http://labs.qt.nokia.com/2011/05/05/qt-quick-designer-in-qt-creator-2-2/[/url]
QML and Qt Creator --
[url]http://www.youtube.com/watch?v=k5gMAMSz77Q[/url]
Qt 01 : Qt SDK - Intro and First Qt App --
[url]http://www.youtube.com/watch?v=GlKU6jGGyHg[/url]
Final Qt SDK 1.1 Available Now for Nokia Developers --
[url]http://www.youtube.com/watch?v=6aMIoZamrOM[/url]
--
--
--
My first application - Qt for Symbian --
[url]http://www.youtube.com/watch?v=AKJsnUluU2E[/url]
How to: Avoid Common Pitfalls When Designing Apps For Symbian Devices --
[url]http://www.youtube.com/watch?v=1XabTOe8cC0[/url]
An Introduction to - QtQuick Playground --
[url]http://www.youtube.com/watch?v=T3Bc5Q4Lcps[/url]
Qt SDK - Getting Started --
[url]http://www.youtube.com/watch?v=alawFjtKCWo[/url]
Nokia Qt SDK - Cross-Platform Development Made Easy --
[url]http://www.youtube.com/watch?v=39D-a3OU1Nk[/url]
DEMOS...
Box2D and Qt 4 Graphics View --
[url]http://www.youtube.com/watch?v=U5xyrKy0sj8[/url]
--
--
LINKS...
[url]http://labs.qt.nokia.com/2010/02/26/qt-box2d-is-easy[/url]
There's most likely a whole lot more to be added. Bookmarked this page to my phone for quick referencing
Re: Maybe We Should Have A Pys60 Game Engine
RememberNumbers BETA Game
[CODE]### RememberNumbersBETA.py Game
### 4u2contact@gmail.com
'''
Special thanks to Pankaj Nathani, the source code below is primarily made from...
http://sites.google.com/site/croozeus/appuifw_module
During 2002 for about 8 months, I did PocketC programming -- generally a watered down pseudo version of C for the PalmOS,
first as a hobby wondering if it would be wise for me to make it a career and that I discontinued my ventures when there
came apparently a sudden shortage of all local community marketing support in that was realized a few months right after
I somehow lost my ingenius 3169WW 3-fold-pocket-to-full-sized-universal-wireless-keyboard...
http://www.amazon.ca/Palm-3169WW-Universal-Wireless-Keyboard/dp/B0003V577C ---- not that I'm advertising it... although I
probably should :^)
'''
import graphics, sensor, appuifw, e32, random, time, os, audio, globalui, math
app_lock=e32.Ao_lock()
dir_x=u"e:\\data\\Python\\rnum.txt"
appuifw.app.title=u"RememberNumbers BETA"
appuifw.app.directional_pad=False
canvas=appuifw.Canvas()
appuifw.app.body=canvas
txt=appuifw.Text()
appuifw.app.body=txt
intro=u"\nProgrammer: Kirk Lawrence\n\nWelcome and Thank You for taking an interest in my first attempt at \
creating a rather basic yet hopefully enjoyable pys60 game that is intended to also improve the mind's recall ability.\n\n\
The Objective:\nOf every session... try to select\nthe number that which has been added from that already shown \
whereas who gets the most correct answers within the least amount of time will make a highscore.\n"+" "*58
txt.set(intro) ### +++ hide cursor should be implimented instead of "\n"+" "*58
def exit_key_handler():
app_lock.signal()
appuifw.app.exit_key_handler=exit_key_handler
def mmenu_x():
appuifw.app.menu=[(u'Start The Game', RememberNumbers), (u'', menu_gap), (u'Top Score', tScore), (u'About ---', about), (u'', menu_gap), (u'*** Delete Saved Score ***', del_score)]
def tScore():
if os.path.isfile(dir_x):
file=open(dir_x,'r')
db_x=file.readline()
file.close
score_db, time_db=db_x.strip().split('++')
score_db=int(score_db)
globalui.global_msg_query(u"in %s s" %(time_db), u"Top Score Is %s Out Of 25" %(score_db))
else:
appuifw.note(u'A Score For This Game Is Not Found')
def about():
appuifw.note(u'RememberNumbers BETA\n\nBy Kirk Lawrence -- 2010\n4u2contact@gmail.com')
def menu_gap():
pass
def del_score():
if os.path.isfile(dir_x):
os.remove(dir_x)
appuifw.note(u'The Score Is Reset')
def RememberNumbers():
score_db=0
time_db=0
while(1): ### simple type loop
score_x=0
time_x=0
ccc=3
msg=''
deckcheck=''
num_x=[] ### to randomly store the numbers 1 to 30
new_x=[] ### to extract the numbers from num_x
thr_x=[] ### to only reveal 3 randomized numbers from new_x at a time
for k in xrange(1,30):
num_x.append(unicode(k)) ### to add each numbers as a list into the num_x array
random.shuffle(num_x) ### shuffles the numbers
for k in xrange(3):
msg=msg + str(num_x[k]) + u" "
new_x.append(num_x.pop(k))
index=globalui.global_msg_query(u"\nTry To Remember These Initial 3 Numbers Before You Begin\n\n\n Timer Is Set To Start On Your Mark\n", msg)
if index == 0:
appuifw.note(u"Cancel Accepted...\nNow Exiting","error")
appuifw.app.body=txt
break
a=time.time()
appuifw.app.body=canvas
canvas.clear((0,0,0))
for k in xrange(25,1,-1):
corr=num_x[0]
random.shuffle(new_x)
thr_x[0:3]=new_x[0:3]
thr_x[0]=corr
new_x.append(num_x.pop(0))
random.shuffle(thr_x)
msg=u'%s is left' %k
index=appuifw.selection_list(thr_x, 0)
if index == None:
appuifw.note(u"Cancel Accepted...\nNow Exiting","error")
appuifw.app.body=txt
break
else:
if thr_x[index] <> corr:
appuifw.note(u"Sorry... Game Over\n%s is the correct answer" %corr,"error")
appuifw.app.body=txt
break
else:
score_x+=1
if score_x == 25:
globalui.global_msg_query(u"Congratulations... You Got All Of Them !!!\n" + u"*"*42, u"WOWWW...")
if index == None:
appuifw.app.body=txt
break
b=time.time()
time_x=b-a
globalui.global_msg_query(u"in %s s" %(time_x), u"Your Score Is %s Out Of 25" %(score_x))
dir_x=u"e:\\data\\Python\\rnum.txt"
if not os.path.isfile(dir_x):
file=open(dir_x,'w')
file.write('0++0')
file.close
file=open(dir_x,'r')
db_x=file.readline()
file.close
score_db, time_db=db_x.strip().split('++')
score_db=int(score_db)
if score_x > score_db or score_x == score_db and time_x < time_db:
time_db=time_x
score_db=score_x
globalui.global_msg_query(u"You Have Set A New High Record!", u"%s in %s s" %(score_x,time_x))
file=open(dir_x,'w')
file.write('%s++%s' %(score_db,time_db))
file.close()
msg=unicode("\nMost Recent Score Is "+str(score_x)+" Out Of 25\nSet Within...\n"+str(time_x)+" Seconds\n \
\nHighest Score With Best Time:\n"+str(score_db)+" in "+str(time_db)+" s"+"\n"*12+" "*58) ### trick: the escape code vs tabs
appuifw.app.body=txt
txt.set(msg)
break
mmenu_x()
app_lock.wait()[/CODE]
Work In Progress... much larger png numbers to fit within red, blue, and green rectangle touch buttons which will alternate sides of the screen whenever pressed... to be kept in the graphics mode... adding music, sound effects and volume settings.
Re: Maybe We Should Have A Pys60 Game Engine
Back from a rather long break away from trying to figure how to incorporate different types of algorithms for animating through my 5230 which seems to be very limiting compared to a few other Nokia handsets as I eventually realized in the attempt to load applications such as box2D, pygame for s60, py2sis, PyFolder, icons4sis and many other applications... and can hardy find any online resources, especially enough short examples like how to fade images, how to completely block specific phone numbers, how to make the screen angle mode far less tilt sensitive, and someway way to resize masked images which I suspect some sort of animation binary converter will be needed.
I'm not sure if this share of progress will be helpful much to anybody being rather quite new to pys60 programming as myself, but hope it'll get those of us contributing more to get way further.
Found about 3 conflicts in structuring this code whereas the looped list method had caused the example to freeze in the attempt to make it very generic like being able to touch add a whole lot more circles... then noticed the fastest moving circle slightly sticks to the left and right sides... plus the circles tend to do a rather slowing hiccup movement.
[CODE]# circlesVSsides.py
from appuifw import *
import e32,audio,appuifw,os,sys,key_codes,time,math,random,graphics,sensor
running=1
def quit():
global running
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()
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_)]
rad=30
number_of_objs=3
def isColliding(objAA,objBB):
global dx,dy
dx=abs(objBB.x-objAA.x)
dy=abs(objBB.y-objAA.y)
distance=int(math.sqrt(pow(dx,2)+pow(dy,2)))
if distance < (objAA.rad+objBB.rad):
return True
return False
def z_xy(pos):
if pos[1]>570:
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:
rgb_pt=1
hSpeed=r_.speed
r_.speed=0,0
elif img.getpixel(pos)[0]==g_.cz:
rgb_pt=2
hSpeed=g_.speed
g_.speed=0,0
elif img.getpixel(pos)[0]==b_.cz:
rgb_pt=3
hSpeed=b_.speed
b_.speed=0,0
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 atSpeed(objAB):
if objAB.cz==r_.cz:
XYspeed=r_.speed
elif objAB.cz==g_.cz:
XYspeed=g_.speed
elif objAB.cz==b_.cz:
XYspeed=b_.speed
return XYspeed
canvas.bind(key_codes.EButton1Up,z_notouch)
canvas.bind(key_codes.EButton1Down,z_dot)
canvas.bind(key_codes.EDrag,z_xy)
while running:
rm_objects=objects
for objA in objects:
Aspeed=atSpeed(objA)
for objB in rm_objects:
if objA <> objB:
if isColliding(objA,objB):
Bspeed=atSpeed(objB)
objA.x += Aspeed[0]
objA.y += Aspeed[1]
### last to keep inbound
if objA.x<30:
objA.x=30
Aspeed=Aspeed[0]*-1,Aspeed[1]
elif objA.x>330:
objA.x=330
Aspeed=Aspeed[0]*-1,Aspeed[1]
if objA.y<80:
objA.y=80
Aspeed=Aspeed[0],Aspeed[1]*-1
elif objA.y>540:
objA.y=540
Aspeed=Aspeed[0],Aspeed[1]*-1
if objA.cz==r_.cz:
r_.speed=Aspeed
r_.x,r_.y=objA.x,objA.y
elif objA.cz==g_.cz:
g_.speed=Aspeed
g_.x,g_.y=objA.x,objA.y
elif objA.cz==b_.cz:
b_.speed=Aspeed
b_.x,b_.y=objA.x,objA.y
###ZZZ rm_objects.pop(0)
### blit image
img.clear(0x000000)
for objA in objects:
img.ellipse(((objA.x-rad,objA.y-rad),(objA.x+rad,objA.y+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))
canvas.blit(img)
e32.reset_inactivity()
e32.ao_yield()[/CODE]
Re: Maybe We Should Have A Pys60 Game Engine
This code was mainly from a "random-size colored rectangles" snippet that sort of first got me wanting to learn about python.
[CODE]# bouncing_sq.py
from appuifw import *
import e32
from random import randrange
from graphics import *
running = 1
def quit():
global running
running = 0
app.exit_key_handler = quit
def handle_redraw(rect):
### if img: canvas.blit(img)
pass
img = None
app.screen = 'large'
app.orientation = 'portrait'
app.directional_pad = False
app.body = canvas = Canvas(redraw_callback=handle_redraw)
img = Image.new(canvas.size)
res_x, res_y = canvas.size
dy = 20
dx = 20
x1 = 0
y1 = 0
while running:
x1 = x1 + dx
y1 = y1 + dy
x2 = x1 + 100
y2 = y1 + 100
if (x1 < -50):
dx = -1 * dx
if (y1 < -50):
dy = -1 * dy
if (x1 > res_x - 50):
dx = -1 * dx
if (y1 > res_y - 50):
dy = -1 * dy
color = randrange(0xffffff)
img.rectangle((x1, y1, x2, y2), fill=color)
canvas.blit(img)
e32.reset_inactivity()
e32.ao_yield()[/CODE]
Re: Maybe We Should Have A Pys60 Game Engine
Just started somewhat coding my own "s60inMobile.py" editor since the other ones able to work on my 5230 doesn't seem anywhere close to what I want, but I still need more examples of each basic function... and speaking of which... here's one that I found and changed just a little bit, especially for it to get back into the pys60 prompt instead of completely exiting.
[CODE]# XYZirkle.py
import appuifw
import sensor
xyz=(0,0,0)
def draw(rect):
canvas.clear(0x000000)
point_size = (xyz[2]*6)-400
point_x = (-xyz[0]+60) * canvas.size[0] / 120
point_y = (xyz[1]+60) * canvas.size[1] / 120
point = (point_x, point_y)
canvas.point(point,outline=0xffffff,width=point_size,fill=0xffffff)
def redraw():
global xyz
xyz=(sens.x,sens.y,sens.z)
draw(canvas.size)
appuifw.app.orientation='portrait'
appuifw.app.title=u'XYZirkle'
appuifw.app.directional_pad=False
canvas=appuifw.Canvas(redraw_callback=draw)
appuifw.app.body=canvas
sens=sensor.AccelerometerXYZAxisData(data_filter=sensor.LowPassFilter())
sens.set_callback(data_callback=redraw)
sens.start_listening()
def forLight():
appuifw.e32.reset_inactivity()
timer.after(10,forLight)
def exit():
app_lock.signal()
appuifw.app.exit_key_handler=exit
timer=appuifw.e32.Ao_timer()
forLight()
app_lock=appuifw.e32.Ao_lock()
app_lock.wait()
sens.stop_listening()
timer.cancel()[/CODE]