Skip to content

Commit 2bafb88

Browse files
committed
EventBlocks: Implement broadcast blocks
* non-atomic scripts are not supported yet, so "broadcast and wait" will be implemented later
1 parent 2481e94 commit 2bafb88

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

src/blocks/eventblocks.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,55 @@
11
// SPDX-License-Identifier: Apache-2.0
22

33
#include "eventblocks.h"
4+
#include "../engine/compiler.h"
5+
#include "../scratch/broadcast.h"
46

57
using namespace libscratchcpp;
68

79
EventBlocks::EventBlocks()
810
{
11+
// Blocks
912
addHatBlock("event_whenflagclicked");
13+
addCompileFunction("event_broadcast", &compileBroadcast);
14+
addCompileFunction("event_whenbroadcastreceived", &compileWhenBroadcastReceived);
15+
16+
// Inputs
17+
addInput("BROADCAST_INPUT", BROADCAST_INPUT);
18+
19+
// Fields
20+
addField("BROADCAST_OPTION", BROADCAST_OPTION);
1021
}
1122

1223
std::string EventBlocks::name() const
1324
{
1425
return "Events";
1526
}
27+
28+
void EventBlocks::compileBroadcast(Compiler *compiler)
29+
{
30+
auto input = compiler->input(BROADCAST_INPUT);
31+
compiler->addInput(input);
32+
if (input->type() != Input::Type::ObscuredShadow) {
33+
input->primaryValue()->setValue(compiler->engine()->findBroadcast(input->primaryValue()->value().toString()));
34+
compiler->addFunctionCall(&broadcastByIndex);
35+
} else
36+
compiler->addFunctionCall(&broadcast);
37+
}
38+
39+
void EventBlocks::compileWhenBroadcastReceived(Compiler *compiler)
40+
{
41+
auto broadcast = std::static_pointer_cast<Broadcast>(compiler->field(BROADCAST_OPTION)->valuePtr());
42+
compiler->engine()->addBroadcastScript(compiler->block(), broadcast);
43+
}
44+
45+
unsigned int EventBlocks::broadcast(VirtualMachine *vm)
46+
{
47+
vm->engine()->broadcast(vm->engine()->findBroadcast(vm->getInput(0, 1)->toString()));
48+
return 1;
49+
}
50+
51+
unsigned int EventBlocks::broadcastByIndex(VirtualMachine *vm)
52+
{
53+
vm->engine()->broadcast(vm->getInput(0, 1)->toLong());
54+
return 1;
55+
}

src/blocks/eventblocks.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,26 @@ namespace libscratchcpp
1111
class LIBSCRATCHCPP_EXPORT EventBlocks : public IBlockSection
1212
{
1313
public:
14+
enum Inputs
15+
{
16+
BROADCAST_INPUT
17+
};
18+
19+
enum Fields
20+
{
21+
BROADCAST_OPTION
22+
};
23+
1424
EventBlocks();
1525

1626
std::string name() const override;
27+
28+
static void compileBroadcast(Compiler *compiler);
29+
static void compileWhenBroadcastReceived(Compiler *compiler);
30+
31+
private:
32+
static unsigned int broadcast(VirtualMachine *vm);
33+
static unsigned int broadcastByIndex(VirtualMachine *vm);
1734
};
1835

1936
} // namespace libscratchcpp

0 commit comments

Comments
 (0)