The Art of Random Cityscapes in MakeCode for Minecraft

 

This MakeCode for Minecraft program is called “Cityscape.” Zillions of cityscapes can be generated by customizing input parameters. A few cityscapes generated by t he program are shown in this blog post.
tall city

ice city.png

dark down

Idea

I had the idea for generating random cityscapes as I was developing The Art of Random Walks in MakeCode for Minecraft.  Essentially, the idea was that instead of placing blocks at each random step, the program would place a building built with a random block with random height, width and depth (depth here means how far back). The program would then move to another  location a random distance from the prior building. It would then place another building, and so on, until the specified number of buildings were placed. The random selections would all be within player specified limits. Optionally, the program would place “ground” of a player-specified block within a rectangle around the city.

city 200 bldg

Customizing Cityscape

Cityscape’s has many options. Such flexibility is marvelous for an experienced player, but can be confusing for a first timer. This is a challenge frequently faced  by software designers. In this case, the solution was to have a default for every option so that a player need only type “city” in the command window to generate a beautiful, probably unique, cityscape. Typing “city” again, generates another city that likely will appear very different from the first, and so on, until the player decides that something a little different would be nice — time to start exploring the options.

Cityscape’s options are specified as follows:

  1. As the values of the parameters in the functions “default_params” and “custom_params.”
  2. As the three arguments to the on-chat “city” command, which starts the program.
  3. As the blocks specified in the block arrays.

Default and Custom Parameter Functions.

Both the default and custom parameter values, which are set in their respective functions,  can be changed.  I suggest having the values in “default_params” be the ones you use most often and the params in “custom_params” be experimental. I also save sets of favorite values by copying them to a scratch area of the program so that I can drag them in and out of the parameter functions.

Cityscape parameters include the following (in the order shown in the param functions):

  • the number of buildings
  • the block array to be used for buildings
  • whether or not to do a compass
  • the ground block to be used in the rectangle surrounding the city
  • the block to be used under the ground block. This is useful if a glass block is used for the ground.
  • foundation block to be used under each building. This is replaced if a new ground is laid.
  • whether a random block is to be used for the ground
  • whether all buildings are to be cubes
  • lower and upper limits for building height
  • lower and upper limits for building width
  • lower and upper limits for building depth (how far back)
  • the maximum distance from one building to another

parms code.png

In the left cityscape below,  all dimensions are set to 1 with a move range of 3. This cityscape illustrates the random walk from the origin, which is indicated by the clear glass block above the lower right TNT block. The right cityscape below has a move range of 0, which means all buildings, which have varying dimensions,  are  built in the same place.

A Function to Verify Parameters

The function “verify_params” checks the parameters for correct values. If one is wrong, for example, a negative value for width, the program will say a message and stop. The last verification in the routine is to check whether the fill command volume limit of 32,768 will be exceeded for any building. This is done by calculating the largest possible volume,  which is calculated as the product of the three variables height limit, width limit  and depth limit.

verify code

color sym city

Blocks from Which Buildings Are Constructed

Building blocks are  specified by the variable “which_array” in the parameter routines above. The values can be 1, 2, 3 or 4. This value can be overridden by an  on-chat “city” command argument. The values 1, 2, 3 or 4 specify, in order, one of the following arrays:

  1. jewel_array,
  2. black_array,
  3. other_array and
  4. an array constructed from all three of the above arrays.

Each of these arrays can have any number of blocks and can contain any type of Minecraft block from which a building can be constructed. The names of the arrays cannot be changed unless they are also changed in the code that reference the arrays. The variable “this_array” is set to the array that is selected by the “which_array” parameter or argument. For building construction, blocks are randomly selected from “this_array.”

array code

on-chat “city” Command Arguments

The on-chat “city” command (see below)  has three arguments.

city args

If num1 is 0, default_params are used. If 1, custom_params are used. A valid num2 overrides the number of buildings provided in default or custom parameters. A valid num3 overrides the array of blocks to be used.

blue city

Using Cityscape

The on-chat “city” command is the main command. It generates a cityscape according to the previously set parameters and arrays, which may have been overridden by the command’s arguments (see above).

The on-chat “view” command moves through views of the city from 20 different vantage points, including 4 sides, 4 corners, over the origin and over center of rectangle. For each of these  2 different heights are used. The on-chat command “s” will stop movement at the current view. The argument num1 to view is the number of seconds to pause at each view, default 3.

The Code

The left third of Cityscape’s code has to do with the inputs that tailor the program to generate an near-endless variety of cityscapes. The middle third, which is launched with on-chat “city” command,  is the guts of the program and actually constructs the city building by building within the bounds of the input parameters. The right third of the program is primarily that launched by the “view” command, which assists the player in looking at the city from various vantage points.

All Code

on-chat Command “city” Starts the Program

The on-chat “city” command defines the main flow of the program in the following steps:

  1. Processes arguments to
    • choose between default and custom parameters,
    • optionally, override number of buildings and
    • optionally, override the array of blocks used in building construction.
  2. Initializes variables, sets origin and, optionally, launches an on-chat to draw a compass.
  3. Uses a repeat block for the following:
    • calls “do_one_building” function to construct a building and
    • calls “get_new_rposition” to pick random position for next building.
  4. Adjusts height of origin marker to be taller than highest building and moves player to above origin.
  5. Calls “build_ground” to create rectangle at ground level.

city code

Function to Do One Building

The “do_one_building” function does the following:

  1. picks random height, width and depth.
  2. calls function to pick block to be used.
  3. uses fill block to create hollow building.
  4. uses fill block to lay foundation of building.
  5. calls function to update minimum and maximum X and Z.

do one bldg code

Function to Get New Random Position

The position of the next building is selected as a random position between the current building’s position plus {minus the move range, 0, minus the move range} and the current building’s position plus {move range, 0, move range}. Simply put, the new building can be any direction up to a distance of  move range from the current position.

get new position code

Function to Pick the Block for Building Construction

The “pick_block” function chooses a random block from the “this_array” array. It also call the function “give_flint_if_needed” to give the player a flint-and-stone item if the block is TNT.

pick block code

Function to Give Player Flint and Steel Item If Block Is TNT

This function gives the player a flint-and-stone item if “this_block” is TNT and the item had not been previously given in this run of “city.” This function is called when a new building block is chosen and also when the foundation block is selected.

give flint

blown up

Functions to Initialize and Finalize Origin Marker and Player Position

Origin marker is a tower of clear glass blocks that is a bit higher than the tallest building. It marks the place of the first building. I use it to view the direction that the random sequence of buildings developed. Initially, the marker is at the maximum height that a building can be. Finally, it is adjusted to be just above the actual highest building. The on-chat “no” command erases the origin marker. This is useful for those situations where the origin marker detracts from the view of the city.

origin marker

Functions to Keep Track of Minimum and Maximum X and Z coordinates

Maximum and minimum X and Z coordinates are updated with each building so that, in the end, the ground can be placed under the city with the same distances from buildings on all sides. Most of the view points are on the perimeter of the rectangle surrounding the city.

min max XZ code

Function to Do Ground Rectangle

This function uses the minimum and maximum X and Z coordinates to define a rectangle. Within that rectangle, grass is replaced by a block, which is either a random block or a block supplied as a parameter in either default or custom parameters functions. An underground block is also placed below the ground. This is useful when the ground is transparent.

do ground code

on-chat “view” Command Helps the Player in Appreciating Her Handiwork

After a cityscape is generated, the player may want to look at it from various vantage points because the view can be very different from various directions. Moving around a city can be tedious; therefore, automation to the rescue. The on-chat command “view” moves the player through 20 positions, pausing to allow time to view each one. The number of seconds to pause is specified to num1, which defaults to 3 seconds. If a particular view is spectacular, an “s” on-chat command stops movement to the next view.

view code

Function to Calculate the Positions for Viewing a Cityscape

The ground plane positions from with views are provided are shown by the drawing below. Minimum and maximum X and Z are used to do the calculation in the function that initializes the view positions array.

drawing directions

calc view positions

Note that, as far as I know,  arrays of positions are an documented feature of MakeCode for Minecraft.

Other Code Used by Cityscape

Two other pieces of code are used by Cityscape:

  • compass and
  • a function to convert a number on-chat argument  to a Boolean array.

This version of compass is particularly fast and flexible. It will be described in my next block post.

compass

This handy little function was motivated by the fact I needed to use several Booleans arguments to an on-chat command. It will be documented in a soon-to-come blog post.

bits

flat world

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

up black city.png

Get the Code

Cityscape code is shared on Code Connection at this URL

https://makecode.com/_MXigqm5HTdev

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

gray city.png

red on black down

black on cyan city

down-pink.png

down green city.png

down city.png

This slideshow requires JavaScript.

Monster Showtime in MakeCode for Minecraft

 

The video above runs Monster Showtime from beginning to end. In the Code section below is a video that describes the MakeCode for Minecraft code that creates the show.

makecode-for-minecraft-monster-showtime-blaze.png

Watching the Show

The on-chat-command “run” starts the show. The players then needs to do three things:

  1. Move the player to look to the east. If you don’t know which direction east is, you can use a sunflower because it always faces east. Or, when the show starts, just scan around until you see the stage.
  2. If needed, press the F1 key so that the screen log does not show — All those teleport messages can be annoying.
  3. Sit back and watch the show — no hands needed.

makecode-for-minecraft-monster-showtime-zombie-villager.png

Monster Showtime, after a flashy introduction, cycles though all monster types. For each monster type, it spawns  three on the stage with the monster’s name displayed above. The program delays a bit before going on to the next monster type so that the player can contemplate the monster’s characteristics. About half way through the viewing of a monster, a skylight is opened in the stage roof so that the player can see some combustible monster’s catch fire.

makecode-for-minecraft-monster-showtime-skeleton-on-fire.png

Challenges Solved

I did a prototype of this program a few months ago, but the following challenges kept me from completing it until now:

  1. Arrays, especially text arrays, sometimes go crazy. For example, in an array of numbers, sometimes, for no apparent reason, MakeCode forgets that the variable is an array and thinks that it is just a single number. It gives a message that “a number[] cannot be assigned to a number” — like I didn’t know. Eventually, I found a workaround.
  2. The MakeCode print block is so slow that most people would give up waiting for monster names to print. Eventually, I found a way to dramatically speed up printing.

The Code

All the Monster Showtime code is shown in the screenshot  below. On the left are the initialization routines. Right of initialization is   “run,” which along with “do_one_monster” below it, defines the flow of the program. Moving right, are the routines  that flash the initial display of “MONSTER SHOWTIME” and build the stage. Next right  is the code that displays “THE END” and spawns a crowd of monsters to take a final bow. On the far right, are the fast print routines that make each monster’s type appear almost instantly above the stage.

MakeCode for Minecraft All Code

The On Start Block Initializes Variables

It is good practice to initialize variables that never change in the on-start block, as this code does below.

on start codeThe two arrays shown below must be the same length and the names in the same order as the corresponding monsters.

arrays code

Run Starts the Program and Defines the Main Loop

The on-chat command “run” does the following:

  1. Calls a function to teleport the player to a new location and set the variable “origin,” which is used as the reference position in all building and spawning.
  2. Checks to be sure that the monster array and monster name arrays are the same length; and, if not, displays an error message and exits. If OK, continues with next  step.
  3. Calls a function to flash “MONSTER” and “SHOWTIME” on the stage in oscillating colors. Another function displays a suggestion message to the player.
  4. Sets “print_block,” which is used by “print_fast,” to orange concrete, the color used to print the monster names.
  5. Loops through all monsters doing the following for each:
    • Teleport player to new location and set “origin.”
    • Set the global variable “idx_global” to the loop index. “idx_global” specifies the monster being processed.
    • Calls the function “do_one_monster.”
  6. After all monsters are processed, teleports player to new location and runs “end” function.

do one

flash monster code

error code

Do One Monster

For each monster, the “do_one_monster” function does the following:

  1. Places a sunflower near the player to verify that the stage is being built to the east of the player.
  2. Calls the function “make_stage” to do just that.
  3. Sets “print_text” to the name of this monster, which is selected from the “monster_names” array at index “idx_global.”
  4. Calculates “Z_coordinate” such that the monster name will be centered when displayed.
  5. Sets the print position for the name using “Z_coordinate” calculated above and  X and Y determined by trial-and-error.
  6. Calls “print_fast” to print the monsters name.
  7. Teleports the player to “origin” to move close to the stage for a good view of the monsters as they are spawned.
  8. Spawns three of this monster in a row on the stage. Of course, the monsters will not stay where they are spawned very long, but some longer than others.
  9. Pauses, then teleports back one block at a time using a loop. This makes the player slowly back up for a full view of the stage.
  10. Pauses, then builds a skylight in the stage roof so that sunlight shines on most of  the stage. Some monsters will catch on fire in sunlight.
  11. Pauses for more monster viewing, then exits.

do one

Build the Stage — Fast

The stage is built using several on-chat-commands, instead of functions, so that several  elements of the stage will be built at the same time. This makes stage construction much faster. Speed is desirable because a new stage is generated for each monster.

stage code

The function “make_stage_roof_window” is called about half way through displaying each monster to allow sunlight, which makes some monsters catch fire. The on-chat-command “stage_test” is a tool for building a single stage for debugging purposes.

The “stage_test” function is included to enable testing “make_stage” independent of the program.

Print Fast

“print_fast” is speedy because all characters of the text string are printed at the same time, not one by one sequentially as they are using the normal MakeCode print block. To accomplish this, each character position, say 0 to 20, in a string must have its own print_n on-chat command. This code takes a lot of room. The good news is that all the routines are exactly the same except for the name. For example, the code shown below will print up to 21 characters using “print_0,” “print_1,” and so on to “print_20.”

The function “print_fast” loops through each character of “print_text” with the loop index “print_index” indicating the character to be printed. It calls a different print_n function for each character. It also supplies an argument, which is the number of the character to be printed.

“print_fast” uses some cleverness to be sure that each “print_n” routine does not share variables that might be changed by another “print_n” running at the same time.

    1. “print_text” is a global variable that is never changed by a “print_n” routine.
    2. The argument “arg_print_index” is unique to each “print_n” because arguments are local to an on-chat. This argument selects the character from “print_text” that is to be printed by this print_n. For example, “print_2” prints the third character of “print_text,” which is “i”. “arg_print_index” is also used to calculate the position at which the character will be printed relative to “print_position,” a global variable that is not changed within the “print_n” routines.

print code

The End

At the end of the show, the monsters all come out to take a final bow.

makecode-for-minecraft-monster-showtime-the-end.png

The end function does the following:

  1. Prints “THE END” in the sky.
  2. Spawns all monsters in front of the player.

An on-chat command “end_test” enables testing the function without running the entire program.

End Code

Code Requires a Flat World

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

MakeCode for Minecraft Monster Showtime Vex

Get the Code

Monster Showtime code is shared on Code Connection at this URL

https://makecode.com/_h7bEY4TVifUK

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

Coordinates Game in MakeCode for Minecraft

 

begin game

Early in the game, most of the spaces on the grid are white. The green blocks indicate that the player got the coordinates of that position correct while the red blocks were incorrect. The center cyan block is the origin (center) of the grid, which is coordinate { 0  0 }.

finish green

At the end of a game, all blocks are green except those that were missed by the player. The percentage score is shown above the grid.

Coordinates Game is a companion to Coordinates Tutor, which is described in Coordinates Tutor in MakeCode for Minecraft. Coordinates Game enables a player to demonstrate their knowledge of coordinates.

How to Play

To play Coordinates Game, type “run” in the command window. The program will display one of the windows below. It will oscillate between the two windows reminding the player that X and Z correspond to east and south, respectively.

The game will then display { X Z } coordinates, such as {  1  -1 } on the left below. The player’s challenge is to break the white block in the grid corresponding to the displayed coordinates. If the player gets it right, a green block will replace the broken white block at the coordinate {  1  -1 }. If the player gets it wrong, a red block will replace the broken one. The program then displays the next set of coordinates for the player until all positions  in the grid have been used. At this time, the score is displayed as a percentage of correct answers (see above).

The game loop, simply put is:

  • the program displays a position as a set of coordinates,
  • the player breaks the white glass block at that position in the grid,
  • the program replaces the broken white block with either green or red blocks corresponding to right or wrong, respectively, and
  • the program displays the next position coordinates, and so on until all positions have been used.

Code Design

The big-picture design of the program is depicted below. The program first initializes, which includes building the grid and compass as well as creating a list of all positions on the grid. At first, all these positions are available to be displayed to a player. As each position is used, it is removed from the list. When there are no positions remaining, the game is over.

drawing

In operation,  after the program posts position coordinates,  nothing happens until the player breaks a block, which generates an on-broken event. The position of the broken block is compared against the displayed position using a sneaky method that I will describe later. If correct, the broken block and the block under it are replaced by green ones. If wrong, a red block is placed at the correct position with a red block under it, which indicates that the player got that one wrong. The broken block is repaired by replacing the white glass.

The Code

The first version of Coordinates Game code was completed in July. I didn’t like it because on rare occasions weird things occurred that I didn’t understand. For example,

  1. Sometimes. towards the end of the game the on-white-glass event stopped firing and would not restart. No matter how much glass I broke, no event. I put many say-blocks in the program so that I was absolutely sure there was no explainable reason for this to occur. I still don’t know why this happened and I could not reproduce the problem outside my program.
  2. My original program did repairs asynchronously in a forever loop. On rare occasions, this interfered with game play. I eventually understood how this rare thing happened. To fix it,  I had to give up asynchronous repairs. This turned out wonderfully, as the resulting code is totally reliable and much faster. How great is that?

I changed and changed and changed the design as well as then code to make it more understandable and reliable. I did thought experiments, had nightmares and awakened with new ideas that sometimes worked and sometimes didn’t. I trashed large sections of the code and started over again and again. My 6-weeks on-and-off effort was rewarded. Now the program has no anomalies, at least none that I have found after playing the game many times.

The figure below shows all the code for the Coordinates Game. Starting on the left is the initialization code. Towards the middle is the code that posts coordinates. Moving right is the on-broken events that triggers processing of a player’s answer. To the right is the code that makes repairs.

all code with labels

run on-chat command

This on-chat command is how the player starts the program. It does the following:

  1. Moves the player to a new, pristine location and sets the origin variable.
  2. Calculates the opposing corners of the grid as { -5 -5 } to { +5 +5 } that will be used for building the grid.
  3. Sets the print position where the coordinates and score sill be displayed.
  4. Launches the on-chat command brackets to print the brackets within which coordinates will be displayed. Because it launches an on-chat command instead of using a function, the program continues while the brackets are being drawn.
  5. Launches the on-chat command compass to draw a simple compass while the program continues to run.
  6. Calls the function canvas to build a grid.
  7. Initializes the counts of right and wrong answer to zero.
  8. Calls a function to flash between { X Z } and { E S } to remind the player that X is East and Z is South.
  9. Calls a function to initialize the available-positions-list.
  10. Launches an on-chat command to post the first position coordinates. Because of using the on-chat command instead of a function, after launching the on-chat, the program continues and exits.
  11. At this point nothing happens until the player breaks a block, hopefully, corresponding to the correct answer.

run code

Display  New Position Coordinates

This on-chat command run asynchronously and performs the following functions:

  1. Calls a function to get a random grid position from those that have not been used; that is, is available.
  2. If all position have been used, the on-chat command end is launched to post the score and end the game.
  3. If an unused position was found, the answer position is calculated as origin, which is  the position at the center of the grid, plus the available position, which is a position of the form { X 0 Z }, where X and Z are each a  value between -5 and +5. This is more fully explained in the section following this one. The variables answer_X and answer_Z are the X and Z coordinates or the answer position, respectively.
  4. Prepares the coordinates for printing in the correct location by putting a space in front positive coordinates. The space occupies the space that is occupied by a minus sign in negative coordinates.
  5. Increments nPrints, which is used to select the color of block used to print the next coordinates. The color oscillates so that there is no confusion during the time when one coordinate is being replaced with a new one.
  6. Launches the two on-chat commands that prints the two coordinates at the same time. If this were done with a single print, it would be irritatingly slow.

postNewCoordinate

Available-Positions List

The list of available positions is key for keeping track of which grid positions have not yet been used. There were other more convoluted ways of doing this, but using a position list — an undocumented feature in MakeCode for Minecraft —  is neat. Usually, a coder should not use undocumented features of a language, but at 76 years of age, I can do anything I want. Since in JavaScript, lists of positions is allowed, I trust the makers of MakeCode will not eliminate the feature.

The function has an outer loop corresponding to the X coordinate of a position and an inner loop corresponding to Z. Each position { X 0 Z } is added to the list. { X 0 Z } is a world position; that is, each coordinate is just a number that can be added to origin to get a world position of a block on the grid. Each position added to the list is of the form { X 0 Z }, where X and Z are each a  value between -5 and +5.

init array code

The get available position function does the following:

  1. Checks the length of the available positions list. If the length is 0, meaning there are no positions available, it sets the Boolean variable availableFound to false and exists; otherwise, it continues at the next step.
  2. Picks a random position from the list as the variable availablePosition and removes it from the list.
  3. Sets availableFound to true and exits.

get available code

Process on-broken events

When a player breaks a white or cyan block on the grid, events are triggered that call the breakCommon function, which does the following:

  1. If the variable answerPosition has not yet been set, the function repairs the broken block and exits.
  2. If the block at the answer position is air, the answer is correct; otherwise not. I think this is sneaky or perhaps I mean clever, but I wouldn’t want to brag.
  3. For correct answers, the block at the answer position as well as the one below it are replaced with green blocks.
  4. For incorrect answers, the block at the answer position as well as the one under it, are replaced with red blocks. But before that, the block above the answer position flashes green a few times to indicate where the correct answer is. The wrong white block broken by the user, is left as air until repairs are done in the last step of this function.
  5. Before the on-chat command is launched to post coordinates of a new position on the grid, the function pauses one second to give the player a chance to view the current position coordinates at the same time as the corresponding block turns green or red.
  6. Finally, a function is called to do repairs, which replaces the air block, which was  left by a wrong answer, with a white block.

break code

Repairs

The do_repairs function runs every time a white or cyan block is broken; that is, an answer is given to the displayed position question. Repairs are needed when the player breaks a block that is not the correct answer. The first replace block  in the function fixes that. Also, on rare occasions, the flashing green block above the correct answer is left as a green block, not air as it should have been. The second replace assures that all blocks above the grid are air. The last step is to set the origin block, which might have been changed by mistake or broken as a correct answer to grid position { 0 0 }.

do repairs

Besides wrong answers, players make other mistakes when breaking things; for example, a player might break a grass block next to the grid. Or, a player might just be plain ornery, breaking things to see what happens. The remaining repair routines run in response to events when something is broken by a player that should not have been either by mistake or orneriness. The following should not be broken:

  • green blocks
  • red blocks
  • axis market blocks (white carpet)
  • grass blocks

When these blocks break, the associated on-broken event makes the needed repairs. How cool is that?

fix red and green

axes markers

repair grass

Code Requires a Flat World

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

Get the Code

Coordinates Game code is shared on Code Connection at this URL

https://makecode.com/_8vKbsj7diit1

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

Negative Random Number Tester in MakeCode for Minecraft

 

main

I have made several uses of negative random numbers in my MakeCode for Minecraft programs, for example, in Coordinates Tutor in MakeCode for Minecraft I used random numbers between -5 and +5 to generates X and Z coordinates on a grid. With each use,  I wondered whether the number of negative numbers generated were, in fact, equal to the number of positive numbers generated. Thus, this exploration.

By experimenting with this program, I observed two things. First, in cases where I generated fewer random numbers, say 10, the number of positive numbers and negative numbers were often quite different. For example, in one case of only 10 generated numbers, 60% were positive and 30% were negative — not close. However, in the case of a million random numbers, 47% were positive  and 48% were negative — close. But, remember that in both cases, because the numbers are random, different runs of the program may give different results.

Three runs of the program generating 10 random numbers each gave the results shown below. The case on the left was perfect with exactly the same negative as positive numbers. The other two cases were not so close. Generating only 10 numbers is likely to give results like on the right because the number of runs (the sample size  n) is small and, thus,  one can expect large variation in the cases.

Three runs of the program with But, remember that in both cases, because the numbers are random, different runs of the program may give different results. random numbers gave the results shown below. The case on the left yielded exactly the same negative as positive numbers. The other two cases were not exact; but, they were close. Because the sample size n 100,000  is relative large, the variation in the runs is not great. But, beware, a single run might have very different results.

While the two cases on the right (above) total to 100%, the case on the left totals to 101%. This is caused by

  1. division that may not yield a whole number and
  2. by rounding.

This is illustrated below, which is say-block output from the program. These results show more significant digits than the billboard output.. Notice on the right that while before rounding the total is 100% but after rounding the calculated percentages is 101%.

Don’t worry if the reasons for such situations are not intuitive. Entire books are written on the subject. I remember taking and later teaching courses called “Machine Arithmetic” and  “Numerical Analysis,” which tediously explored such situation.  In your programming journey, just know that such situations exists and devise code to give the precision needed.

The Plan

The plan for Negative Random Number Tester, or just “Tester,” is to generate some number n random numbers between negative and positive limits of equal absolute value; for example from -10 to +10 or from -1000 to +1000 or from -1 to +1. The exact value of the limits should not matter; however, I did not test that.

The number of random numbers generated n is an argument to the run on chat command that starts the program. It can have values from 10 to 1,000,000.

The guts of the program is the loop that generates the random numbers counting individually the number of zero, positive and negative numbers.

After all the numbers have been generated and counted, the n and the percentages of each of zero, positive and negative random numbers are printed on a billboard, as shown above.

The Code

The run on-chat command is on the top left. The right half of the screen are those routines that convert counts to percentages and print them on the billboard.

code all

The run on chat command performs the following:

  1. Calls a function to move the player, set the origin and set the print position on the billboard.
  2. Checks the argument n for the correct range of 10 to 1,000,000. If n is out of range it set it to the default value 100,000.
  3. Builds the billboard on which the results will be printed.
  4. Initializes the count variables for zero, positive and negatives values of generated random numbers.
  5. Loops n times generating random numbers and counting the resulting values that are zero, positive or negative.
  6. After exiting the loop, says the three count values and calls a function to convert and print them on the billboard.

run code

Rather than print results in the sky, they are printing on a billboard..
whiteboard code

The routine in charge of printing the percentages first calls the functions that convert each of the percentages to text. It then runs the three chat commands to do the actual printing. It also says two totals, one for the total of the three percentages before rounding and one for after rounding.

print pcts code

There are three individual function for the conversions for no other reasons than to organize the code. The routines doe the following:

  1. calculates count as percentage of total,
  2. rounds the result,
  3. calls the format_pct routine right align the number in a 3-digit string, and
  4. adds the appropriate label and the % sign.

The gray block indicates that rounding is done in JavaScript.

convert pct to text

The format_pct routine takes as input a text variable representation of an integer percentage; for example, “1” or “13” or “100”. Since an integer percentage may have 1, 2 or 3 digits, it makes the forces the string to be length  3 by adding spaces on the left of the digits. When the numbers so modified are printed in a column, as they are on the billboard, they will be right aligned.

pad code

The print routines are individual chat commands, not functions, so that they will print simultaneously, which greatly speeds up the print. Notice that when the program is running the three numbers print at the same time. Each of the print routines have a different Y-axis value, which specifies the up-down position on the billboard..

print pos

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

Get the Code

Negative Random Number Tester code is shared on Code Connection at this URL

https://makecode.com/_EfC4c9WCUcuR

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

Faster FISH Print in MakeCode for Minecraft Aquarium

 

FISH

This post describes a change to Aquarium in MakeCode for Minecraft that was suggested by a YouTube viewer..

The challenge in the design of the aquarium was to  print  “FISH” on the front of the aquarium by using the Minecraft Print block. The spaces within each character are to be filled with cyan glass blocks, not air (the Minecraft default). Filling with cyan glass blocks  makes the print appear to be embedded in the wall.

The Code

The helpful viewer suggested that I use the Minecraft Replace block instead of the much slower and more verbose nested loops, which test each position in each character for air and replace it with glass.

LOOPS

A loop within a loop that tests each position in a 5×5 character for air. If an air block  is found, it is replaced with a cyan glass block.

replace block code

A single Replace block replaces any air blocks in a 5×5 character with a cyan glass block.

The screenshot below shows the entire Aquarium code with the new print routines.

code all.png

Aquarium code with new print routines.

One print_n routine is required for each character in the text to be printed to enable the four prints to run at the same time rather than each character waiting for the preceding character to print. This was described in the original post Aquarium in MakeCode for Minecraft. The four print routines for “FISH” are shown below. The only differences in the four routines are:

  1. The character to print and
  2. The position in the wall.

The character to print is selected from the string print_text at the position print_num1, which is an argument to the routine. For example, print_2 is passed the argument print_num1 = 2, which selects the string “S” from the string “FISH”.

The position in the wall at which to print is print_num1 position from the array print_pos. For example, for print_num1 = 2, the position chosen from the array is the position for “S”.

prints.png

The four new print routines.

These routines would be a great deal simpler if arguments to an on chat command could be of type string or of type position instead of just a number. This not being so, dictated that the routines use the number argument print_num1 to select the string to print and the position at which to print.

one print

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

Faster, Smaller and Easier to Understand

What’s not to like? The Minecraft Replace block does exactly what the nested loops (above) did. The Replace is much faster, as demonstrated in the video (above) . Further, the Replace is less verbose; that is, is fewer lines of code. The Replace is also much easier to understand.

Why Didn’t I Think of That? Wasn’t It Obvious?

It was obvious to my viewer. But,  I am only a few months into learning MakeCode for Minecraft. I have not used every block in the MakeCode language. One can argue that that was a mistake. I, as usual, was so impatient to start creating programs that I did not take the time  to methodically learn every MakeCode block before I started. I prefer Just-in-Time learning, which I am sorry to say that along with one of my life’s themes “not knowing what I don’t know” results in projects that can be improved. Don’t expect me to change. I like improving my projects and I love learning  whenever it is done. So bring it on — every constructive criticism  is welcome.

Get the Code

Aquarium with the improvements described here is shared on Code Connection at this URL

https://makecode.com/_YALWi6RbUXe2

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

Aquarium in MakeCode for Minecraft

 

main

Aquarium Front. Pool of dolphins on left. Watch them frolic in the  fountain. Salmon in the right pool. Slime seem to be attracted to the salmon.

glass view from door

The main fish tank as seen from the entry.  All kinds of Minecraft fish are included with a bit of kelp and coral, also.

at glass

A look through the glass of the main fish tank.

inside top view

A view from the top of the main fish tank. The green things are kelp.

inside tank

From inside the main fish tank.

from inside

Aquarium interior

slime in pool 2

Slime seems to be attracted to the salmon tank.

The Design

When viewing the final aquarium from above, one can see the concentric squares of the main building, the steps up to the aquarium, the fish tank and the glass square at the center of the tank. The porch on the aquarium features a left pool with a fountain and a right pool.

building from above

I started the design of the aquarium with the drawing below. Note that the concentric squares of the main building, as well as the porch with pools, correspond to structures in the final aquarium. Each square is defined by its lower-left corner and the number of blocks in a side of  square.

plan

Because the lower-left corner position of each structure is used as the reference position, each structure is built to the east and south of the corner; therefore, all coordinates X and Z positive.

Space and Time Challenges

I encountered several challenges in coding this program. I wanted to type run and a few seconds later view my aquarium.

I wanted to print  “FISH” on the building in a manner that the characters are embedded in the outer blocks, not in front of the blocks. Printing “FISH” with one print block is unbearably slow. Further, the code to embed the characters at least doubles the print time. I don’t have the patience for it.

print embedded

I solved the slow-print problem by printing each of the four characters in “FISH” asynchronously. The code is described later in this post. This approach required greatly increasing the number of code blocks  making the program so large that if I ever viewed it in JavaScript, MakeCode would not convert it back to blocks, so I gave up JavaScript.

The program was still too slow for me. Again, I used asynchronous code to nearly halve the time by running the code that builds the porch at the same time as the main building is built. This choice only increased the code by one on-chat block.

The Code

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

All the code for Aquarium is shown in the graphic below. Upper left t is the main on-chat command “run.” Below it is the function that sets the dimensions, such as, the size of each square, that define the structures. Below that is the function that calculates the corners as shown in the drawing above. From left to right, is the code for the outer building, the tank and fish, the porch with pools and, lastly, the fast print. Notice how much code is required for the fast print, which caused the program to be fast but larger than I would like.

ALL CODE LABELED

This program could have required much more code to build such a complex structure. The clever, if I do say so myself, use of 25 fill blocks enabled it to be amazingly compact. The use of the fill-block hollow option was particularly useful.

run on-chat command

in this on-chat command block, which starts the program, notice the use of the two run-chat-command blocks instead of functions. Had functions been used, the function would have to complete before the following block would be executed. By implementing it as shown, the code for porch and print_fish runs asynchronously with the functions that follow. You can think of the run-chat-command blocks as launching independent programs then immediately to run the code that follows.

run code

Beware of Common Variables in Asynchronous Code

When using asynchronous code, the variables used in two code sections that run at the same time, must not share variables except for those that are read only.

Set Dimensions and Define Corner Positions of Structures

define dims

define corners

Build Outer Building and Foundation

outer building code

do outer door

do foundation code

Build Tank and Populate with Fish

do tank code

do tank interior code

AQUA THINGS CODE

Build Porch

pool code
porch entry code

Build Two Porch Pools and Populate with Dolphins and Salmon

TWO POOLS CODE

pool code

Fast Print “FISH”

The key to print speed is to print each character with a separate print on-chat command.  In the case of “FISH,” which has four  characters, the on-chat commands are named print_0, print_1, print_2 and print_3. The only difference in code for the four commands is the name. All the interior code is identical in the four functions. The code following the print block fills in the air spaces left by the character within the area where the character was printed. A for-index block would have been neater; however, the index in such a loop cannot be an element of an array. Of course, I tried it.

print fish one letter

Before you ask, of course, the four functions can be collapsed to one; but, in that case, the commands will not run asynchronously and no time is saved.

print fish several letters

The code below is the main code for the fast print. It launches each of the four print commands after initializing the appropriate element of the three arrays print_pos, print_i and print_j. Each on-chat command using a different element of the three arrays. This was necessary to avoid having the asynchronous routines from changing the same variables. This could have been done by  naming the variables differently for each on-chat command; however, that would have  made the interior codes different.

print fish main

I plan a future post that will further explore fast printing.

Get the Code

Aquarium code is shared on Code Connection at this URL

https://makecode.com/_0kDWR4UsX9KP

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

Coordinates Tutor in MakeCode for Minecraft

 

main screen

We recently developed a game to demonstrate a player’s knowledge of MakeCode Minecraft coordinates. Soon as The Girl started testing it, we realized that a more tutorial program was needed to assist in learning coordinates. Coordinates Tutor — this program — was born..

How to Play Coordinates Tutor

After the user types run in the command window, the Coordinates Tutor will move to a new, pristine  world location, print a compass in the sky for the player’s reference, place a grid of blocks with a cyan glass block at the origin, which is the variable name we give to the 0 0 point in the grid where the X and Z axes intersect.

After initialization, the program will display the left scene then the right to remind the player that in MakeCode Minecraft coding, a coordinate  X is east, Z is south and Y is up. We do not use Y here because it is always the same.

{  X  Y  Z  }.

The positive X axis is east. If one thinks of herself, the player, as facing east, south will be on her right, north on her left, and west behind. Of course, the values X and Z can be negative as well as positive. A negative X is west and a negative Z is north.

When the right scene — {  E   S  } —  is displayed, Coordinates Tutor is waiting for the user to break any block in the grid. Please, break just one block.

broken block

After a block is broken, question marks will flash during the varying time that it takes for the program to search the grid to find the broken block.

When the program finds the broken block, the coordinates of the block will be printed between the brackets. The  broken block will be replaced with a green one, except for the origin block, which will be restored to a cyan block. The green block shown below is at coordinates { – 2 –  2 }.

coor display

At this point, the user may break another block and the program repeats. Coordinates Tutor is patient allowing a user to break blocks until she has absolutely mastered Minecraft coordinates. Then it is time to play Coordinates Game, which works in reverse: that is, when a coordinate is displayed, the user must break the block at the corresponding position on the grid.

The MakeCode Code

The Code Assumes a Flat World

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

Coordinates Tutor Starts with the Run Command

The on-chat run command initializes the program. The steps are:

  1. Teleport the player to an unused part of the world.
  2. Set the variable origin, which will be used as the reference position for all actions as well as the center of the coordinates grid.
  3. Set a position in the sky to be used as left reference point for the coordinate print area.
  4. Run the on-chat command compass to print E, S, W and N in the distant sky. compass runs while the code after it continues because it is an on-chat, not a function.
  5. Run the on-chat command brackets to print squiggly brackets on the left and right sides of where the coordinates will be printed.
  6. Call the function canvas to draw the grid for the coordinates.
  7. Call the function flashXZES, which will display X Z then E S, inside the brackets. This reminds the  player that the left coordinate is X and the right Is Z, or, equivalently, E and S.

run code

The Action Is in the Broken Events

When the player breaks a white, green or cyan stained glass block, which defines the grid, an on-broken event occurs, which for all three events results in the doBrokenEvent being run.

The doBrokenEvent function does the following:

  1. Sets the Boolean variable air_found to false. This variable will be set to true in the function findAir when the broken block is found.
  2. Set nPrints to 0. This variable will be incremented by 1 in one of the print commands launched by the run-chat flash_q.
  3. Launch chat command flash_q, which flashes questions marks inside the coordinate brackets until air_found is set to true in the findAir function.
  4. Call function findAir, which returns only after the broken block is found at which time it runs the chat command postCoordinates.
  5. The chat command postCoordinates prints the coordinate that was found, which is the coordinate of the broken block. postCoordinates is run as a chat, not a function, so that the on-broken event can complete. Although not required, this is neater than having the possibility of a second on-broken event occurring before the prior one has completed.

on break code

Searching for Air

The findAir function, searches the grid starting at coordinate  { -5  -5 } and searching to { 5  5 } for a position in the grid that is air instead of the glass block that was broken. To do the test, it uses the function testTryPositoin to determine air or not. The variable air_found was set to false before the function findAir was called. If air is found, the function testTryPosition sets air_found to true.

find air code

The function testTryPosition tests the Minecraft position to determine whether or not an air block is at that position. If it is not air, it returns doing nothing as air_found is already false. If air is found, it sets air_found to true and sets the airPositoin as well as air_X and air_Z. Note that airPositon has origin added because the Minecraft position is need to place the green block. However, air_X and air_Z are relative to origin; that is they are the coordinates on the grid, e.g. { ,-5  2 } because these variables will be used in posting the coordinate at which air was found. A green glass block is placed at the position at which air was found.

test try position code

The MakeCode Bug that Wasn’t

While coding testTryPosition, I became convinced that there was a MakeCode bug in testing position variables for equality. After some time trying the understand and prove the bug, which included writing a program to test for the bug in a less complex situation, I realized, as I have so many times before, that the bug was in my understanding of position variables. I will not go into the detail here, but take my word for it — if  you want to test a calculated position variable against another, test that all individual coordinates {X Y Z} pairwise for equality instead.

Print the Broken Block Coordinate

postCoordinate is a simple on-chat command that, if the broken block was found, prints the coordinate between the brackets. If the broken block was not found, which should never happen,  it prints red question marks between the brackets. Most of the code is to adjust the text for whether or not X and Z are negative.

post coordinates code

Simultaneous, Oscillating Print Until … Something Happens

I couldn’t resist explaining how the question marks print at the same time and are reprinted in another color block until the broken block is found. To review this short vid show this working.

The key to the simultaneity is using on-chat commands instead of a function or just doing the print blocks inline.  The changing colors are enabled by the variable nPrnts, which is incremented each time through the print blocks. Because the print blocks are run more or less simultaneously, nPrints must be incremented in only one of the print blocks; otherwise, the colors would get out of sync. The print blocks are in a while loop that tests air_found, which when true,   the prints stop enabling the coordinate of the broken block to be printed in the same spaces.

print q flasher code

Get the Code

Coordinates Tutor  code is shared on Code Connection at this URL

https://makecode.com/_d7PAhvEH98iy

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

Using Minecraft Blocks as Buttons: Block-by-Block Tutorial Video in MakeCode for Minecraft

 

main

Strategy

The strategy for using Minecraft blocks as buttons to control a program is:

  1. Place the buttons on the screen in a place convenient to the player.
  2. In the block on-broken event, use the code that would have been in a on-chat command to do a sequence of actions,
  3. Replace the broken block with another of the same kind.

MakeCode Code

We modified the existing program described in Handy Timer — Block-by-Block Tutorial Video in MakeCode for Minecraft , to illustrate using Minecraft blocks as buttons. Only the changed code is described here.  This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

The placeButtons Function

The placeButtons function does exactly what its name implies: it places each button that will be used in lieu of an on-chat command. I like to place the buttons in front of the player within easy reach so that the player need not move to break a block (click a button). In this case we placed red concrete to do the same thing as the stop on-chat command, yellow for the reset command and green for the go command.
Place button code

Call the placeButtons Function

Once the function is built, it must be called from every code that initializes a screen. Here it is called from on start and from moveMe. As explained in the next section, it is also called from each block’s on-broken event.

on start and moveme

Code the on-broken Events

Each block being used as a button must have an on-broken event in which the same code as in the corresponding on-chat command should be run. I like to move the code to a function, which is called from both the on-broken event and the on-chat command. The advantage of putting the code in a function is that if it is modified, it need be changed in only one place.

Each on-broken event must also call placeButtons. Of course, an on-broken event really must replace only the broken button, but the advantage of calling the placeButtons event is that if you want to futz with the location of the buttons, it need be changed only in one place — always a good thing.

all buttons code

Get the Code

Handy Timer with Blocks for Buttons code is shared on Code Connection at this URL

https://makecode.com/_iwCgCd5bsFxY

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.

How to Use Shared MakeCode on Microsoft Code Connection for Minecraft

 

Most of our wecodemakecode.com posts share a link to the Makecode programs that were described in the post. To use the code, follow these steps on a Windows 10 PC.

Skip to Step 5 — if you are an experienced Code Connection user. In this case, in another 30 second you will have opened your first shared program.

Skip to Step 4 — if you know how to open and link Code Connection to Minecraft.

Skip to Step 3 — if you have already installed Minecraft and Code Connection.

Step 1. Install Minecraft and Code Connection from the Microsoft Store

Step 2. Start Minecraft and Code Connection

code connection link to minecraft

Step 3. Link Code Connection to Minecraft

Copy the link from Code Connection by

Click the copy button  button, which copies the link to the Windows clipboard.

Start a game in Minecraft and choose a world.

Choose world.png

Most We Code MakeCode programs require a flat world such as Sandbox, which we described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

Open or create a world and open a chat window. Paste the link copied from about into the chat window. I use the keyboard combination control-v to do the paste.

Chat window with link

Hit Enter on the keyboard or click chat arrow , which is to the right in the chat window. The message “Connection established to server: …” should be shown on the Minecraft screen. If instead, an error message is shown, a common reason is the Internet connection is not available or too slow.
connection established

After the connection is established, the Code Connection screen will show the  languages in which programs can be written to control Minecraft objects, for example, MakeCode or Scratch.

code connection language choices

Click the MakeCode button. The MakeCode window will then become that shown below on the left. I like to position my Code Connection window to the left and my Minecraft windows on the right.

side by side 2

I sometimes think of the Code Connection window as my MakeCode window because once I open or create a program, it is MakeCode I see, such as shown below after clicking the New Project button.

after new projects button.png

Step 4. Load a MakeCode Program

side by side 2

In the Code Connection screen shown above, there are five ways to access a MakeCode program:

  1. New Project, by clicking  new projects.
  2. By clicking one of buttons to the right of New Project, which, in my case, is one of the projects that I had previously developed, for example, flat fixer button. Of course, your Code Connection will show your prior projects.
  3. By clicking one of the buttons below New Project, which are Microsoft-developed example MakeCode programs, such as, flower rail button.
  4. By clicking the Import button  import button, which is on the upper right just below the Code Connection banner, two additional sources of programs are revealed.
    • Import a previously saved program from your computer.
    • Import a shared program from Code Connection using a URL that was supplied to you by the person sharing the program, for example, one a friend or teacher might have emailed you or one suppled in a We Code MakeCode blog post.

Import choices

Step 5. Import a Shared MakeCode Program

Click the Import URL button Import URL , which is on the right, to open the window shown below.
Import Copy link

Now all that is needed is the URL of the specific project you are wanting to import. The URL must have been provide to you by the person sharing the program. For Example, In We Code MakeCode blog posts, we provide the needed URL in the “Get the Code” section at the end of the post. Paste the URL supplied for the program you want to use  in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button

The next window you will see will be is the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

Methods of Using the Code URL that Mostly Don’t Work

We have tested several other methods of downloading the code using the URL. We have pasted it into browser or click the link. Typically, this will open a browser, e.g., Edge, Safari. Interestingly, Safari on iPad opened the code allowing a view of both the Block and JavaScript versions of the code. There was a run button, but it did exactly nothing. Edge on a high-end Surface Studio with very fast download Internet connection,  opened smaller programs but always hung up on larger ones. On those that opened, I have not yet figured out how to get the opened new Code-Connection window linked to Minecraft. Of course, I would prefer clicking a shared URL put the code in my usual Code Connection window, but I have not yet accomplished that.

I recommend you stick to the method described above of pasting the URL into the Code Connection import window.

Handy Timer — Block-by-Block Tutorial Video in MakeCode for Minecraft

 

field 70 seconds

Handy Timer

I needed a timer for the game Snowman Army, which I will describe  in a  future post. Games often need a timer. This post describes Handy Timer, which explores how a timer might work in a game.

Handy Timer Strategy

The guts of Handy Timer is a forever loop that increments a second counter each time a second passes. The second counter is displayed each time it changes; however, in a real game other game-appropriate actions could be done each time the counter is updated. . The default second interval is one second, but it can be changed to other intervals, e.g., 10 seconds, 60 seconds.

The Code

This code assumes a flat world such as that described in MakeCode for Minecraft Sandbox World: Make It Flat and Simple.

The code consists of the forever loop, the on-chat commands that control the timer and my ubiquitous moveMe chat command.

Forever Loop: The Guts of Handy Timer

Below is the forever loop guts of Handy Timer. The Boolean variable bRun is true when the timer is running and false when it is stopped. The pause block pauses the code for delta seconds. The variable delta is the timer interval. Actions are taking after delta seconds have passed but only if bRun is true; that is, the timer is running. The actions shown here are to increment the second timers by delta seconds and display the timer value.

forever code

on-chat commands Control the Timer

The following on-chat commands control the timer:

  • go — starts the timer by setting bRut to true
  • stop — stops the timer by setting bRun to false
  • reset — initializes the timer setting seconds to 0 and delta to 1 second. These same values are set when the program starts in the on-start block.
  • delta — changes the interval to the number specified in the on-chat command argument. The variable delta will be changed only when the second counter is 0; therefore, it can be changed when the program first starts or after a stop then reset commands have been executed.

go stop reset chat code

The reset actions are implemented as a function so they can be called from both the on-start block and the on-chat command reset.

on start and reset code

The on-chat command delta has one argument num1. If num1 is greater than 0, delta is set to num1; otherwise, delta is set to 1, the default. If num1 is not provided, it is 0 and the default is used.

delta code

moveMe chat Command

I love my moveMe command because it saves me all that manual moving from place to place in a Minecraft world just to find a clean place to try my program again and again and again, which is usually needed during development and testing. Notice that only X is changed each time moveMe is run; thus, the player is always moved 100 blocks to the East. The player is also placed on the ground because this is what is expected by the other sections of the program. For Handy Timer, a sunflower is placed 2 blocks east of the player as a direction guide. Sunflowers always face east. Since the timer will be printed to the East of the player, its good to know in which direction to look.
moveme basic

Is Handy Timer Accurate?

I used my phone timer to compare to Handy Timer for an estimate of accuracy. For a short time, e.g.,  5 seconds — not very accurate. For longer time periods, e.g., 30 seconds, then results are essentially the same, or at least as close as my eye balls can discern. The difference is the time it takes to perform the actions Handy Timer does at the end of each interval. With a say-block to display the time, it is more accurate than it is with a print block, which takes much longer to display the seconds.

For games, a timer similar to this would be useful for marking more-or-less regular intervals, but it will not replace a stop watch.

Handy Timer’s Future

In my next post, Using Minecraft Blocks as Buttons: Block-by-Block Tutorial Video in MakeCode for Minecraft  I will use Handy Timer to show how to use Minecraft Blocks as Buttons to control the timer. In the post after that, I will use it to explain When and How NOT to Use Player World Position in MakeCode for Minecraft.

We Will Do More Block-by-Block Tutorial Videos

The Girl argued that some of our videos be tutorials on coding MakeCode block by block so that a beginner can see exactly how and why each MakeCode block is used. This post presents our first such effort. Our prior videos have described a program by looking at the final code and describing section by section what it does and how it works. Admittedly, this may be overwhelming to a MakeCode beginner. We will do a bit of both in the future. Our tutorial coding videos will be listed under the category “Block by Block Tutorial Video.”

Get the Code

Handy Timer code is shared on Code Connection at this URL

https://makecode.com/_3C89FjDJaEbR

To get and use the code, follow these steps.

Click the Import button import button , which is upper right in the Code Connection window just below the banner. This will open the window shown below.
Import choices

Click the Import URL button Import URL, which is on the right, to open the window shown below.

Import Copy link

Paste the URL supplied for the program you want to use  in the space under the text “Copy the URL …”
import url with url

Click the Go ahead! button go ahead button.

The next window you will see will be the MakeCode window with the code downloaded from the URL. At this point, you can treat it like any other code, e.g., run it, save it locally, modify it, publish your changes or whatever else your heat desires.

We have tested several other methods of downloading the code using the URL, for example, pasting the URL in a browser. No joy. For more detailed instruction see our post How to Use Shared MakeCode on Microsoft Code Connection for Minecraft.