Python: some practice, questions and #%§' - Printable Version +- HP Forums (https://www.hpmuseum.org/forum) +-- Forum: HP Calculators (and very old HP Computers) (/forum-3.html) +--- Forum: HP Prime (/forum-5.html) +--- Thread: Python: some practice, questions and #%§' (/thread-16915.html) Python: some practice, questions and #%§' - Guenter Schink - 05-12-2021 09:10 PM Now with Python I was curious what it is after all. So I decided to play a little bit around. You're of course invited to play with me. Subject is: drawing the Mandelbrot set WARNING If you play with this, your Prime will reboot when you access an APP, definitely. BUT this is not a great deal, you'll only lose the stack. To prevent from this, switch the Prime on and off. this will preserve the stack, but won't prevent from a reboot. That's what the "#%§'" is about. Really annoying. I hope the moderators leave this here, because it's not meant as a great program but a playing field, to explore and exploit the capabilities of the implementation of Python on the Prime. Specifically LISTS, SETS and Drawing. Copy this code to a PPL-program. The name doesn't matter. Look at the top of the code for input syntax. Code: ```#PYTHON name from hpprime import * from math import * import sys from urandom import * """Get arguments Input format at HOME            [[n]n]n.[m|0[a]]  n  maximum depth of the Iteration m    Magnitude of colors i.e. number            of colors =mag^3 default is 4,            giving 64 colors a    how to plot   0:      rolling from left to right   1:      roll by tiles   2:      kind of dust   3:      another dust, more random takes longer """ """parsing input. Bit tricky,   and  needed due to binary  character. N >= 1000 results in error """ inp=sys.argv[0] inp=float(inp) inp=modf(inp) depth=int(max(inp[1],10)) inp=round(inp[0],2)*10 inp=modf(inp) mag=(4 if (inp[1] <= 1 or inp[1]>6)\     else int(inp[1])) inp=round(inp[0],2)*10 inp=modf(inp) art=int(inp[1]) # set black and white black=0x000000 white=0xffffff """ put a pixel at x,y with color  determined by the iteration at this  specific point   """  def paint(x9,y9):    z = complex(0,0)    c = complex(3*x9/319-2*1,\        -2.25*y9/239+1.125)    i = 0    while (i < depth) and abs(z) < 2:      i = i + 1      z = z**2+c    rgb = pal[i%len(pal)]    if i==depth :      pixon(0,x9,y9,0)    else:      pixon(0,x9,y9,rgb)    # When finished display a small  # white square top-left def finish():   fillrect(0,0,0,10,10,white,white) #clear screen black fillrect(0,0,0,320,240,black,black) """   create color palette with    "LIST Comprehension"  at first for     calculate how many elements    for each of red, green, blue.   then for  combine each of the    elements of one color with each    element of the other colors.    Thus number of colors = mag^3 """ elem=(255/(mag-1)) pal0=[(int(iter*elem)) for iter \       in range(mag)] #pal0.reverse pal=[(b*256**2 + g*256 + r ) \       for b in pal0 \       for g in pal0 \       for r in pal0] pal.sort() # screen filled from top to bottom,  # left to right, the simplest way if art==0:   for x in range(320):     for y in range(240):       paint(x,y)   finish()    # Pixel put pseudo randomly,takes  # much longer. Picture completed  # by using  after this loop if art==3:   for i in range(40**3):    paint(randint(0,320),randint(0,240))   art=1 # Tiles are distributed randomly and  # then filled randomly very nice,  if art==1:  i=0  Tiles=[]  for TileX in range(0,320,32):    for TileY in range(0,240,16):        Tiles.insert(randint(0,len(Tiles)),(TileX,TileY))            Pixels=[]  for PixelX in range(32):    for PixelY in range(16):        Pixels.insert(randint(0,len(Pixels)),(PixelX,PixelY))    P0=0  for PixX in range(32):    for PixY in range(16):      px,py=Pixels[P0]     P0+=1;      #on the virt. prime uncomment next line     #eval("wait(0.01")     for t0 in range(len(Tiles)):      tx,ty=Tiles[t0]       paint(tx+px,ty+py)      #paint(Tiles[t0]  finish()    # Pixels distributed by tiles. You  # won't see a difference to  # on the Virtual Prime) if art==2:   t0=10   tx=int(320/t0)   ty=int(240/t0)       y1=0   for x1 in range(tx,321,tx):     for y1 in range(ty,241,ty):       for x in range(x1-tx,x1):         # on the virtual Prime uncomment the next line          #eval("Wait(0.001)")         for y in range(y1-ty,y1):          paint(x,y)   finish() eval("WAIT") #end EXPORT mandel(a) BEGIN   PYTHON(name, a); END;``` This program lives as a Python script in a PPL environment in HOME. It features 4 different kinds of output and 6 different depth of color. And it is really fast. I'm a complete newbie to Python and inexperienced in programming, so bear with me if I talk about the obvious, but I hope to get some input as well. Ref: #%§' The reboot problem needs to be solved. has been reported sys.argv errors out when value is >999 Ref: Questions, has anybody managed to: get something from the mouse get something from the keyboard read the value of a pixel Next step should be zooming. Therefore MOUSE or KEY events would be very helpful. Günter RE: Python: some practice, questions and #%§' - jkor - 05-15-2021 01:04 AM I seem to have some success with the following snippet in PPL: Code: ``` #PYTHON EXPORT mktest() from hpprime import * from math import * # haven't found terminal screen clear yet print("""Perform one of the following: 1. position mouse pointer on screen and then double-touch 2. click a calculator key 3. press 'On' to exit""") lastm,lastk=0,0 while 1:   # gets 2nd pair of coords (2-touch)   # move mouse ptr around screen and double touch   m=mouse()[1]   k=keyboard()   if len(m)>0 and m!=lastm:     print('2-touch y= '+str(m[1]))   if k>0 and k!=lastk:     print('key= '+str(int(log2(k))))   lastm=m   lastk=k #end``` The snippet prints the y-coord of the mouse pointer for a two-point touch, or the key code for a clicked calculator key and can be exited by pressing 'On'. Both mouse() and keyboard() don't seem to accept any parameters. As noted in one of your previous posts, I haven't had any luck making a Python script file work (using the More>Files>New Program feature of the Editor). Thanks for your invaluable contributions to the knowledge base. Your posted have been very helpful in trying to figure things out. Jim RE: Python: some practice, questions and #%§' - Guenter Schink - 05-15-2021 11:05 PM (05-15-2021 01:04 AM)jkor Wrote:  I seem to have some success with the following snippet in PPL: Code: ``` ...``` The snippet prints the y-coord of the mouse pointer for a two-point touch, or the key code for a clicked calculator key and can be exited by pressing 'On'. Both mouse() and keyboard() don't seem to accept any parameters. As noted in one of your previous posts, I haven't had any luck making a Python script file work (using the More>Files>New Program feature of the Editor). Thanks for your invaluable contributions to the knowledge base. Your posted have been very helpful in trying to figure things out. Jim Thanks for your comment, and the code snipped, that helped a lot. Now I have a routine for mouse, at least on the virtual Prime, that seems to work reliably and easy to use. Checking out on the real Prime will follow. For now I call it a day, although I should call it a night at 1 hour past midnight here. Code: ```from hpprime import * # So far only tested on the Virtual. # Left mouse button returns first tuple # Right mouse button returns second tuple # initiate Maus as 1 tuple of 2 tuples # and wait for a mouse event # Maus is the German word for mouse :-) Maus=((),()) while Maus==((),()):   Maus=mouse() # clear terminal Window as it fits, guess that's what you were looking for eval("PRINT") #split Maus into two tuples Maus1 and Maus2 # in Python it's easy this way (Maus1),(Maus2)=Maus #let's see what we got print("Maus1:",Maus1,"Maus2:",Maus2) #before doing something with first tuple,  #check  it's not empty if Maus1>():  (Maus1x,Maus1y)=Maus1  print("Maus1x:",Maus1x,"Maus1y:",Maus1y) #before doing something with second tuple,  #check  it's not empty if Maus2>():   (Maus2x,Maus2y)=Maus2   print("Maus2x:",Maus2x,"Maus2y:",Maus2y)     #end EXPORT test7(a) BEGIN   PYTHON(name1, a); END;``` We'll continue to play with Python, no? Günter RE: Python: some practice, questions and #%§' - jkor - 05-16-2021 12:06 AM Yes we definitely should continue. Like you, I am relatively new to Python, picking it up about a week ago. So, I see this as a golden learning opportunity, through actually trying to make things work. I can't wait for the stable release, having many PPL programs that I am looking forward to revamping. Playing with the Prime has become an somewhat of an obsession, currently . Of particular interest is coming up with generic framework for a GUI (cascading menus, dialog boxes and the like). Again, thank you for the inspiration provided, and many thanks to the HP Prime team for a compelling product that ensures I don't get too much (enough) sleep. Until the next hurtle, very best, Jim RE: Python: some practice, questions and #%§' - Guenter Schink - 05-16-2021 10:17 AM Another trap: in your snipped:Quote: print('key= '+str(int(log2(k)))) doesn't always return the correct key code due to the binary nature of floats. This can be avoided by replacing by . In this case even doesn't need a second argument. For positive numbers it works like from the math module. Quote: print('key= '+str(round(log2(k)))) Things like this could drive you crazy. Günter