import cocos
from cocos.layer import Layer, ColorLayer
from cocos.text import Label
from cocos.menu import MenuItem, Menu
from pyglet import font
# 颜色配置(使用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):
def __init__(self):
super().__init__()
self.current_input = "0"
self.create_display()
self.create_buttons()
self.schedule(self.update_display)
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[:3], # 确保使用RGB格式
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 = [
['C', '(', ')', '/'],
['7', '8', '9', '*'],
['4', '5', '6', '-'],
['1', '2', '3', '+'],
['0', '.', '=', '']
]
# 创建按钮
start_x, start_y = 40, 380
button_size = 80
for row_idx, row in enumerate(button_layout):
for col_idx, label in enumerate(row):
if not label:
continue
# 按钮背景
bg_color = BUTTON_COLOR
if label in ['+', '-', '*', '/', '=']:
bg_color = OPERATOR_COLOR
elif label == 'C':
bg_color = CLEAR_COLOR
btn_bg = ColorLayer(*bg_color, 255)
btn_bg.width = button_size
btn_bg.height = button_size
btn_bg.position = (start_x + col_idx*100, start_y - row_idx*100)
self.add(btn_bg)
item = MenuItem(
label,
self.on_button_pressed,
font_name="Arial",
font_size=24,
color=TEXT_COLOR[:3] # 确保使用RGB格式
)
item.x = start_x + col_idx*100 + 40
item.y = start_y - row_idx*100 + 40
self.add(item)
def on_button_pressed(self, 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
def update_display(self, dt):
self.display_label.element.text = self.current_input[:12]
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)