将self.label.element.text = '轮到玩家' 位置调整后,可正常显示'轮到玩家'、‘轮到电脑’
但要在‘电脑胜利‘后 加上 return后才会显示‘电脑胜利‘,否则继续显示'轮到玩家' # coding: utf-8
import cocos
from cocos.scene import Scene
from cocos.director import director
import pyglet
import random
class GameLayer(cocos.layer.ColorLayer):
def __init__(self):
super().__init__(128, 128, 128, 128)
cocos.layer.Layer.is_event_handler = True
self.label = cocos.text.Label('轮到玩家', font_name='kaiti', font_size=30, color=(255, 0, 0, 255),
anchor_x="center",
anchor_y="center")
self.label.position = (320, 80)
self.add(self.label)
self.label1 = cocos.text.Label('', font_name='kaiti', font_size=30, color=(0, 0, 255, 255),
anchor_x="center",
anchor_y="center")
self.label1.position = (320, 380)
self.add(self.label1)
self.player = 0
self.blocks = []
for i in range(18):
bo = cocos.sprite.Sprite('block.png')
bo.position = 40 + 32 * i, 240
self.add(bo)
self.blocks.append(bo)
def on_mouse_press(self, x, y, button, modifiers):
if self.player == 0:
if button == pyglet.window.mouse.LEFT:
x = min(round((x - 40) / 32), len(self.blocks) - 1)
ss = len(self.blocks) - x
if ss > 0:
for i in range(ss):
bo = self.blocks.pop()
self.remove(bo)
self.label1.element.text = f"玩家取数:{ss}"
print(f"玩家取数:{ss}")
print('len(self.blocks)=', len(self.blocks))
if len(self.blocks) == 0:
self.label.element.text = '玩家胜利!'
return
self.player = 1
self.label.element.text = '轮到电脑'
self.do(cocos.actions.Delay(random.randint(2, 5)) + cocos.actions.CallFunc(self.computer_move))
def computer_move(self):
k = random.randint(1, min(3, len(self.blocks)))
for i in range(k):
bo = self.blocks.pop()
self.remove(bo)
self.label1.element.text = f'电脑取数:{k}'
print("电脑取数:" + str(k))
print('len(self.blocks)=', len(self.blocks))
if len(self.blocks) == 0:
self.label.element.text = '电脑胜利!'
return
self.label.element.text = '轮到玩家'
self.player = 0
def main():
director.init()
scene = Scene()
scene.add(GameLayer(), z=0)
director.run(scene)
if __name__ == "__main__":
main()
|