# SPDX-License-Identifier: LGPL-3.0-or-later # Copyright (C) 2020 Johannes Wache """Calculator application This is a simple calculator app that uses the build-in eval() function to compute the solution. """ import wasp, fonts # 2-bit RLE, generated from res/calc.png, 413 bytes calc = ( b'\x02' b'`@' b'(@\x03P?\x0eV?\x08[?\x04_?\x01b' b' 200): # undo button pressed if (self.output != ""): self.output = self.output[:-1] else: indices = [(event[2]// 48)-1,event[1]//47] # Error handling for touching at the border if (indices[0]>3): indices[0] = 3 if (indices[1]>4): indices[1] = 4 button_pressed = self.fields[indices[0]][indices[1]] if (button_pressed == "C"): self.output = "" elif (button_pressed == "="): self.output = self.calculate(self.output) else: self.output += button_pressed self.display_output() def _draw(self): draw = wasp.watch.drawable draw.fill() # Make grid: draw.set_color(wasp.system.theme('accent-lo')) for i in range(4): # horizontal lines draw.line(x0=0,y0=(i+1)*47,x1=240,y1=(i+1)*47) # vertical lines draw.line(x0=(i+1)*47,y0=47,x1=(i+1)*47,y1=240) # Draw button label: draw.set_color(wasp.system.theme('accent-hi')) for x in range(5): if x == 3: draw.set_color(wasp.system.theme('accent-mid')) for y in range(4): label = self.fields[y][x] if (x == 0): draw.string(label, x*47+14, y*47+60) else: draw.string(label, x*47+16, y*47+60) draw.string("<", 215, 10) draw.set_color(wasp.system.theme('accent-hi')) def display_output(self): wasp.watch.drawable.fill(x=2,y=2,w=170,h=40) if (self.output != ""): if len(self.output) >= 10: wasp.watch.drawable.string(self.output[len(self.output)-9:], 6, 14, width=170) else: wasp.watch.drawable.string(self.output, 6, 14, width=170) def calculate(self,s): equation = s # Normal calculator stuff for i in range(len(s)): if (s[i] =="^"): equation = s[:i] + "**"+s[i+1:] elif (s[i] == ":"): equation = s[:i] + "/"+s[i+1:] try: result = eval(equation) except: # Error result = "" return str(result)