import cocos
from cocos.layer import ColorLayer, Layer
from cocos.text import Label
from cocos.menu import Menu, MenuItem
# 颜色配置(使用RGB三元组)
DISPLAY_COLOR = (40, 40, 40) # 显示屏背景
BUTTON_COLOR = (80, 80, 80) # 普通按钮
OPERATOR_COLOR = (255, 165, 0) # 运算符按钮
CLEAR_COLOR = (255, 69, 0) # 清除按钮
TEXT_COLOR = (255, 255, 255) # 文字颜色(RGB格式)
class Calculator(Layer):
is_event_handler = True # Enable this layer to receive events
def __init__(self):
super(Calculator, self).__init__()
self.current_input = "0"
self.create_display()
self.create_buttons()
def create_display(self):
# 显示屏背景
display_bg = ColorLayer(*DISPLAY_COLOR, 255)
display_bg.width = 400
display_bg.height = 100
display_bg.position = (40, 450)
self.add(display_bg)
self.display_label = Label(
"0",
font_name="Arial",
font_size=48,
color=(TEXT_COLOR + (255,)),
anchor_x="right",
anchor_y="center",
width=380,
multiline=False,
align="right"
)
self.display_label.position = (430, 500)
self.add(self.display_label)
def create_buttons(self):
button_layout = [
['7', '8', '9', '/'],
['4', '5', '6', '*'],
['1', '2', '3', '-'],
['C', '0', '=', '+']
]
buttons = []
operators = {'/', '*', '-', '+'}
start_x, start_y = 60, 300
button_size = 80
for row_idx, row in enumerate(button_layout):
for col_idx, label in enumerate(row):
x = start_x + col_idx * 100
y = start_y - row_idx * 100
color = OPERATOR_COLOR if label in operators else BUTTON_COLOR
if label == "C":
color = CLEAR_COLOR
btn_bg = ColorLayer(*color, 255)
btn_bg.width = button_size
btn_bg.height = button_size
btn_bg.position = (x, y)
self.add(btn_bg)
item = MenuItem(label, self.on_button_pressed)
item.position = (x + button_size / 2, y + button_size / 2)
buttons.append(item)
menu = Menu()
menu.create_menu(buttons, layout_strategy=None)
self.add(menu)
def on_button_pressed(self, item):
label = item.label
if label == 'C':
self.current_input = "0"
elif label == '=':
try:
self.current_input = str(eval(self.current_input))
except:
self.current_input = "Error"
else:
if self.current_input == "0":
self.current_input = label
else:
self.current_input += label
self.update_display()
def update_display(self):
self.display_label.element.text = self.current_input
if __name__ == "__main__":
cocos.director.director.init(width=480, height=600, caption="Simple Calculator", resizable=False)
scene = cocos.scene.Scene(Calculator())
cocos.director.director.run(scene)