How to use switch case statement in blockly.

1,085 views
Skip to first unread message

SUCHITRA GIRI

unread,
Aug 12, 2021, 9:03:41 AM8/12/21
to Blockly
Hello Everyone,

I am very new to Blockly from 2 days I am exploring it for my project work.
Actually, I want to use a switch case statement which can take input from the dropdown as question when the user selects the particular option and return the output as specified  ans.


Thanks in Advance:)
Please help!!

SUCHITRA GIRI

unread,
Aug 12, 2021, 9:09:06 AM8/12/21
to Blockly
Screenshot (318).png

Beka Westberg

unread,
Aug 12, 2021, 9:53:18 AM8/12/21
to blo...@googlegroups.com
Hello,

We seem to get this question quite frequently :D Is this part of a course? I just ask because the core team would love to get in contact with the professor/organization to hear more about how they're using Blockly =)

With regard to your question, please refer to the previous answers on this topic:

Best wishes,
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/27bb5f5e-67b6-4867-b048-d1af566aecfan%40googlegroups.com.

SUCHITRA GIRI

unread,
Aug 12, 2021, 1:01:08 PM8/12/21
to Blockly
Thanks for the help. Btw it is not a part of the course, it just a task assigned to us with certain time duration!

After examining the links still I am stuck with this part, actually getting undefined instead of specified answer.
Where I did mistake in my code:(

$(document).ready(function () {
  $("#runBtn").click(function () {
    runcode();
  });
  $("#resetBtn").click(function () {
    reset();
  });
});
//statement block
Blockly.Blocks['Bot'] = {
  init: function() {
    this.appendStatementInput("NAME")
        .setCheck(null)
        .appendField("Bot");
    this.setPreviousStatement(true, null);
    this.setColour(230);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};

//dropdown block
Blockly.Blocks['Ask_me_a_question'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("Ask me a question?")
        .appendField(new Blockly.FieldDropdown([["What is the date today?","Date"], ["What is the time now?","Time"], ["How are you?","Feel"], ["What is javascript?","JavaScript"], ["What is your name?","Name"]]), "OPTIONS");
    this.setPreviousStatement(true, null);
    this.setColour(290);
 this.setTooltip("");
 this.setHelpUrl("");
  }
};

// Blockly.JavaScript["Bot"] = function (block) {
//   var text_input = block.getFieldValue("OPTIONS");

//   var code = `
//  var inputTextValue = "${text_input}";
//   `;
//   return code;
// };

Blockly.JavaScript['Ask_me_a_question'] = function(block) {
  return block.getFieldValue('OPTIONS')
};

Blockly.JavaScript['Bot'] = function(block) {
  //var statements_bot = Blockly.JavaScript.statementToCode(block, 'NAME');
  var dropdown_ask_me_a_question = Blockly.JavaScript.statementToCode(block, 'OPTIONS');
  //console.log(dropdown_ask_me_a_question);
  var question;
  switch(dropdown_ask_me_a_question) {
    case "Date":
      var today = new Date();
      question = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();
      break;
    case "Time":
      var today = new Date();
      question = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + " IST";
      break;
    case "Feel":
      question = "I am good, How are you?";
      break;
    case "JavaScript":
      question = "JavaScript is a text-based programming language used both on the client-side and server-side that allows you to make web pages interactive";
      break;
    case "Name":
      question = "I am a bot created by Suchitra using blockly";
      break;
}
  var code = `
  var inputTextValue = "${question}";
  `;
  return code;
};

var workspace = Blockly.inject("blocklyDiv", {
  media: "assets/media/",
  toolbox: document.getElementById("toolbox"),
});

function redrawUi() {
  if (typeof inputTextValue !== "undefined") {
    $("#inputBox").text(inputTextValue);
  } else {
    $("#inputBox").text("");
  }
}

function runcode() {
  // Generate JavaScript code and run it.
  var geval = eval;
  try {
    geval(Blockly.JavaScript.workspaceToCode(workspace));
  } catch (e) {
    console.error(e);
  }
  redrawUi();
}

function reset() {
  delete inputTextValue;
  redrawUi();
}

Screenshot (320).png

Beka Westberg

unread,
Aug 12, 2021, 4:41:00 PM8/12/21
to blo...@googlegroups.com
Hmm it doesn't look like you should be getting a value of undefined. Especially when you explicitly protect against that in your redrawUi function.

I would start by adding some logging and seeing what that tells you. Eg:
```
function runcode() {
  // Generate JavaScript code and run it.
  var geval = eval;
  try {
    // These lines changed!
    var code = Blockly.JavaScript.workspaceToCode(workspace);
    console.log(code);
    geval(code);
  } catch (e) {
    console.error(e);
  }
  redrawUi();
}
```
And:
```
Blockly.JavaScript['Bot'] = function(block) {
  // Etc... other code.

  var code = `
  var inputTextValue = "${question}";
  `;
  // This line changed!
  console.log(code);
  return code;
};
```
Or you could try to step through it using chrome's built-in breakpoints.

Hopefully that will clarify where the issue is!
--Beka

SUCHITRA GIRI

unread,
Aug 13, 2021, 11:28:13 AM8/13/21
to Blockly
Hey, 
I am so sorry still I couldn't resolve my issue:(

See, I have two blocks, 1st one is the statement input name "Bot" block and 2nd one is dropdown block name "Ask_me_a_question".
It should work like this way:
when I drag the parent block (Bot) then drag (Ask_me_a_question) into "Bot" block and  choose the option from dropdown it should be displayed the specified answer  in the UI. For the ans purpose, I have used switch case statement.

So, I think my mistake is in the part of JavaScript generator code, I explored a lot about it that how to get options from dropdown list when we click and display the specified ans on the ui.

Now I think I messed up the code:( 
But still look at once!!
```
Blockly.JavaScript['Bot'] = function(block) {
  var dropdown_ask_me_a_question = Blockly.JavaScript.statementToCode(block, 'OPTIONS');
  //var statements_bot = Blockly.JavaScript.statementToCode(block, 'NAME');
  //var dropdown_ask_me_a_question = Blockly.JavaScript.statementToCode(block, 'OPTIONS');
  //var dropdown_ask_me_a_question = block.getFieldValue('OPTIONS');
  console.log(dropdown_ask_me_a_question);
  var question;
  switch(dropdown_ask_me_a_question) {
    case "Date":
      var today = new Date();
      question = today.getDate()+'/'+(today.getMonth()+1)+'/'+today.getFullYear();
      break;
    case "Time":
      var today = new Date();
      question = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + " IST";
      break;
    case "Feel":
      question = "I am good, How are you?";
      break;
    case "JavaScript":
      question = "JavaScript is a text-based programming language used both on the client-side and server-side that allows you to make web pages interactive";
      break;
    case "Name":
      question = "I am a bot created by Suchitra using blockly";
      break;
}

  var code = `
  var inputTextValue = "${question}";
  `;
  console.log(code);
  return code;
};

var workspace = Blockly.inject("blocklyDiv", {
  media: "assets/media/",
  toolbox: document.getElementById("toolbox"),
});

function redrawUi() {
  if (typeof inputTextValue !== "undefined") {
    $("#inputBox").text(inputTextValue);
  } else {
    $("#inputBox").text("");
  }
}

// function runcode() {
//   // Generate JavaScript code and run it.
//   var geval = eval;
//   console.log(geval);
//   try {
//     geval(Blockly.JavaScript.workspaceToCode(workspace));
//   } catch (e) {
//     console.error(e);
//   }
//   redrawUi();
// }

function runcode() {
  // Generate JavaScript code and run it.
  var geval = eval;
  try {
    // These lines changed!
    var code = Blockly.JavaScript.workspaceToCode(workspace);
    console.log(code);
    geval(code);
  } catch (e) {
    console.error(e);
  }
  redrawUi();
}

function reset() {
  delete inputTextValue;
  redrawUi();
}
```
Please help!



Beka Westberg

unread,
Aug 13, 2021, 11:47:21 AM8/13/21
to blo...@googlegroups.com
Hello :D

It would really help to know the results you got from your logging. If you try to generate your code, what output are you seeing in the browser console?

Best,
Beka

SUCHITRA GIRI

unread,
Aug 13, 2021, 12:37:12 PM8/13/21
to blo...@googlegroups.com
You received this message because you are subscribed to a topic in the Google Groups "Blockly" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/blockly/ewXFprydsJo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to blockly+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/blockly/CAHpwHMbHqamWehDWOaQihvZk7G%2B3PUnPrtvTLsUy1Wi3mKbE2w%40mail.gmail.com.
Screenshot (324).png
Screenshot (323).png

Jason Schanker

unread,
Aug 13, 2021, 4:08:15 PM8/13/21
to Blockly
Hi,

The current issue is that your Bot block has a statement input named NAME (this.appendStatementInput("NAME")), not 'OPTIONS' so Blockly.JavaScript.statementToCode(block, 'OPTIONS') returns the empty string since it has no such statement input.  That's why you're seeing the empty string (a blank line) for the first line that's getting logged (console.log(dropdown_ask_me_a_question)) and why question will not be assigned any value (i.e., it will be undefined).  So the generated code is var inputTextValue = "undefined".  Note that since you are assigning inputTextValue to the *string literal* "undefined", typeof inputTextValue will be string which is why inputTextValue !== "undefined" will evaluate to true and consequently, why the text input shows the text undefined instead of going to the else statement where it would instead show the empty string.

If you instead assigned dropdown_ask_me_a_question to Blockly.JavaScript.statementToCode(block, 'NAME'); as you seemed to do at first, then dropdown_ask_me_a_question will be assigned the generated code from the connected 'Ask_me_a_question' block, which would correctly be the OPTIONS field value of the 'Ask_me_a_question' block BUT IT WOULD BE PADDED BY INITIAL SPACING because it's a statement input (See: https://github.com/google/blockly/blob/master/core/generator.js#L316) .  Therefore, none of the cases would match (e.g., it would compare "   Feel" with 2 leading spaces to "Feel", which would be false).  So one way to deal with this would be to instead use switch(dropdown_ask_me_a_question.trim()) to remove the leading spaces.  However, if you instead used blockToCode passing the block connected to the NAME input as follows, no indentation would be added and then you can leave it as you had before:

var dropdown_ask_me_a_question = Blockly.JavaScript.blockToCode(block.getInputTargetBlock('NAME'));

Note however, when the question block is not connected to the Bot block, you'd still get undefined in the text input.  Probably the best way to fix this would be to add a default statement to the end of the body of your case statement:

    default:
      question = "";

You could alternatively change typeof inputTextValue !== "undefined" to inputTextValue !== "undefined" (removing the typeof), but this seems more fragile.

One more note is that when the blocks are disconnected, your code would have an extra string being generated such as "Feel" that would be part of the code.  To avoid this you could change your "Ask_me_a_question" generator to only produce the field value of OPTIONS as code when its previous connection isn't null (and an empty string otherwise) as follows:

Blockly.JavaScript['Ask_me_a_question'] = function(block) {
  return this.getPreviousBlock() ? block.getFieldValue('OPTIONS') : "";
};

Best,
Jason

SUCHITRA GIRI

unread,
Aug 14, 2021, 4:02:18 AM8/14/21
to blo...@googlegroups.com
Thank you so much Jason for the detailed and intuitive explanation. I am glad that I joined the mailing list and have great community members.

My issue is resolved:)


Reply all
Reply to author
Forward
0 new messages