summaryrefslogtreecommitdiff
path: root/wasp
diff options
context:
space:
mode:
authorDaniel Thompson <daniel@redfelineninja.org.uk>2020-12-28 14:41:37 (GMT)
committerDaniel Thompson <daniel@redfelineninja.org.uk>2020-12-29 08:59:53 (GMT)
commit21210c5c072ddd174f91bd7c80a1b2a00cb39bf3 (patch)
treefd39500b36e15bb8db7f2fc2515579e0716d44db /wasp
parente570bf4f262180f09d8b6bdef393d529c567b238 (diff)
apps: calc: Rewrite the display and calculation engine
Currently calculations such as 22/7 do not work correctly on the simulator (which uses double precision floating point). Fix this by explicitly truncating the strings when needed. Additionally the current calculate() method has some problems when the calculation cannot be evaluated since it will needlessly clear out the calculation. Push calculate (and the exception handling) into the caller and report errors using the vibration motor instead. Finally we rename display_output() to the more idiomatic _update(). Signed-off-by: Daniel Thompson <daniel@redfelineninja.org.uk>
Diffstat (limited to 'wasp')
-rw-r--r--wasp/apps/calc.py34
1 files changed, 8 insertions, 26 deletions
diff --git a/wasp/apps/calc.py b/wasp/apps/calc.py
index 5860b31..e5ea04d 100644
--- a/wasp/apps/calc.py
+++ b/wasp/apps/calc.py
@@ -74,10 +74,13 @@ class CalculatorApp():
if (button_pressed == "C"):
self.output = ""
elif (button_pressed == "="):
- self.output = self.calculate(self.output)
+ try:
+ self.output = str(eval(self.output.replace('^', '**')))[:12]
+ except:
+ wasp.watch.vibrator.pulse()
else:
self.output += button_pressed
- self.display_output()
+ self._update()
def _draw(self):
draw = wasp.watch.drawable
@@ -106,27 +109,6 @@ class CalculatorApp():
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) \ No newline at end of file
+ def _update(self):
+ output = self.output if len(self.output) < 12 else self.output[len(self.output)-12:]
+ wasp.watch.drawable.string(output, 0, 14, width=200, right=True)