Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### pys60demos.py <<< updated 2017 Aug
- import appuifw, e32, sensor, key_codes, os, sys, re, time, math, random, graphics, audio, urllib, urllib2, base64, copy, tempfile
- lg_scr = 576
- yy2=lg_scr/9
- img=None # temp reference
- def scr(msg):
- txt.set(unicode(msg))
- z_Colors = ((u'RGB_BLACK',(0,0,0)),
- (u'RGB_WHITE',(255,255,255)),
- (u'RGB_GRAYLIGHT',(211,211,211)),
- (u'RGB_GRAY',(128,128,128)),
- (u'RGB_GRAYDARK',(169,169,169)),
- (u'RGB_RED',(255,0,0)),
- (u'RGB_ORANGE',(255,165,0)),
- (u'RGB_YELLOW',(255,255,0)),
- (u'RGB_GREEN',(0,128,0)),
- (u'RGB_BLUE',(0,0,255)),
- (u'RGB_CYAN',(0,255,255)),
- (u'RGB_PURPLE',(128,0,255)),
- (u'RGB_VIOLET',(238, 130, 238)),
- (u'RGB_PINK',(255,148,238)),
- (u'RGB_DARKBLUE',(0,0,139)),
- (u'RGB_DARKGREEN',(0,100,0)),
- (u'RGB_DEEPPINK',(255,20,147)),
- (u'RGB_INDIGO',(75,0,130)),
- (u'RGB_LIGHTBLUE',(173,216,230)),
- (u'RGB_LIME',(0,255,0)),
- (u'RGB_OLIVE',(107,142,35)),
- (u'RGB_BROWN',(128,64,0)),
- (u'RGB_GOLD',(255,215,0)),
- (u'RGB_SILVER',(192,192,192)))
- #
- rgb_menu="rgb_menu=["
- for rgb in z_Colors:
- i,ii=rgb[0].replace('RGB_',''),str(rgb[1])
- rgb_menu += "(u'"+i+"',c_"+i+"),"
- exec 'def c_'+i+'(): cv.color='+ii
- exec rgb[0]+'='+ii
- rgb_menu += ']'
- def z_bg():
- cv.bg=cv.color
- cv.t=time.time()+0.5
- cv.color=RGB_WHITE
- if (cv.bg[0] > 180 or cv.bg[1] > 148 or cv.bg[2] > 180) and sum(cv.bg) > 250: cv.color=RGB_BLACK
- img.clear(cv.bg)
- rainbow=[]
- def z(r,g,b):
- rainbow.append((r,g,b))
- r,g,b=255,0,0
- for g in range(256):
- z(r,g,b)
- for r in range(254, -1, -1):
- z(r,g,b)
- for b in range(256):
- z(r,g,b)
- for g in range(254, -1, -1):
- z(r,g,b)
- for r in range(256):
- z(r,g,b)
- for b in range(254, -1, -1):
- z(r,g,b)
- max_rgb=len(rainbow)-1
- #
- alnu=u'one two three four five'.split()
- def dts(x=0):
- import datetime
- dt=datetime.datetime.now()
- ampm=' am'
- if dt.hour > 11 and dt.hour != 24: ampm=' pm'
- d=dt.hour%12, dt.minute, dt.second
- d="%02d:%02d:%02d" % (d)
- if x:
- d2= dt.strftime("%A %d %B %Y ")
- if x is 2:
- d2 += d+ampm
- elif x is 3:
- d2=d2.split()[:-1] + d.split(':') + [ampm]
- return d2
- return d+ampm
- #
- mask_z="""
- def automask(im):
- width, height=im.size
- mask=Image.new(im.size, '1') # black and white
- tran=im.getpixel((0,0))[0] # transparent top-left
- 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) # mask on the point
- return mask
- #Converts the specified "area" of the image into an image mask
- #Transparent color is the color found in the upper left pixel
- 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') # black and white
- tran=im.getpixel((startX,startY))[0] # transparent top-left
- 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 z_text():
- msg=appuifw.query(u'Enter text','text' )
- scr(msg)
- def z_number():
- msg=appuifw.query(u'Enter number','number' )
- scr(msg)
- def z_date():
- msg=appuifw.query(u'Enter date','date' )
- scr(msg)
- def z_time():
- msg=appuifw.query(u'Enter time','time' )
- scr(msg)
- def z_code():
- msg=appuifw.query(u'Enter code','code' )
- scr(msg)
- def z_multiquery(): # accept only 2 entries at a time
- try:
- first_name,last_name=appuifw.multi_query(u'Enter first name',u'Enter last name')
- scr('Hello, %s %s.\nThis is a demo.' %(first_name,last_name))
- except:
- pass
- def z_query():
- msg=appuifw.query(u'query','query' )
- scr(msg)
- def z_popup():
- items=[u'item 1',u'item 2',u'item 3',u'item 4',u'item 5',u'item 6',u'item 7',u'item 8',u'item 9']
- index=appuifw.popup_menu(items,u'*** Select Item ***')
- scr('popup '+items[index]+' was selected')
- def note_info(): # type: info
- # create a pop-up note: appuifw.note(label,type)
- appuifw.note(u'information note','info')
- def note_error(): # type: error
- appuifw.note(u'error note','error')
- def z_checkbox(): # note: when none is checked,the highlighted is then selected
- items=[u'item 1',u'item 2',u'item 3',u'item 4',u'item 5']
- chosen=appuifw.multi_selection_list(items,style='checkbox',search_field=0)
- chosen=sorted(chosen)
- z_selected(chosen,items)
- def z_checkmark(): # note: when none is checked, the highlighted is then selected
- items=[u'item 1',u'item 2',u'item 3',u'item 4',u'item 5']
- chosen=appuifw.multi_selection_list(items,style='checkmark',search_field=1)
- chosen=sorted(chosen)
- z_selected(chosen,items)
- def z_selected(chosen,items):
- selected=u'Selected: --'
- for i in chosen:
- selected=selected+'\n\t\t'+items[i]
- txt.set(selected)
- def z_regex():
- print
- print
- print "\nCommon image references--"
- imgReg = '''["']([a-zA-Z0-9_$]+\.(?:jpe?g|gif|png|bmp))["']'''
- print imgReg
- print
- def okay(test):
- print test, '=',
- print re.findall(imgReg, test, re.IGNORECASE)
- okay('''abc="jpg''')
- okay('''abc=".jpg"''')
- okay('''abc="2.jpg"''')
- okay('''abc="_.jpg"''')
- okay('''abc="$.jpg"''')
- okay('''abc="*.jpg"''')
- okay('''abc="+.jpg"''')
- okay('''abc="/.jpg"''')
- okay('''abc='test.test.png"''')
- okay('''abc="test.jpg"''')
- okay('''abc="test.jpeg"''')
- okay('''abc="test.JPEG"''')
- okay('''abc="TEST.gif"''')
- okay('''abc="test.png"''')
- okay('''abc="test.xjpg"''')
- okay('''abc="test.jpgx"''')
- okay('''abc="test..jpg"''')
- def z_dl():
- URL = "http://www.python.org/images/python-logo.gif"
- if appuifw.query(u'Might take quite a long while to download the 2.48kb image','query' ): ### ???
- dest_file = u"E:\\Images\\python-logo.gif"
- print
- print "Downloading Image...",
- urllib.urlretrieve(URL, dest_file)
- appuifw.note(u'Opening Viewer To Showcase Image Downloaded','info')
- print "Completed!"
- viewer = appuifw.Content_handler()
- viewer.open(dest_file)
- def z_savedata():
- dir_x = u'E:\\'
- folder = u'Python\\demos\\'
- try: os.mkdir(dir_x+folder)
- except: pass
- filename = 'demofile.txt'
- fullpath = dir_x + folder + filename
- print fullpath
- # Open the file for writing -- Note if to append the data... change the 'w' to 'a'
- #if not os.path.isfile(fullpath):
- f=open(fullpath,'wb')
- f.write("Python is a great language!\n\n-- End of Demo --\n")
- f.close
- # Open the file for reading
- f = open(fullpath, 'rb')
- # Read the file
- db_x = f.read()
- print db_x
- # Close the output file... as for good measure
- f.close()
- #
- newtabs=alnu
- def z_tabexit():
- app.set_tabs([],None)
- z_mainmenu()
- def z_5tabs(): # Note: Substitute changes were made since the tabs did not work properly for the Nokia 500
- # normalize screen
- app.screen='normal'
- app.menu=[(u'End tab demo',z_tabexit)]
- # create a function that handles switching between tabs
- def tab_handler(i):
- global newtabs
- i=alnu.index(newtabs[i])
- newtabs=alnu[i:]+[alnu[0]]
- app.set_tabs(newtabs,tab_handler)
- # set the tabs
- # switch to the tab according to index
- if(i==0):
- demo='This is tab #1'
- elif(i==1):
- demo='This is the second tab'
- elif(i==2):
- demo='Now tab #3'
- elif(i==3):
- demo='Showing fourth tab'
- else:
- demo='*** Finally, tab 5 ***'
- app.body=appuifw.Text(unicode(demo))
- # open the first tab
- tab_handler(0)
- #
- def z_submenu_demo():
- # create the application menu including submenus
- msg=[(u'item 1',z_item1),(u'item 2',z_item2),
- (u'Submenu 1',((u'sub item 1',z_subitem1),(u'sub item 2',z_subitem2),(u'sub item 3',z_subitem3))),
- g_menu]
- scr('Submenu Demo')
- app.menu=msg
- def setTabs(self):
- app.set_tabs([u'Main',u'Text',u'List',u'Canvas'],z_tabs)
- def text_color(COLOR):
- txt.color=COLOR
- def text_hlight(COLOR):
- txt.highlight_color=COLOR
- def text_font():
- txt.font=(u'Nokia Hindi S60',25,None)
- def abc(demo):
- if type(demo) is tuple: demo=demo[0]
- txt.add(u''+demo+' 0123456789 ABCDEFG\n')
- txt.add(u'abcdefghijklmnopqrstuvwxy\n')
- def z_text():
- mem_style=txt.style
- mem_color=txt.color
- txt.clear()
- txt.font=("annotation")
- txt.color=(255,0,0)
- abc(txt.font)
- txt.font=("annotation",42,None)
- txt.add(u'annotation @ 42\n')
- txt.font="title"
- txt.color=(0,255,255)
- abc(txt.font)
- txt.font="legend"
- txt.color=(0,255,0)
- abc(txt.font)
- txt.font="dense"
- txt.color=(0,0,255)
- abc(txt.font)
- txt.font="normal"
- txt.color=(0,0,0)
- abc(txt.font)
- txt.style=(STYLE_BOLD)
- txt.add(u'STYLE_BOLD\n')
- txt.style=(STYLE_ITALIC)
- txt.add(u'STYLE_ITALIC\n')
- txt.style=(STYLE_UNDERLINE)
- txt.add(u'STYLE_UNDERLINE\n\n')
- txt.style=(STYLE_BOLD|STYLE_ITALIC|STYLE_UNDERLINE)
- txt.add(u'All 3 Styles\n')
- txt.style=mem_style
- txt.color=mem_color
- styles=( STYLE_BOLD, STYLE_ITALIC, STYLE_UNDERLINE, STYLE_STRIKETHROUGH,
- HIGHLIGHT_STANDARD, HIGHLIGHT_SHADOW, HIGHLIGHT_ROUNDED )
- def style_toggle(a_style): ### ZZZ
- ''' Toggle style (on/off) '''
- if txt.style & a_style:
- txt.style = txt.style ^ a_style
- else:
- txt.style = txt.style | a_style
- def no_style(a_style):
- ''' Clear all text style attributes '''
- txt.style = 0
- '''
- set_pos(cursor_pos)
- len()
- set(text)
- delete([pos=0,length=len()])
- get_pos()
- get([pos=0,length=len()])
- '''
- def addtext(msg):
- txt.add(unicode(msg))
- # create the callback functions for the application menu and its submenus
- def z_item1():
- scr('item one was selected')
- def z_item2():
- scr('item two was selected')
- def z_subitem1():
- scr('subitem one was selected')
- def z_subitem2():
- scr('subitem two was selected')
- def z_subitem3():
- scr('subitem three was selected')
- def z_find(reverse=False,beginning=False):
- '''find text within a document'''
- string=appuifw.query(u'Find text:','text',unicode(last_find))
- saved_string=string[:]
- if (string != None):
- try:
- text=text.get()
- if settings.config['casesensitive'][0] == 'no':
- text=text.lower()
- string=string.lower()
- if beginning:
- if reverse:
- cur_pos=text.rindex(string)
- else:
- cur_pos=text.index(string)
- else:
- if reverse:
- cur_pos=text.rindex(string,0,(text.get_pos() -1))
- else:
- cur_pos=text.index(string,(text.get_pos() +1))
- text.set_pos(cur_pos)
- except:
- appuifw.note(u'Search string not found.','info')
- last_find=saved_string
- def z_replace():
- '''find and replace all instances of a given string'''
- replace=appuifw.multi_query(u'Replace :',u'with : ')
- if replace != None:
- text=text.get()
- cur_pos=text.get_pos()
- text.set(text.replace(replace[0],replace[1]))
- text.set_pos(cur_pos+text[0:cur_pos].incr(replace[0])*(len(replace[1])-len(replace[0])))
- appuifw.note(unicode(text.incr(replace[0]))+' instances replaced')
- def _rename():
- '''rename a file/folder'''
- path=dir_iter.entry(browse.current())
- filename=unicode(os.path.basename(path))
- if appuifw.query(u'Rename '+filename+' ?','query'):
- newname=appuifw.query(u'Rename '+filename,'text',filename)
- if newname != None:
- try:
- os.rename(path,os.path.dirname(path)+str(newname))
- appuifw.note(u'File renamed','info')
- except:
- appuifw.note(u'Error renaming file!','error')
- def screen():
- '''change the screen size'''
- current_screen=config['screen']
- config['screen']=appuifw.popup_menu([\
- u'Normal',\
- u'Large',\
- u'Fullscreen',\
- ],u'Screen size:')
- if (config['screen'] == 0):
- app.screen='normal'
- config['screen']='normal'
- elif (config['screen'] == 1):
- app.screen='large'
- config['screen']='large'
- elif (config['screen'] == 2):
- app.screen=full
- config['screen']=full
- else:
- config['screen']=current_screen
- def z_speech(data):
- if data !='':
- e32.ao_sleep(0.2)
- audio.say(data)
- #
- def z_betw(x,y,betw):
- if betw == int(betw):
- if betw < 0:
- l,r,t,b=betw,abs(betw),betw,abs(betw)
- else:
- l,r,t,b=0,betw,0,betw
- elif len(betw) == 2:
- l,r,t,b=0,betw[0],0,betw[1]
- else:
- l,r,t,b=betw
- if x < l: x=l
- elif x > r: x=r
- if y < t: y=t
- elif y > b: y=b
- return x,y
- #
- xy_outline=(-5,5),(-5,-5),(5,-5),(5,5),(0,-5),(0,5),(-5,0),(5,0),(0,0)
- def z_outline(x,y, msg,fg=RGB_LIME,bg=RGB_BLACK):
- color=bg
- for xy in xy_outline:
- if xy == (0,0): color=fg
- img.text((x+xy[0],y+xy[1]), unicode(msg),fill=color,font=(u'Nokia Hindi S60',100,STYLE_BOLD))
- #
- def star_5pt(x,y,s):
- a,b,c,d,e,f,g,h,j,k,m,n,p=0,180,192,250,308,500,340,294,402,476,357,96,157
- plot_xy=[(a,b),(c,b),(d,a),(e,b),(f,b),(g,h),(j,k),(d,m),(n,k),(p,h)]
- nova=[]
- for xy in plot_xy:
- xy=(xy[0]*0.002)*s+x,(xy[1]*0.002)*s+y
- nova.append(xy)
- return nova
- #
- def btns_med(x=4,y=7,xy=(0,0),sz=(90,90)):
- code='if 1:\n'
- i=0
- if xy is 1: xy=(0,38)
- for y2 in range(y):
- for x2 in range(x):
- xx=str(sz[0]*x2+xy[0])
- yy=str(sz[1]*y2+xy[1])
- n=str(i+1).zfill(2)
- code += '\txy_'+n+'=(('+xx+','+yy+'), ('+xx+'+'+str(sz[0])+','+yy+'+'+str(sz[1])+'))\n'
- code += '\tdef box_'+n+'(event):\n\t\tcv.xy,cv.btn=xy_'+n+','+str(i+1)
- code += '\n\tcanvas.bind(key_codes.EDrag, box_'+n+', ((xy_'+n+')))\n'
- return code
- #
- def mosaic(s=90):
- for x in range(0,s*4,s):
- for y in range(0,s*7,s):
- img.rectangle((x,y,x+s,y+s),fill=(random.randint(80,255),random.randint(80,255),random.randint(80,255)))
- #
- def sCapture(scr):
- z=graphics.screenshot()
- if scr[-4:] not in ['.png','.jpg','.gif']: scr += '.png'
- z.save(u"e:\\python\\"+scr)
- z.save(u"e:\\python\\_.png") # should immediately unlock the saved image
- appuifw.note(u'Screenshot Has Been Saved As: '+scr+'\n... Hopefully.','conf')
- #
- def z_loop():
- for i in range(1, 23):
- print 'for num in range(1, 23) >>> '+str(i)
- print '*** time.sleep(10) # 10 seconds'
- time.sleep(5)
- for i in range(1, 10):
- print 'scrolling...'
- def z_dts():
- scr(dts()+'\n'+dts(1)+'\n'+dts(2)+'\n'+str(dts(3)))
- #
- def z_enum():
- scr('for item in enumerate('+str(alnu)+')\n\n>>>\n')
- for item in enumerate(alnu):
- print(item)
- #
- def slidebar():
- cv.sVy=cv.y/yy2
- img.rectangle(((350,0,358,640)), fill=RGB_BLACK)
- for sVyy in xrange(0,9,2):
- yy=yy2*sVyy+2
- img.rectangle(((350,yy,358,yy+yy2)), fill=RGB_WHITE)
- #
- def z_tools():
- index=appuifw.popup_menu(tools,u'*** Select Tool ***')
- cv.val=tool_val[index]
- #
- def pr_menu(z):
- msg=''
- for i in z:
- msg+=str(i[0])+'\n'
- scr(msg)
- app.menu=z
- #
- def z_textmenu():
- pr_menu(t_menu)
- #
- def z_textmenu2():
- pr_menu(t2menu)
- #
- class cv():
- go='+++'
- color=RGB_WHITE
- xyz=[0,0,0]
- xy=[0,0]
- x=0
- y=0
- light=0
- evt=None
- tmp=0
- sw=0
- padx,pady=0,0
- up=-1
- w=1
- h=1
- cv=cv()
- arrow_points=[ ( 0.0, -6.0), ( 3.0, 0.0), ( 1.0, 0.0),
- ( 1.0, 6.0), (-1.0, 6.0), (-1.0, 0.0),
- (-3.0, 0.0)]
- #
- def draw(rect):
- if img:
- canvas.blit(img)
- #
- def e_callback(event):
- x,y=event['pos']
- try: timer.cancel()
- except: pass
- if cv.x > 270:
- try: cv.incr=increment[int(cv.y/yy2)]
- except: cv.incr=0
- cv.down=[cv.incr]*10
- if event['type'] == key_codes.EButton1Down:
- if cv.sz == full:
- cv.sz=large
- cv_set()
- cv.jot=(x, y, x+1, y+1)
- elif event['type'] == key_codes.EDrag:
- pass # see def line_plot()
- elif event['type'] == key_codes.EButton1Up:
- cv.down=None
- cv.x=x
- cv.y=y
- def line_plot():
- x1,y1,x2,y2=cv.jot
- cv.jot=x2,y2,cv.x,cv.y
- step=10 ### ZZZ
- def pieplot():
- exec ('cv.'+cv.val+'+='+str(pdeg[cv.deg]))
- def circle(x,y,radius,fill,outline=0,width=0):
- img.ellipse((x-radius,y-radius,x+radius,y+radius),outline=outline,fill=fill,width=width)
- def square(loc,color):
- x,y=loc
- img.rectangle((x*step,y*step,x*step+step,y*step+step),fill=color)
- def radian(d):
- return (float(d)*pi)/180.0
- def velo(objx,objy,xdir,ydir,speed=0.05): # velocity
- xx = xdir * speed
- yy = ydir * speed
- return objx+xx,objy+yy,xdir-xx,ydir-yy
- def switch(): # boolean
- cv.sw=(1,0)[cv.sw]
- def portal(direction,max,min=0):
- if direction < min: direction += max
- if direction > max: direction -= max
- return direction
- def draw_score():
- img.rectangle((0,0,360,20),fill=(0,0,0))
- img.text((2,14),u"Score: %d Speed: %d%s"%(score,1200-speed,'inches/hr'),(0,192,0))
- def draw_field():
- img.rectangle((0,20,360,y_max*step),fill=fieldcolor)
- def xyzsens():
- try:
- cv.xyz=(sens.x,sens.y,sens.z)
- except: pass
- full,large,normal='full large normal'.split()
- def cv_set(i=0):
- global img
- if i == 0:
- cv.ttl='Pys60 Demos'
- cv.sz=large # (full,normal)
- cv.ori='portrait' # (landscape)
- cv.dpad=False
- cv.color=RGB_WHITE
- cv.font='normal'
- cv.padx,cv.pady=0,0
- forLight() # ??? ZZZ not working
- app.title=unicode(cv.ttl)
- app.orientation=cv.ori
- app.screen=cv.sz
- app.directional_pad=cv.dpad
- app.body=cv.mode
- img=Image.new(canvas.size)
- #
- def forLight():
- timer=appuifw.e32.Ao_timer()
- appuifw.e32.reset_inactivity()
- if cv.light:
- timer.after(10,forLight)
- #
- def z_xyzircle():
- cv.go='$xyzircle'
- #
- def z_360arrow():
- cv.go='$360arrow'
- #
- def z_progress():
- cv.go='$progress'
- #
- def z_SnakeGame():
- cv.go='$SnakeGame'
- #
- def z_SpinCube():
- cv_set()
- cv.go='$SpinCube'
- #
- def z_3Dspin():
- cv_set()
- cv.go='$3Dspin'
- #
- def z_snowfall():
- cv_set()
- cv.go='$snowfall'
- #
- def z_bouncySq():
- cv_set()
- cv.go='$bouncySq'
- #
- def z_star_5pt():
- cv_set()
- cv.go='$star_5pt'
- #
- def z_captureDemo():
- cv_set()
- cv.go='$captureDemo'
- #
- def z_sqdance():
- cv_set()
- cv.go='$sqdance'
- #
- def z_btn_matrix():
- cv_set()
- cv.go='$btn_matrix'
- #
- def z_sketchpad():
- cv_set()
- cv.go='$sketchpad'
- #
- def z_slider():
- cv_set()
- cv.go='$slider'
- #
- def z_blend_colors():
- cv_set()
- cv.go='$blend_colors'
- #
- def z_pieslice():
- cv_set()
- cv.go='$pieslice'
- #
- def z_text2fit():
- cv_set(1)
- cv.go='$text2fit'
- #
- def z_velocity():
- cv_set(1)
- cv.go='$velocity'
- #
- def z_textscroll():
- cv_set(1)
- cv.go='$textscroll'
- #
- def z_ori():
- if cv.ori is 'portrait': cv.ori='landscape'
- else: cv.ori='portrait'
- z_text2fit()
- def z_fit(a,b,c):
- pl=canvas.measure_text(a,font=b)[1] # pixel length
- cl=canvas.measure_text(a,font=b,maxwidth=c)[2] # chr length
- ### note: maxwidth is not generic
- return cl,pl
- def text2wrap(prev,new=None,gap=20,setfont=(u"dense",30)):
- if type(prev) in [int,tuple]:
- color=prev
- if new:
- if gap is not 20:
- setfont=gap
- gap=new
- y=40
- for gen in wrapped:
- img.text((gap,y),u''+gen,font=setfont,fill=color)
- y += 36
- else:
- ww=canvas.size[0]-gap*2
- if type(prev) != list: prev=[]
- def wrap_gen(line):
- tmp=''
- if prev: tmp=prev.pop(-1)+' '
- while 1:
- cl,pl=z_fit(tmp+line,setfont,ww)
- if pl > ww:
- if tmp:
- prev.append(tmp)
- tmp=''
- else:
- prev.append(line[:cl])
- line=line[cl:]
- else:
- break
- prev.append(tmp+line)
- if ' ' in new: new=new.split()
- else: new=[new]
- for data in new: wrap_gen(u''+data)
- _gv = globals()
- _gv['wrapped']=prev[:]
- #
- animals=[u'dog', u'cat', u'cow']
- def z_rec2play():
- scr('Record animal sounds')
- for animal in animals:
- fullpath='e:\\'+animal+'.wav'
- try: os.remove(fullpath)
- except: pass
- rec="sound of a "+animal
- z_record(fullpath,rec)
- z_playaudio(animals)
- for animal in animals:
- fullpath='e:\\'+animal+'.wav'
- try: os.remove(fullpath)
- except: pass
- print 'Done!'
- def z_record(fullpath,rec=''):
- sounds=audio.Sound.open(fullpath)
- if appuifw.query(u"Record "+rec, "query"):
- sounds.record()
- appuifw.query(u"Press OK to stop recording", "query")
- sounds.stop()
- sounds.close()
- def z_playaudio(menu):
- while True:
- index=appuifw.popup_menu(menu, u"Select sound...")
- if index == None:
- break #
- else:
- sound=u'e:\\'+menu[index]+'.wav'
- sound=audio.Sound.open(sound)
- sound.play()
- def z_readtext():
- phrases=[u'Here is an All-In-One demo',u'Thank you very much',u'This PyLang is awesome!']
- index=appuifw.popup_menu(phrases,u'*** Select Phrase ***')
- data=phrases[index]
- scr(data)
- z_speech(data)
- #
- def menuX():
- cv.go='+++'
- cv_set()
- full_bind()
- cv.mode=txt
- app.exit_key_handler=mainexit
- def z_mainmenu(null=''):
- menuX()
- scr('Main Menu --\nPress Options\n\n')
- app.menu=mainmenu
- def z_gfxmenu():
- menuX()
- scr('Graphics Demo Menu --\nPress Options\n\n')
- app.menu=g2menu
- def z_rgbmenu():
- app.menu=[(u'<<<', z_pad_menu)]+rgb_menu
- def z_pad_menu():
- pad__=pad_menu[:]
- if cv.go not in ['$sketchpad']: pad__.pop(1)
- app.menu=pad__
- def z_audiomenu(): ### ZZZ
- cv_set()
- scr('Audio Demo --\nPress Options\n\n')
- app.menu=s_menu
- def z_exitmenu():
- app.menu=[m_menu]
- #
- m_menu= u'*** Main Menu',z_mainmenu
- g_menu= u'*** GFX Menu',z_gfxmenu
- g2menu= [(u'XYZCircle',z_xyzircle),
- (u'Snake Game',z_SnakeGame),
- (u'Blend Colors',z_blend_colors),
- (u'3D Spin',z_3Dspin),
- (u'Spin Cube',z_SpinCube),
- (u'Velocity',z_velocity),
- (u'360arrow',z_360arrow),
- (u'Basic Buttons',z_btn_matrix),
- (u'Color Slider',z_slider),
- (u'Sketchpad',z_sketchpad),
- (u'Pie-Arc-Key',z_pieslice),
- (u'5pt Star',z_star_5pt),
- (u'Snowfall',z_snowfall),
- (u'Bouncy Square',z_bouncySq),
- (u'Capture Demo',z_captureDemo),
- (u'Progress Bar',z_progress),
- (u'Mosaic Dance',z_sqdance),
- (u'Text Scroll',z_textscroll),
- (u'Text Wrap',z_text2fit),
- m_menu]
- s_menu= [(u'rec and play',z_rec2play),
- (u'text-to-speech',z_readtext),
- m_menu]
- t_menu= [(u'text',z_text),
- (u'number',z_number),
- (u'date',z_date),
- (u'time',z_time),
- (u'code',z_code),
- (u'query',z_query),
- (u'multi-query',z_multiquery),
- (u'checkbox: multi-select',z_checkbox),
- (u'checkmark: multi-select',z_checkmark),
- (u'popup menu',z_popup),
- (u'tabs (5)*',z_5tabs),
- (u'Sub Menu',z_submenu_demo),
- m_menu]
- t2menu= [(u'loop',z_loop),
- (u'enumerate',z_enum),
- (u'datetime',z_dts),
- (u'basic image regex',z_regex),
- (u'download image',z_dl),
- (u'save text data',z_savedata),
- m_menu]
- #(u'textwrap*',z_textwrap),
- mainmenu=[(u'Text Demo',z_textmenu),
- (u'Text Demo 2',z_textmenu2),
- (u'Graphics Demo',z_gfxmenu),
- (u'Audio Demo',z_audiomenu)]
- exec rgb_menu
- pad_menu=[(u'-- Color Selection',z_rgbmenu),(u"-- Set Background",(z_bg)),(g_menu)]
- img=None
- app.screen = 'large'
- app.orientation = 'portrait'
- app.directional_pad = False
- app.body = canvas = Canvas(redraw_callback=draw, event_callback=e_callback) #
- img = Image.new(canvas.size)
- txt=appuifw.Text()
- x_scr=canvas.size[0]
- y_scr=canvas.size[1]
- x_mid=x_scr / 2
- y_mid=y_scr / 2
- cv.mode=txt
- cv.t=0
- app_lock=e32.Ao_lock()
- if 1: # b64_img
- py_png_b64='''\
- R0lGODlhQABAAPcAAAAAAAAPMwAXNwAaOAAYQwAbQQAdQQAbTwAeSwAWUQMmQgAjSwEnSwYuTwoo
- SggtSAwrSAAlVAAgWQAmWAAqVgAuVwAuXQcuWAw1TQs5Xhk0SQAsYwAxZAA1YQA0bAA6bAA/dyw/
- UAxAbgxGeh5BYRxHbRRKdBRNfi5IXC5OaCJQdCNUfzdTajlQYj1UaTJWdDZge0BXaUZZaE1dakJa
- cEBffElhc0lieUlmfU9leQZJgBRVjB5bjypehzNXhzFbgTlchiZjljhkhzRplixtozNwozF1qzp4
- q0BehERmhENli0dshUZvjktylk1wkE92kltvgVBwiVp1g1lyiVl1il95j1B3l1V3klh6lmB2iWt7
- lUWDuUaIvEqCskmGul6Col2FqVSLtVONvVqMtl+NsWaInmmAlGyGnHOGlHGHmXGKnnqJk3mMm3uR
- lX2Qn2SGpmqIoW+Pp2yOrGeRuXGLoneOoHaPo3STp3eSrXyRonWZuX2gvmOWwW2aw2meynOfwnGh
- yXuhw3yly3iqz3ypz3Sl0HCp1pt+Ha6ED6SAE6yDGqeRF7OEBbqTCriTFr6fEKyJLaODMKWWJqWS
- M7WTI7aWN62iJrqlKrekOJiOR5uRTKSTRqaXVa2bV7mZR7mdVKmeZ62da62ec7Cfd7ujRrCmXrGt
- W7yoWq6jaqyicbWga7OpbbqpbbSrebmueMGXC8SaFcSZJcOcNcqjGtSoHc2pJ8yrOcG1P9iuKdG4
- LdC5PtmwPNq5MN29PcurScqtWtG8S9uwS9G8X921Xsmvbc2yd9C9cN/AUNHAfeHKRePMUuDDYOTP
- ZODFcubPdOLIfoKPmIGZq4qcrIGasYedsYOgs4eiv5euvoSjwIapx4KozYSrzI6wzoaw1Iux1Y+1
- 1oq12JSyz5K00Ji305i72qC706C92Z3B3JnA4aTC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AAAAA
- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAP8ALAAAAABAAEAA
- AAj/AP8JHEiwoEGBARIqXMhQ4cGHECNCbEixYkKJGDMOtMixosaPBzuKbAiyJMKRKAOYBEnyZEqG
- KzXCJPhyZkyJNl3WvHgzYs5/Oxf29GkzqNChD42KRJpUKUemIZ1ahGpQ6lSqNK1SxLqy5lCtL4F6
- JAo2pdixUcua7ZhWLcqzVze6DTsy69y3dXXeXfoW7l62eP/mDSwYcGGweg8r9avYaOLGXhlDNvtY
- 8M3JdieHlax5cOedlT8bFr2ZtFfTFwmLDg0TNWuhpjNPjS13dOeqtjW33bq6qcfPOH9DRhqZK8u7
- xl8vTr43OWerzpszd1rb4XTHsqMvr65SO3a/zpUXEw+vNrzs7ea5j09fEDT74GyZBgQAOw=='''
- tf = tempfile.mktemp(".png", "tmp_x")
- print tf
- g = open(tf, 'wb')
- g.write(base64.decodestring(py_png_b64))
- g.close()
- png = Image.open(tf)
- g = open(tf, 'wb')
- g.write(base64.decodestring(b64mask))
- g.close()
- png_mask = Image.open(tf)
- img_mask=Image.new(png_mask.size, mode='1')
- img_mask.blit(png_mask)
- def mainexit():
- z_tabexit()
- app_lock.signal()
- cv.go=False
- app.exit_key_handler=mainexit
- timer=appuifw.e32.Ao_timer()
- app_lock=appuifw.e32.Ao_lock()
- import sensor
- sens=sensor.AccelerometerXYZAxisData(data_filter=sensor.LowPassFilter())
- sens.set_callback(data_callback=xyzsens)
- sens.start_listening()
- ### joypad
- mv=0
- jxa,jya=70,350 ### <<< jpad xy axis point
- jxb,jyb=jxa+220,jya+220
- jx1,jy1=jxa+70,jya+70
- jx2,jy2=jxa+150,jya+150
- def mL(event):
- global mv
- if mv <> 3:
- mv=2
- def mR(event):
- global mv
- if mv <> 2:
- mv=3
- def mU(event):
- global mv
- if mv <> 1:
- mv=0
- def mD(event):
- global mv
- if mv <> 0:
- mv=1
- def bind_jpad():
- canvas.bind(EButton1Down,mU,((jx1,jya),(jx2,jy1))) # up
- canvas.bind(EButton1Down,mD,((jx1,jy2),(jx2,jyb))) # down
- canvas.bind(EButton1Down,mL,((jxa,jy1),(jx1,jy2))) # left
- canvas.bind(EButton1Down,mR,((jx2,jy1),(jxb,jy2))) # right
- def jpad():
- grey=(220,220,220)
- img.rectangle((jxa,jy1,jxb,jy2),fill=grey) # w
- img.rectangle((jx1,jya,jx2,jyb),fill=grey) # h
- def jpad_key(): ### bonus feature!
- if mv == 0:
- xy_=(jx1,jya,jx2,jy1) # U
- elif mv == 1:
- xy_=(jx1,jy2,jx2,jyb) # D
- elif mv == 2:
- xy_=(jxa,jy1,jx1,jy2) # L
- elif mv == 3:
- xy_=(jx2,jy1,jxb,jy2) # R
- else: return
- img.rectangle(xy_,fill=0xffff00)
- #
- if not appuifw.touch_enabled():
- appuifw.note(u"This application only works on devices that support touch input")
- #
- def up_event(event):
- cv.up=-1
- def dn_event(event):
- cv.up=1
- #
- def mv_event(event):
- x=event[0]
- y=event[1]
- jx=x/cv.w
- jy=y/cv.h
- cv.btn99=jx+(jy*4)+1
- cv.xy=(cv.w*jx,cv.h*jy)
- cv.up=time.time()+1
- #
- def btn_pad(xx=4,yy=7):
- for y2 in range(yy):
- for x2 in range(xx):
- img.text((x2*cv.w+5,y2*cv.h+75+cv.pady), unicode(x2+(y2*4)+1), fill=RGB_GRAY,font=(u'Nokia Hindi S60',80,appuifw.STYLE_BOLD))
- def btn_rpl(target,btn_99,sq=RGB_WHITE,btn_label=RGB_GRAY):
- a,b,c,d=target
- return (a,b+cv.pady,c,d+cv.pady), (a+cv.padx,b+cv.pady), sq, btn_label
- #
- def full_bind():
- canvas.bind(key_codes.EButton1Up, up_event, ((0,0), (x_scr,720)))
- canvas.bind(key_codes.EButton1Down, dn_event, ((0,0), (x_scr,720)))
- canvas.bind(key_codes.EDrag, mv_event, ((0,0), (x_scr,720)))
- full_bind()
- cv_set()
- z_mainmenu()
- jxa,jya=70,350 ### <<< jpad xy axis point
- jxb,jyb=jxa+220,jya+220
- jx1,jy1=jxa+70,jya+70
- jx2,jy2=jxa+150,jya+150
- mv=0
- def mU(event):
- global mv
- if mv <> 1:
- mv=0
- def mD(event):
- global mv
- if mv <> 0:
- mv=1
- def mL(event):
- global mv
- if mv <> 3:
- mv=2
- def mR(event):
- global mv
- if mv <> 2:
- mv=3
- palref='''
- cv.Lcolor = (hh(cv.Lcolor[0],1), cv.Lcolor[1], cv.Lcolor[2])
- cv.Lcolor = (cv.Lcolor[0], hh(cv.Lcolor[1],1), cv.Lcolor[2])
- cv.Lcolor = (cv.Lcolor[0], cv.Lcolor[1], hh(cv.Lcolor[2],1))
- cv.Rcolor = (hh(cv.Rcolor[0],1), cv.Rcolor[1], cv.Rcolor[2])
- cv.Rcolor = (cv.Rcolor[0], hh(cv.Rcolor[1],1), cv.Rcolor[2])
- cv.Rcolor = (cv.Rcolor[0], cv.Rcolor[1], hh(cv.Rcolor[2],1))'''.split('\n')[1:]
- cv.active_palette=palref[0]
- if 1: # slider
- cv.incr=0
- cv.down=(0)
- increment=[100,50,10,1,0,-1,-10,-50,-100]
- if 1: # blend_colors
- def rgb_btns(x,y,x2=360,y2=50):
- xx=x2/3+1
- rgb=RGB_RED,RGB_GREEN,RGB_BLUE
- for i in xrange(3):
- xy2=(x+xx*i,y,x+xx*(i+1),y+y2)
- if cv.x:
- xv,yv=cv.x,cv.y
- if yv > y and yv < y+y2:
- if xv > xy2[0] and xv < xy2[2]:
- cv.active_palette=palref[palette+i]
- cv.RGB_mark=(x+xx*i,y,x+xx*i+10,y+10)
- img.rectangle((xy2), fill=rgb[i])
- #
- def mixColors(): ### ZZZ yellow + blue = (0,128,0)
- def rgbfix(R):
- aaa=(LC[R]*-1)+(RC[R])
- tmp=[0,1,2]; tmp.pop(R)
- bbb=LC[tmp[0]]+LC[tmp[1]]
- ccc=int((RC[tmp[0]]+RC[tmp[1]]))*-1
- tmp=abs(aaa+bbb+ccc)-637
- if tmp > 0: return tmp
- return 0
- LC,RC = cv.Lcolor,cv.Rcolor
- rgb = [(LC[0]+1)/2, (LC[1]+1)/2, (LC[2]+1)/2] # L
- rgb = [rgb[0]+((RC[0]+1)/2), rgb[1]+((RC[1]+1)/2), rgb[2]+((RC[2]+1)/2)] # R
- # color fix for mixing yellow and blue to correspondingly make green
- r,g,b = rgb[0]-rgbfix(2),rgb[1],rgb[2]-rgbfix(2)
- return ((hh(r),hh(g),hh(b)))
- #
- def rgb_box(box,x=10,y=210,w=60,h=60):
- i='LRM'.find(box)
- return ((x,y,350-x-w,y+h*3),(x+w,y+h,350-x,y+h*4),(x+w,y+h,350-x-w,y+h*3))[i]
- #
- def hh(limit,incr=0,min=None,max=None):
- if incr: limit+=cv.incr
- if not min:
- min,max=0,255
- elif not max:
- min,max=0,min
- if limit < min: limit=min
- if limit > max: limit=max
- return limit
- #
- cv.sVy=-1
- go='-'
- init=''
- skip=0
- while cv.go:
- go=cv.go
- if go and time.time() > skip:
- skip=time.time()+0.05
- if go[0] is '$': ### graphics mode
- try: sens.start_listening()
- except: pass
- if cv.mode is txt:
- cv.mode=canvas
- cv_set(1)
- else:
- try: sens.stop_listening()
- except: pass
- if cv.mode is canvas:
- cv.mode=txt
- cv_set()
- if go == '$SnakeGame':
- if init != go:
- init=cv.go
- step=10
- _ww=360/step
- bodycolor=(32,180,32)
- headcolor=(0,128,0)
- fieldcolor=(192,192,128)
- foodcolor=(255,0,0)
- padding=4
- deltas=((0,-1),(0,1),(-1,0),(1,0)) # up down left right
- y_max=(jya-2)/step
- defaultloc=w,h=[_ww/2,y_max/2]
- food_rnd=[]
- for x in range(4,_ww-4,10):
- for y in range(4,y_max-4,10):
- food_rnd.append((x,y))
- random.shuffle(food_rnd)
- defaultsnake=12
- arraydefault=[]
- for i in range(defaultsnake,0,-1): # body (excluding the snake head)
- arraydefault.append([w,h+i])
- loc='init'
- if loc is 'init':
- loc=w,h=defaultloc
- score=0
- mv=0
- foodloc=[5,5]
- sp=10000.00
- speed=1200.00
- snakelength=12
- fillarray=arraydefault[:]
- bind_jpad()
- p=0
- if loc == foodloc:
- p=1
- score+=1
- for z in food_rnd:
- a,b=food_rnd.pop()
- food_rnd.insert(random.randrange(1,9)*-1,[a,b])
- if a != loc[0] and b != loc[1]:
- if foodloc not in fillarray+loc:
- foodloc=[a,b]
- p=0
- break
- else:
- fillarray.pop(0)
- fillarray.append(loc)
- try:
- e32.ao_sleep(speed/sp)
- speed-=0.9
- except: pass
- w+=deltas[mv][0]
- h+=deltas[mv][1]
- loc=[w,h]
- if loc in fillarray or w<0 or h<2 or w>_ww-1 or h>=y_max or p:
- print 'end of game'
- loc='init'
- go=appuifw.query(u'Score: %d Speed: %d\nPlay Again?'%(score,1200-speed),'query')
- if not go:
- z_gfxmenu()
- else:
- if 1200-speed < 2: img.clear(RGB_BLACK)
- img.rectangle((0,20,360,y_max*step),fill=fieldcolor)
- square(foodloc,foodcolor)
- for bloc in fillarray:
- square(bloc,bodycolor)
- square(loc,headcolor)
- img.rectangle((0,0,360,20),fill=RGB_BLACK)
- img.text((2,14),u"Score: %d Speed: %d"%(score,1200-speed),(0,192,0))
- jpad()
- jpad_key()
- elif go in ['$3Dspin','$SpinCube']:
- if init != go:
- init=cv.go
- xm,ym,x2,y2=0,0,0,0
- halfResX=x_mid
- halfResY=y_mid
- distance=180
- PX=0
- PY=0
- PZ=200
- Size=10
- xyz=80
- VX = [-xyz, -xyz, -xyz, -xyz, xyz, xyz, xyz, xyz]
- VY = [-xyz, xyz, -xyz, xyz, -xyz, xyz, -xyz, xyz]
- VZ = [-xyz, -xyz, xyz, xyz, -xyz, -xyz, xyz, xyz]
- faces = [(0,1,3,2),(7,5,4,6),(0,2,6,4),(7,3,1,5),(7,3,2,6),(0,1,5,4)]
- colors = RGB_RED, RGB_ORANGE, RGB_YELLOW, RGB_GREEN, RGB_BLUE, RGB_VIOLET
- ANGLEX=0
- ANGLEY=0
- ANGLEZ=0
- xm,ym,zm=cv.xyz
- xm,ym=z_betw(xm,ym,(-20))
- ANGLEX+=ym
- ANGLEY+=xm
- rax=ANGLEX*math.pi/180
- ray=ANGLEY*math.pi/180
- raz=ANGLEZ*math.pi/180
- sinx=math.sin(rax)
- cosx=math.cos(rax)
- siny=math.sin(ray)
- cosy=math.cos(ray)
- sinz=math.sin(raz)
- cosz=math.cos(raz)
- """
- buf=graphics.Image.new((640,360)) ### not sure if this is the pythonic double buffer, but it works like a charm
- img=graphics.Image.new((640,360))
- """
- r1=[]
- r2=[]
- for n in range(8):
- ZX=VX[n]*cosz - VY[n]*sinz - VX[n]
- ZY=VX[n]*sinz + VY[n]*cosz - VY[n]
- YX=(VX[n]+ZX)*cosy - VZ[n]*siny - (VX[n]+ZX)
- YZ=(VX[n]+ZX)*siny + VZ[n]*cosy - VZ[n]
- XY=(VY[n]+ZY)*cosx - (VZ[n]+YZ)*sinx - (VY[n]+ZY)
- XZ=(VY[n]+ZY)*sinx + (VZ[n]+YZ)*cosx - (VZ[n]+YZ)
- XR=YX+ZX
- YR=ZY+XY
- ZR=XZ+YZ
- z=(VZ[n]+PZ+ZR)/distance
- x=((VX[n]+PX+XR)/z)+halfResX
- y=((VY[n]+PY+YR)/z)+halfResY
- z=int(Size/z)
- r1.append((x,y))
- r2.append(z)
- img.clear(RGB_LIGHTBLUE)
- if go == '$3Dspin':
- circle(PX+halfResX,PY+halfResY,Size*6,0xff0000)
- for n in range(len(r2)):
- x,y=r1[n]
- z=r2[n]
- circle(x,y,z,0x0000ff)
- else:
- t = []
- c = 0
- for f in faces:
- z1 = [r1[z] for z in f]
- z2 = [r2[z] for z in f]
- t.append([sum(z2),z1,colors[c]])
- c += 1
- z = False
- if time.time() % 2 > 1: z = True
- t.sort(reverse=z)
- for c,a,b in t:
- img.polygon(a,fill=b)
- img.text((20,40),'X:'+unicode(xm),0)
- img.text((20,80),'Y:'+unicode(ym),0)
- elif go == '$bouncySq':
- if init != go:
- init=cv.go
- sq=100
- dy=20
- dx=20
- if time.time() > cv.t:
- cv.x += dx
- cv.y += dy
- x,y=cv.x,cv.y
- if (x < -50)or(x > x_scr - 50):
- dx *= -1
- if (y < -50)or(y > 560 - 50): # y_scr
- dy *= -1
- cv.color=random.randrange(0xffffff)
- cv.t=time.time()+0.05
- img.rectangle((x,y,x+sq,y+sq), fill=cv.color)
- elif go == '$blend_colors':
- if init != go:
- init=cv.go
- cv.RGB_mark=(10,140,20,150)
- cv.x=1
- cv.Lcolor = (0,0,255)
- cv.Rcolor = (255,255,0)
- cv.color = cv.prev_color = (0,0,0)
- app.menu=[(u'<<<', z_pad_menu)]+rgb_menu
- if cv.prev_color <> cv.color:
- exec (cv.active_palette[:9]+'='+str(cv.color))
- cv.prev_color=cv.color
- cv.x=1
- if cv.x:
- img.clear(RGB_GRAY)
- slidebar()
- exec (cv.active_palette)
- cv.subcolor = mixColors()
- img.rectangle(((0,0,350,640)), fill=RGB_GRAY)
- img.rectangle(((0,0,340,92)), fill=RGB_WHITE)
- palette=0
- rgb_btns(10,140,280)
- palette=3
- rgb_btns(10,500,280)
- img.rectangle((cv.RGB_mark ), fill=RGB_WHITE)
- img.rectangle((rgb_box('L')), fill=cv.Lcolor)
- img.rectangle((rgb_box('R')), fill=cv.Rcolor)
- img.rectangle((rgb_box('L')), width=3, outline=RGB_BLACK)
- img.rectangle((rgb_box('R')), width=3, outline=RGB_BLACK)
- img.rectangle((rgb_box('M')), fill=cv.subcolor)
- img.text((10,36), u"RGB Result Of A And B:", fill = RGB_BLACK,font=(u'Nokia Hindi S60',29,STYLE_BOLD))
- img.text((10,68), u""+str(cv.subcolor), fill = RGB_BLACK,font=(u'Nokia Hindi S60',29,STYLE_BOLD))
- img.text((10,128), u"RGB Of A: "+str(cv.Lcolor), fill = RGB_BLACK,font=(u'Nokia Hindi S60',29,STYLE_BOLD))
- img.text((10,488), u"RGB Of B: "+str(cv.Rcolor), fill = RGB_BLACK,font=(u'Nokia Hindi S60',29,STYLE_BOLD))
- cv.x=0
- elif go == '$progress':
- if init != go:
- init=cv.go
- cv.bar=0
- if cv.bar < 1:
- img.clear(RGB_BLACK)
- ybarA=y_scr-60
- ybarB=ybarA+20
- cv.bar+=1
- i=cv.bar
- c=int(((255.0*2)/x_scr)*i)
- if not c > 255:
- # red marker
- color=(255,c,0)
- else:
- # green marker
- c -= 255
- color=(255-c,255,0)
- img.rectangle((i,ybarA,i+5,ybarB),fill=color)
- # frame
- img.rectangle((0,ybarA,x_scr,ybarB+2),0xffffff)
- if cv.bar > x_scr:
- cv.bar=0
- elif go == '$captureDemo':
- if init != go:
- init=cv.go
- cv.go='-'
- def saveImg():
- sCapture('demoImage')
- id=unicode(random.randint(100000,999999))
- print id
- mosaic()
- img.text((148,60),id,font=('dense',60))
- app.menu=[(u'Save Image',saveImg), g_menu]
- elif go == '$btn_matrix':
- if init != go:
- init=cv.go
- cv.x=0
- cv.y=0
- cv.padx,cv.pady=0,38
- cv.btn99=1
- cv.w,cv.h=90,90
- img.clear()
- btn_pad()
- draw(())
- e32.ao_sleep(0.1) ###
- bg=graphics.screenshot()
- a,b=cv.x,cv.y
- btn_=(a,b+cv.pady ,a+cv.w,b+cv.pady+cv.h)
- txt_=(a+cv.padx+5,b+cv.pady+75)
- sq_color, btn_label = RGB_GREEN, RGB_BLACK
- if cv.up < time.time():
- sq_color, btn_label = RGB_RED, RGB_WHITE
- img.blit(bg,source=(0,0))
- img.rectangle((btn_), fill=sq_color)
- img.text((txt_), unicode(cv.btn99), fill=btn_label,font=(u'Nokia Hindi S60',80,STYLE_BOLD))
- elif go == '$sketchpad': # ZZZ
- if init != go:
- init=cv.go
- thickness=10
- cv.color=RGB_RED
- cv.bg=RGB_WHITE
- img.clear(cv.bg)
- z_pad_menu()
- e32.ao_sleep(1)
- cv.jot=-99,-99,-99,-99
- cv.x,cv.y=-99,-99
- line_plot()
- img.line((cv.jot), cv.color, width=thickness)
- elif go == '$slider':
- if init != go:
- init=cv.go
- cv.tmp=max_rgb
- img.clear(RGB_GRAY)
- slidebar()
- if cv.down:
- msg=cv.down.pop()
- else: msg=0
- if cv.t < time.time():
- cv.tmp = portal(cv.tmp+msg, max_rgb)
- cv.t=time.time()+0.4
- rgb=rainbow[cv.tmp]
- img.rectangle((120,2,348,50), fill=rgb)
- img.text((10,44), u"Color:", fill = RGB_BLACK,font=(u'Nokia Hindi S60',40,STYLE_BOLD))
- img.text((10,90), unicode(rgb), fill = RGB_BLACK,font=(u'Nokia Hindi S60',30,STYLE_BOLD))
- img.text((10,130), unicode(msg), fill = RGB_BLACK,font=(u'Nokia Hindi S60',30,STYLE_BOLD))
- z_outline(254,100, (cv.sVy-4)*-1)
- elif go == '$star_5pt':
- if init != go:
- init=cv.go
- wait=time.time()+2
- img.clear((0,128,255))
- star=star_5pt(30,60,300)
- img.polygon((star), outline=RGB_GREEN, width=10, fill=RGB_YELLOW)
- if wait < time.time():
- wait=time.time()+1
- switch()
- if cv.sw:
- img.polygon((star), outline=RGB_PURPLE, width=9) # outline in pys60 does not round properly over 9 width
- img.blit(png, target=(100,120), mask=img_mask) ### b64_img
- elif go == '$pieslice':
- if init != go:
- init=cv.go
- tools=[u'x move',u'y move',u'x scale',u'y scale',u'x arm',u'y arm',u'x+y scale',u'seg rotate']
- tool_val=u'xp yp x2 y2 rx ry xyt rxy'.split()
- pdeg=[30,10,5,1,0,-1,-5,-10,-30]
- cv.xp,cv.yp=20,60; cv.rx,cv.ry=90,180
- cv.x2=cv.y2=300
- cv.xyt=cv.rxy=0
- cv.deg=4
- cv.up=-1
- cv.val='rx'
- app.menu=[(u'Select Tool',z_tools), g_menu]
- cv.deg=cv.y/yy2
- if time.time() > cv.up and cv.x > 300:
- pieplot()
- cv.up=time.time()+0.5
- img.clear(RGB_GRAY)
- slidebar()
- plots=(cv.xp, cv.yp, cv.xp+cv.x2+cv.xyt, cv.yp+cv.y2+cv.xyt)
- img.pieslice(plots, radian(180-cv.rx+cv.rxy),radian(180-cv.ry+cv.rxy), outline=RGB_BLUE,fill=RGB_YELLOW,width=10)
- cv.x=0
- cv.rx=cv.rx%360
- cv.ry=cv.ry%360
- img.text((10,20),u''+str(plots),RGB_WHITE)
- img.text((10,40),u''+str((cv.rx+cv.rxy,cv.ry+cv.rxy)),RGB_WHITE)
- elif go == '$sqdance':
- mosaic()
- elif go == '$xyzircle':
- img.clear(RGB_BLACK)
- radius=(cv.xyz[2]*-2)+120
- point_x=(-cv.xyz[0]+60) * x_scr / 120
- point_y=(cv.xyz[1]+60) * y_scr / 120
- circle(point_x,point_y,radius,(255,0,0))
- elif go == '$360arrow':
- if init != go:
- init=cv.go
- wait=t=0
- of_angles=600
- cv.zoom=29.0
- cv.angle=ang=0
- cv.xy=True
- cv.x=x_mid
- cv.y=y_mid-1
- pi2=math.pi*2
- img.clear(RGB_PURPLE)
- if cv.xy:
- cv.xy=False
- x,y=cv.x,cv.y
- cv.angle=int((math.atan2(x_mid-x,y-y_mid)+math.pi)/pi2*of_angles)
- wait=time.time()+0.8
- elif wait < time.time():
- wait=time.time()+0.1
- cv.angle=(cv.angle+3) % of_angles
- angle_rad=cv.angle * 2 * math.pi / of_angles
- rot_points=[]
- for point in arrow_points:
- x,y=point
- rot_x=math.cos(angle_rad) * x-math.sin(angle_rad) * y
- rot_y=math.sin(angle_rad) * x+math.cos(angle_rad) * y
- rot_x *= cv.zoom
- rot_y *= cv.zoom
- rot_x += x_mid
- rot_y += y_mid
- rot_points.append((rot_x, rot_y))
- if time.time() > t:
- t=time.time()+0.5
- ang=cv.angle
- img.polygon(rot_points, fill=RGB_YELLOW, width=2)
- img.text((10,50),u'%s'%(ang),fill=RGB_WHITE,font=(u'Nokia Hindi S60',50,STYLE_BOLD))
- img.text((10,560),u'%s'%('** Interactive **'),fill=RGB_WHITE,font=(u'Nokia Hindi S60',48,STYLE_BOLD))
- elif go == '$snowfall':
- if init != go:
- init=cv.go
- nflakes=120
- imgSnow=8
- moveX=range(nflakes)
- moveY=range(nflakes)
- XX=range(nflakes)
- YY=range(nflakes)
- for i in range(nflakes):
- moveY[i]=random.randint(5,20)
- dir=random.choice([-1,1])
- moveX[i]=dir*random.randint(1,3)
- XX[i]=random.randint(0,x_scr)
- YY[i]=random.randint(0,640)
- img.clear(0x000080)
- for i in range(nflakes):
- dir=random.choice([-1,1])
- moveX[i]=dir*moveX[i]
- XX[i]=XX[i]+moveX[i]
- YY[i]=YY[i]+moveY[i]
- if((XX[i]>x_scr)or(XX[i]<0)):
- moveX[i]=-moveX[i]
- if(YY[i]>640): # y_scr
- YY[i]=moveY[i]=random.randint(1,10)
- img.ellipse([(XX[i],YY[i]),(XX[i]+imgSnow,YY[i]+imgSnow)],RGB_WHITE,fill=RGB_WHITE)
- elif go == '$velocity':
- if init != go or max(cv.x,cv.y) < 0.6:
- init=cv.go
- oX = 30
- oY = 20
- cv.x=270
- cv.y=500
- img.clear((225,225,0))
- oX,oY,cv.x,cv.y=velo(oX,oY,cv.x,cv.y)
- img.ellipse((oX,oY,oX+40,oY+40),fill=(128,0,128))
- elif go == '$textscroll':
- if init != go:
- init=cv.go
- W,G,Y=((255,255,255),(0,255,0),(255,255,0))
- f1,f2=(u'Normal', 30), (u'Normal', 25)
- t1=u'Programming PyS60'
- t2=u'A Vertical Text Scroll Demo'
- print img.measure_text(t1,f1)
- print img.measure_text(t2,f2)
- a=img.measure_text(t1,f1)[0][2]
- b=img.measure_text(t2,f2)[0][2]
- i=0
- w,h=x_scr,y_scr
- distance=h/2-30
- t2h=(h-25)-i*5
- color=int(255+i*2)
- Bg=(0,color,255)
- img.clear(Bg)
- img.text((5,20),u'* Length: %s'% [t2h,distance], Y)
- img.text(((w-b)/2,(h-25)-i*5),t2,0,f2)
- img.text(((w-b)/2-2,(h-25-1)-i*5-2),t2,G,f2)
- img.text(((w-a)/2,35+i*5),t1,0,f1)
- img.text(((w-a)/2-2,35-1+i*5-2),t1,Y,f1)
- img.rectangle((0,0,w,h),Y)
- if t2h < distance:
- e32.ao_sleep(2)
- i=0
- i+=1
- elif go == '$text2fit':
- if init != go:
- init=cv.go
- app.menu=[(u'Rotate Display',z_ori), g_menu]
- img.clear(0x5555ff)
- o1st_entry='This is a "measure_text" wrap method example whereas...'
- o2nd_entry=['blahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblahblah',
- 'should','appear','segmented','to','stay','within','the','given','boundary.']
- #
- text2wrap('',o1st_entry)
- for divided in o2nd_entry:
- text2wrap(wrapped,divided)
- text2wrap(0xffffff)
- elif go == '-':
- pass
- draw(())
- cv.incr=0
- e32.ao_yield()
- try:
- sens.stop_listening()
- except: pass
- try:
- timer.cancel()
- except: pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement