blockly game

277 views
Skip to first unread message

Salman Butt

unread,
Nov 8, 2021, 5:24:45 AM11/8/21
to Blockly
Hi, i am making a blockly game for my website and i want to move a character via a move forward block but i am unable to do so.

it would be of great help if you can guide me on how i can connect my block to the game and move the character on a specific path.

thank you. 

Beka Westberg

unread,
Nov 8, 2021, 2:36:50 PM11/8/21
to blo...@googlegroups.com
Hello,

Have you checked out the getting started code lab? That should give you a good idea of how the different parts of Blockly connect together, and how the connect to other things. You can also check on the docs on code generation.

But without knowing more about your system (eg what library you're using for your characters, what language it is written in, etc) it's hard to give more specific advice :/

I hope that helps! If you have any further questions please reply!
--Beka

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/blockly/7bb3ff35-b8b3-46c5-ada0-8620a81ac38bn%40googlegroups.com.

Salman Butt

unread,
Nov 9, 2021, 2:24:35 AM11/9/21
to Blockly
My system is based on HTML,CSS & Javascript also using blockly library. I am making a educational website where students can build up their logic building and learn programing through a series of block based programming game, similar to blockly maze game, where there is a move forward block that moves the player forward.

I have made that block for my system but i am finding it troublesome to get it to move the character in any direction. 

Beka Westberg

unread,
Nov 10, 2021, 9:33:59 AM11/10/21
to blo...@googlegroups.com
That's cool! So when you generate code for your workspace, what result are you getting?

Best =)
--Beka

Santiago Hitta

unread,
Nov 10, 2021, 11:40:32 AM11/10/21
to Blockly
I am a newbie but as far as I know you can't "connect" blockly to the game. Blockly is just a set of libraries that help you set up the visual blocks editor, then you have to create blocks that make sense for your game, for example a "move forward" block. When you create a block you can specify the text that the block generates when you transform the workspace to code with  "workspaceToCode" function (search for generators in blockly documentation).
So what you can do is generate code from your blocks, or just plain text like "move_forward, move_left, move_forward, ...." and then you have to do something with this text (graphically moving your character accordingly), your game engine should be able to interpret this and move the character (this has nothing to do with blockly).

I'm on a similar boat, but in my case it's an educational robot, good luck with your endeavors!
Santiago.

Salman Butt

unread,
Nov 11, 2021, 2:57:28 AM11/11/21
to Blockly
Exactly I may have been mis-using the word "Connect" what i really meant was that how can i use my move forward block to actually move the player forward. I just dont know where to write that code or how to write it as i am aslo a newbie.

what i want is that when a user drags the block and drops it in workspace and then runs it, it should take the player forward.

Salman Butt

unread,
Nov 11, 2021, 2:59:55 AM11/11/21
to Blockly
Actually i am not getting any result because the block has no functionality yet, it is just a front-end, i am confused as to how to get the blocks working or produce a result which in my case would allow the user to move in any direction he wants

Beka Westberg

unread,
Nov 11, 2021, 8:17:52 AM11/11/21
to blo...@googlegroups.com
Hello again =)

As I recommended before, I think you should really check out the getting started codelab. Anything I would tell you here is already covered there, and it'll be a lot easier/faster to understand because it comes with examples :D It gives you a good understanding of how all of the parts of Blockly work together (ie front end and code generation). And it should put you well on your way to knowing how to connect your blocks to your game.

Once you've done that, if you have any further questions I'm happy to help =)

Best wishes,
Beka

Salman Butt

unread,
Nov 12, 2021, 5:40:41 AM11/12/21
to Blockly
Hi, yes i was able to generate code using my custom block i generated an alert to see if it worked and it did but after some time the alert stopped popping and i have no clue what happened even though i didnt change anything

Beka Westberg

unread,
Nov 12, 2021, 6:48:31 AM11/12/21
to blo...@googlegroups.com
Hmmm that's weird. Could you post the code you're using to generate code? Like you're block-code generator, and the code surrounding your call to Blockly.JavaScript.workspaceToCode()? That would really help with starting to debug =)

Best wishes,
--Beka

Salman Butt

unread,
Nov 13, 2021, 3:23:24 AM11/13/21
to Blockly
sure, also i want to know that my game logic is in a seperate file called maze.js and my blocks are in customblock.js, how do i reference my player who is in maze.js from customblock.js because that is where my blocks are defined and their code generators.
Capture.PNG
Capture1.PNG

Beka Westberg

unread,
Nov 13, 2021, 2:08:48 PM11/13/21
to blo...@googlegroups.com
Hello,

Well your basic code looks correct! Just make sure you're calling the runCode() function from somewhere.

Referencing code in other files depends a bit on how you're compressing your code, if you're using modules or just importing with script tags, etc. If you're just importing your files using script tags in your html (which is a good way to start) everything should exist in the global scope, so you should be able to access any code from any other file. I believe your `eval`ed code should be able to access anything as well =)

Best wishes,
--Beka

Salman Butt

unread,
Nov 15, 2021, 4:25:06 AM11/15/21
to Blockly
Hi,

Well i am calling the runCode() function but its not working anymore.

And yes i am using script tags in html, but how do i import a javascript file in another javascipt file in order to access the code

Beka Westberg

unread,
Nov 15, 2021, 1:30:03 PM11/15/21
to blo...@googlegroups.com
> Well I am calling the runCode() function but its not working anymore.

Have you added any logging to try to debug the problem? I would add some logs to your runCode function to see if  (1) it is actually being triggered, and (2) to see what code is actually being generated.

> And yes i am using script tags in html, but how do i import a javascript file in another javascipt file in order to access the code

I don't believe you should have to. Once both are loaded via script tags they exist in the same scope, and as such should have access to each other. Here's a stack overflow answer with some more info about importing in general.

Best wishes,
--Beka

Salman Butt

unread,
Nov 17, 2021, 2:23:39 AM11/17/21
to Blockly
Hi, 

so far my character is moving in every direction only when the arrow keys are pressed but what i want is it should move without keys being pressed through code block, for example, a move forward block should take the character forward from its initial position.

how do i achieve this without pressing any key, like what should be the function that does this.

Salman Butt

unread,
Nov 19, 2021, 5:47:11 AM11/19/21
to Blockly
Hello,

I have a question, how do i make my block execute one time ? Means if i am using a move forward block once it should move my character once, and if i am using move forward block twice or thrice then it should move my character accordingly.

right now my character moves one time per one block but as soon as i add multiple same blocks it gives error

Beka Westberg

unread,
Nov 19, 2021, 10:18:54 AM11/19/21
to blo...@googlegroups.com
Hello again =)

Could you post the generated code, and the error you are getting? The solution is going to depend on the library you're using.

Best wishes!
--Beka

Salman Butt

unread,
Nov 20, 2021, 2:40:41 AM11/20/21
to Blockly
Sure here you go

as you can see having two blocks of the same kind in workspace is giving this error.
Capture.PNG
Capture.PNG
Capture.PNG

Beka Westberg

unread,
Nov 20, 2021, 10:38:26 AM11/20/21
to blo...@googlegroups.com
Ah! It looks like it's because you don't have a semicolon and a new line in your generator. Like:
```
// The below line is changed
var code = 'moveRight();\n';
return code;
```

So right now, the two blocks together are generating the code string 'moveRight()moveRight()', which isn't valid javascript. For a good overview of how the code gen system works you can check out the generating code documentation.

I hope that helps!
--Beka

Salman Butt

unread,
Nov 22, 2021, 3:09:38 AM11/22/21
to Blockly
ahh yess it worked, i'm so happy that it did. 

Salman Butt

unread,
Nov 23, 2021, 3:13:46 AM11/23/21
to Blockly
Hi, 

I wanted to ask that how can i limit the use of my custom blocks, like what if i didnt wanted move forward block to be used more than two times per level or in a specific game level.

Beka Westberg

unread,
Nov 23, 2021, 2:48:12 PM11/23/21
to blo...@googlegroups.com
Hello again :D

It sounds like you're looking for the maxInstances configuration property!

Best,
Beka

Salman Butt

unread,
Nov 24, 2021, 2:58:53 AM11/24/21
to Blockly
Hi,

 i am attatching 2 videos below. 

first video shows how my game is actually working. When i add multiple lines of code it jumps my character to its final position based on the code compiled.

second one shows how i want it to work. I want it to execute multiple line of codes (like the one in first video) but move the character step by step (like in the second video)

How can i make my character move step by step as shown in the second video ? what should the runCode() function be in order to achieve this.
video1.mp4
video2.mp4

Beka Westberg

unread,
Nov 24, 2021, 4:00:54 PM11/24/21
to blo...@googlegroups.com
Hello,

It sounds like the issue is actually in your moveRight() (or equivalent) function, You'll want to modify it so that it includes a delay while your character is moving.

Best wishes =)
--Beka

fu6...@gmail.com

unread,
Nov 24, 2021, 10:46:17 PM11/24/21
to Blockly
Hi, 
If you want to include a delay function in your project...

<script>
const delay=(seconds)=>{return new Promise((resolve)=>{setTimeout(resolve,seconds*1000);});};
const play=async()=>{
  moveRight();
await delay(1);
  moveLeft();
};

startButton.onclick = function(){
   play(); 
};
</script>

Salman Butt

unread,
Nov 25, 2021, 3:51:57 AM11/25/21
to Blockly
Hi,

the picture below shows my moveRight() function. I tried adding delay but it didn't work for me. 

is there anything wrong with the function ? where should i add delay to make it work properly ?

pic1.PNG

fu6...@gmail.com

unread,
Nov 25, 2021, 6:11:56 AM11/25/21
to Blockly
Hi,
I tested the code and it worked well.


<html>
<head></head>
<body>
<img id="character" src="https://developers.google.com/blockly/images/logos/logo_vertical.svg" style="position:absolute;left:0px;top:50px">
<button id="start">START</button>

<script>
const start = document.getElementById("start");
const character = document.getElementById("character");

const delay=(seconds)=>{return new Promise((resolve)=>{setTimeout(resolve,seconds*1000);});};
const play=async()=>{
character.style.left = "0px";
while ( parseInt(character.style.left) < 500) {
character.style.left = parseInt(character.style.left) + 100;
await delay(1);
}
start.disabled = false;
};

start.onclick = function(){
start.disabled = true;
play(); 
};
</script>

</body>
</html>

Salman Butt

unread,
Nov 27, 2021, 2:02:28 AM11/27/21
to Blockly
Hi, 

i looked at your code snippet and tried to implement it in my project but i was unable to use it to effect.

Here is my playCode() function which is an onlick event that happens when user clicks Play Button. any suggestions where should the delay come and how?
playcode.PNG
Message has been deleted

fu6...@gmail.com

unread,
Nov 27, 2021, 11:04:55 AM11/27/21
to Blockly
Hi,

eval('const delay=(seconds)=>{return new Promise((resolve)=>{setTimeout(resolve,seconds*1000);});};const play=async()=>{' + code + '};play();');

Salman Butt

unread,
Nov 29, 2021, 2:01:44 AM11/29/21
to Blockly
Hello,

for some reason " eval('const delay=(seconds)=>{return new Promise((resolve)=>{setTimeout(resolve,seconds*1000);});};const play=async()=>{' + code + '};play();');"  is also not working. 

fu6...@gmail.com

unread,
Nov 29, 2021, 3:18:53 AM11/29/21
to Blockly
Hi, 
What's the Javascript error with your browser’s console?

Salman Butt

unread,
Nov 29, 2021, 3:58:50 AM11/29/21
to Blockly
well there is nothing wrong with the line of code so it doesnt have any error on console. 

it just doesnt delay the character and just jumps at the final position. I also tried to use  eval('setInterval(function(){' + code + '},1000)); but what this did was that it jumped to the final position and then there was a delay and then it repeated itself over and over again.

to make you understand better:

If i used moveRight(); three times, our final position would be x = 150, without using any delay or interval my character is jumping to final position which is 150 rather than moving like 50 then 100 and then 150. 

After using interval what it is doing is that it jumps to final position 150, it delays it for 1 sec and then again jumps to 300, then to 450 and then to 600 and so on. but what it should be doing is that it should move 50 then delay for a sec then 100 then a delay and then to 150 or whatever the number of times i am calling the moveRight(); function. 

fu6...@gmail.com

unread,
Nov 29, 2021, 12:36:54 PM11/29/21
to Blockly
Is there a function named "play()" in your code?

Please update the code and try again.
eval('const delay=(seconds)=>{return new Promise((resolve)=>{setTimeout(resolve,seconds*1000);});};const blockscode=async()=>{' + code + '}; blockscode();');


There is nothing wrong with the code.
<html>
<body>
<script>

var code =  'const delay=(seconds)=>{return new Promise((resolve)=>{setTimeout(resolve,seconds*1000);});};'+
'const play=async()=>{'+
' var character = document.createElement("div");'+
' character.style = "top: 0px;left: 0px; width: 100px;height: 100px;position: absolute;background-color: green;";'+
'       document.body.appendChild(character);'+
' for (var i=0;i<3;i++) {'+
' await delay(1);'+
' moveRight();'+
' }'+
' function moveRight() {'+
' character.style.left = parseInt(character.style.left) + 100;'+
' }'+
'};'+
'play();';

eval(code);

</script>
</body>
</html>

Salman Butt

unread,
Nov 30, 2021, 2:14:58 AM11/30/21
to Blockly
Yes, in order to run the code , i have created a button called play which has an onclick event called playCode();

i have attatched the picture below if the function.

playcode.PNG

Salman Butt

unread,
Nov 30, 2021, 3:14:43 AM11/30/21
to Blockly
How do i generate and run the code statement by statement ? i think this would solve my problem

Salman Butt

unread,
Dec 1, 2021, 11:13:14 AM12/1/21
to Blockly
Hello,

How do i generate and run code statement by statement which in this case is block by block? I used highlight block to highlight the blocks as they are executed and the only block that got highlighted was the last block in workspace.

 if i get to know how to generate and run code block by block it would mean a lot me.

Beka Westberg

unread,
Dec 1, 2021, 2:18:19 PM12/1/21
to blo...@googlegroups.com
Heyo,

There's info about this in the JSInterpreter docs =)

Best wishes,
--Bela

--
You received this message because you are subscribed to the Google Groups "Blockly" group.
To unsubscribe from this group and stop receiving emails from it, send an email to blockly+u...@googlegroups.com.

Salman Butt

unread,
Dec 2, 2021, 3:04:07 AM12/2/21
to Blockly
Hi @bekawe,

I did have a look at JS interpreter earlier, I followed the steps as it were mentioned and it just didn't work like it was supposed to. it kept on giving error on console : uncaught error moveRight() is not defined. 

Beka Westberg

unread,
Dec 3, 2021, 10:43:57 AM12/3/21
to blo...@googlegroups.com
Hello again!

It sounds like from that error that you need to define the moveRight() function in your interpreter. See the information here or here.

Best wishes,
Beka

Salman Butt

unread,
Dec 6, 2021, 4:10:31 AM12/6/21
to Blockly
Hi @bekawe,

i am finding it hard to define the moveRight() function in the interpreter. 

can you guide me what should the code be for the interpreter to work properly ?

Beka Westberg

unread,
Dec 6, 2021, 12:38:10 PM12/6/21
to blo...@googlegroups.com
 Sadly I cannot :/ It will depend on what library you're using, and what information that library expects.

However, if you post a stack trace for an error, or some more details bout the problem you're facing, then I (or someone else!) might be able to give you some advice =)

Best wishes,
--Beka

Salman Butt

unread,
Dec 27, 2021, 3:37:12 AM12/27/21
to Blockly
Hi @bekawe

it's been a while.... i have been working on the rest of my website for the past few weeks, now that i have completed it.. i am back at the same problem where i left it off...

i am attatching the screenshot of console... this error is generated although if i remove the js interpreter code and run it the way i was running it before this error is not generated but that way it also doesnt work the way it is supposed to...

i just want to know how can i execute the code one block at a time this is all i need and i am stuck at it for two weeks help would be appreciated..

Capture.PNG 

Beka Westberg

unread,
Dec 27, 2021, 7:40:34 AM12/27/21
to blo...@googlegroups.com
Hello,

I'm sorry, but there's not really enough info here for me to provide advice :/ If we had some info about the library you're using for moveRight, and what information it expects, someone here might be able to help you define it for the interpreter. But without that information, there's not any advice we can give :/

If you still want help, I would post:
1) What library you're using, or the source code you've written for moveRight().
2) The current definition of moveRight() you're giving to the interpreter, and any other versions you've tried.
3) The block-code generator for your moveRight() block.
4) The code you're using to generate your code-string.
5) The code-string that is currently being generated.  

Best wishes,
--Beka

Salman Butt

unread,
Dec 30, 2021, 3:24:08 AM12/30/21
to Blockly
Below are the code snippets for moveRight() function, block code for moveRight() and the playCode() where the code is generated.
as for the part where you said about the definition i am giving to interpreter i didn't understood what you meant by that but i have just imported the interpreter as it mentioned in the tutorial.


1. moveRight Code:
 moveRight.PNG
2. PlayCode() : 
playcode.PNG
3. Block code for moveRight()
blockCODE.PNG

Beka Westberg

unread,
Dec 30, 2021, 7:55:48 AM12/30/21
to blo...@googlegroups.com
Hello again =)

With regard to the definition you're giving to the interpreter, I referred to that in this post as well.

Basically, the JSInterpreter doesn't have access to any of the functions you've defined in your project (like moveRight()) unless you explicitly define them. This keeps malicious code from doing bad things.

So you need to explicitly define your moveRight() function like so:
```
function initApi(interpreter, globalObject) {
  // Provide a wrapper for moveRight() to the interpreter.
  var wrapper = function() {
    moveRight();
  };
  interpreter.setProperty(globalObject, 'moveRight',
      interpreter.createNativeFunction(wrapper));
}

// optional other code etc....

function playCode() {
  var click = new Audio("../Sounds/clickSound.wav");
  click.play();
  var code = Blockly.JavaScript.workspaceToCode(workspace);
  // This line changed!
  var myInterpreter = new Interpreter(code, initApi);
  myInterpreter.run();
}
```

Note that I can't test this because I don't have access to your system, so it may have bugs, but it should give you a good place to start =)

Best wishes,
--Beka

Salman Butt

unread,
Jan 3, 2022, 2:19:16 AMJan 3
to Blockly
Hi @bekawe 

This is all very new to me and i am confused as to where should i define this function.

should i define it in my maze.js file where i have coded all the game code and functions regarding movements or should i define it somewhere else ?

Salman Butt

unread,
Jan 3, 2022, 3:48:03 AMJan 3
to Blockly
Hi @bekawe 

i managed to write the api function also i wrote an async-function so that it executes one block at a time but it does not seem to work i am sending you the code to see where am i going wrong


var playButton = document.getElementById('playButton');
            var myInterpreter = null;
            var runner;
            function initApi(interpreter, globalObject) {
                    // Provide a wrapper for moveRight() to the interpreter.
                    var wrapper = function() {
                        moveRight();
                    };
                    interpreter.setProperty(globalObject, 'moveRight',
                    interpreter.createNativeFunction(wrapper));
                    var wrapper = function() {
                        moveDown();
                    };
                    interpreter.setProperty(globalObject, 'moveDown',
                    interpreter.createNativeFunction(wrapper));
                    var wrapper = function() {
                        moveLeft();
                    };
                    interpreter.setProperty(globalObject, 'moveLeft',
                    interpreter.createNativeFunction(wrapper));
                    var wrapper = function() {
                        moveUp();
                    };
                    interpreter.setProperty(globalObject, 'moveUp',
                    interpreter.createNativeFunction(wrapper));
                   
                     
                }
                var highlightPause = false;
                var latestCode ;
                function highlightBlock(id) {
                workspace.highlightBlock(id);
                highlightPause = true;
                }
                function resetStepUi(clearOutput) {
               // workspace.highlightBlock(null);
                //highlightPause = false;
                playButton.disabled = '';

                if (clearOutput) {
                    //alert('Program output:\n=================');
                }
                }
                function generateCodeAndLoadIntoInterpreter() {
                  //  Blockly.JavaScript.STATEMENT_PREFIX = 'highlightBlock(%1);\n';
                   // Blockly.JavaScript.addReservedWords('highlightBlock');
                    latestCode = Blockly.JavaScript.workspaceToCode(workspace);
                    resetStepUi(true);
                }
                function resetInterpreter() {
                    myInterpreter = null;
                    if (runner) {
                        clearTimeout(runner);
                        runner = null;
                    }
                }
               
                function playCode(){
                var click = new Audio("../Sounds/clickSound.wav");
                click.play();
                if(!myInterpreter){
                    resetStepUi(true);
                    playButton.disabled = 'disabled';
                    setTimeout(function() {            
                    myInterpreter = new Interpreter(latestCode, initApi);
                    runner = function() {
                    if (myInterpreter) {
                    var hasMore = myInterpreter.run();
                    if (hasMore) {
                    // Execution is currently blocked by some async call.
                    // Try again later.
                    setTimeout(runner, 10);
                    } else {
                    // Program is complete.
                    //alert('Execution complete');
                    resetInterpreter();
                    resetStepUi(true);
                    }    
                    }
                };
                runner();
                },1);
                return;
                }
             }

Beka Westberg

unread,
Jan 3, 2022, 6:53:35 AMJan 3
to blo...@googlegroups.com
Hello,

I'm not exactly sure what's going wrong, because it doesn't seem like there are any async functions in the code you posted. So I'm not exactly sure what you're trying to make asynchronous, or why :/

If you want to step the interpreter, I recommend going back to a basic implementation (with no asynchronicity) and starting with this code, which is the recommended way to handle stepping. Once you get that working you can start modifying it to have more advanced behavior (if you desire).

Best wishes,
--Beka

Salman Butt

unread,
Jan 10, 2022, 4:17:17 AM (7 days ago) Jan 10
to Blockly
Hi @bekawe 

How do make my toolbar specific to my game level.

For example if the game level is 1 i only want to show directional blocks and in game level 2 i want to add a for loop block. 

how do i achieve this?

Beka Westberg

unread,
Jan 10, 2022, 8:31:48 AM (7 days ago) Jan 10
to blo...@googlegroups.com
Hello,

The easiest thing to do is to define different toolboxes for each level, and then re-inject the workspace with the next toolbox whenever the level changes.

Something like:
```
function startLevel(level) {
  var toolbox = myGetToolboxFunction(level);
  workspace.dispose(); // dispose of your current workspace.
  workspace = Blockly.inject('blocklyDiv', {toolbox: toolbox}); // inject your new workspace
}

I hope that helps! If you have any further questions please reply!
--Beka
```

Reply all
Reply to author
Forward
0 new messages