Advertisement
Guest User

Untitled

a guest
Dec 6th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. from __future__ import division
  2. from scene import *
  3. from math import sqrt, pi
  4. import sound
  5.  
  6. button_pad = [['ans', 'pi', 'sqrt(', '%'],
  7. ['(', ')', '*', '/'],
  8. ['7', '8', '9', '-'],
  9. ['4', '5', '6', '+'],
  10. ['1', '2', '3', '='],
  11. ['0', '.', '<--', 'c']]
  12.  
  13. class Calculator (Scene):
  14. def setup(self):
  15. sound.set_volume(1)
  16. self.root_layer = Layer(self.bounds)
  17. self.user_input = {'ans':'', 'text':''}
  18. self.buttons = []
  19. self.create_buttons()
  20.  
  21. def create_buttons(self):
  22. width, height = self.size
  23. for y in xrange(len(button_pad)):
  24. for x in xrange(len(button_pad[y])):
  25. w = (width)/len(button_pad[y])
  26. h = (height-height/5)/len(button_pad)
  27. r = Rect(x * w, (height-height/5-h)-(y*h), w, h)
  28. button = Button(r, button_pad[y][x])
  29. if button_pad[y][x] != ' ':
  30. button.txt = button_pad[y][x]
  31. self.buttons.append(button)
  32. for button in self.buttons:
  33. button.touched = False
  34. self.root_layer.add_layer(button)
  35.  
  36. def calculate(self):
  37. try:
  38. self.user_input['ans'] = str(eval(self.user_input['text']))
  39. self.user_input['text'] = self.user_input['ans']
  40. except Exception as e:
  41. pass
  42.  
  43. def draw(self):
  44. width, height = self.size
  45. background(1,1,1)
  46. text(str(self.user_input['text']), x=width, y=height-height/6.7, font_size=height/20, alignment=4)
  47. for button in self.buttons:
  48. button.draw()
  49.  
  50. def touch_began(self, touch):
  51. for button in self.buttons:
  52. if touch.location in button.frame:
  53. button.touch_began(touch)
  54.  
  55. def touch_moved(self, touch):
  56. for button in self.buttons:
  57. button.touch_moved(touch)
  58.  
  59. def touch_ended(self, touch):
  60. for button in self.buttons:
  61. button.touch_ended(touch)
  62. if touch.location in button.frame:
  63. button.touched = True
  64. if button.touched:
  65. sound.play_effect('Click_1')
  66. if button.txt == 'c':
  67. self.user_input['text'] = ''
  68. elif button.txt == '<--':
  69. self.user_input['text'] = self.user_input['text'][:-1]
  70. elif button.txt == 'ans':
  71. self.user_input['text'] += self.user_input['ans']
  72. elif button.txt == '%':
  73. try:
  74. self.user_input['ans'] = str(eval(self.user_input['text'])/100)
  75. self.user_input['text'] = self.user_input['ans']
  76. except SyntaxError as e:
  77. pass
  78. elif button.txt == '=':
  79. self.calculate()
  80. else:
  81. try:
  82. self.user_input['text'] += button.txt
  83. except AttributeError:
  84. pass
  85. button.touched = False
  86.  
  87. run(Calculator())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement