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.

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.

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.

Creating Symmetric Patterns Using MakeCode for Minecraft

 

red white and blue 50 vista

We created this symmetric red, white and blue 50-block square pattern  in appreciation for U.S. Independence day. The left and right halves are mirror images as are the upper and lower halves.

red white and blue border rotated 50

For July 4th, we couldn’t resist making a red, white and blue pattern including one extra block TNT for a big bang (see YouTube video above).

Symmetric patterns are beautiful, fascinating and endlessly entertaining. Amazon lists 4,000 books on symmetry.  Wikipedia explores symmetry in mathematics,  biology, art, physics, chemistry, social interactions, architecture, poetry, quilts, rugs, physical attractiveness and music among other areas of human endeavor.

We created the MakeCode for Minecraft program described in this post just for the fun of it.  With the program, symmetric squares of any size (within reason) and using any number of Minecraft blocks can be created. The program user picks the Minecraft blocks to be used for the canvas, for the pattern and for the optional  border. The program first builds the background canvas for either one or two levels, then builds the pattern using the number of blocks specified by the user. Optionally, a border can be added.

We are amazed that such a simple program can create such beautiful patterns. Gazillions of combinations are possible, some more pleasing than others. Make your own.

The Plan for the Symmetric Patterns Program

The plan for this symmetric patterns program is that it enable a user  to build a random, 4-way symmetric pattern in the following steps:

  1. Specify Minecraft blocks in three lists; namely, canvasBlocks, patternBlocks and borderBlocks.
  2. Use the on-chat command “canvas” to place one or two layers of blocks from the canvasBlocks list.
  3. Use the on-chat command “pattern” to create a random, symmetric  pattern with blocks from the patternBlocks list.
  4. The on-chat command “border” builds a simple border around the pattern using the first block in the borderBlocks list.

Details of the on-chat commands’ arguments are provided below in the description of the code. This table is a summary and handy when using the program.

The MakeCode for Minecraft Code

The on-start Block

The lists canvasBlocks, patternBlocks and borderBlocks are inputs to the program; that is, they can be changed to create different patterns.

symmetry code 1

Any number of blocks can be included in each list, but only the number specified in the on-chat commands will be used. I sometimes include more blocks than are used so that changing blocks can be done quickly with drag-and-drop. Because now the border can be only one block wide, only the first block is used; however, since I might add additional borders, it is specified as a list rather than a simple one-block variable.

Canvas on-chat Command

The chat command arguments specify the size of the canvas and the number layers to be build. The top layer is even with the grass in a flat world. An optional underlayer can be specified, which is useful when glass blocks are the top layer.

The canvas on-chat command is implemented in three steps:

  1. The two arguments are verified and, if out of range, set to default values.
  2. The variable “center” is set to the player world position, but Y (the up/down coordinate) is set to the same as the grass. This variable is used as the reference point for building the canvas.
  3. The canvas is built around center one  layer at a time in a loop. Each layer is built with a single fill block.

The argument num1 is the number of layers to build. num1 can have values 1 or 2, but also must not be greater than the number of blocks in the canvasBlocs list. If canvasBlocks contains no blocks, a white concrete block is added as the default.

The argument num2 is the size of the canvas specified as half of the final size. for example, if num2 is 80, the canvas will be 160 blocks square. Some limit is required because of the fill block limit volume is 32,768 blocks.

symmetry code 2A

Canvas Code — Part 1 of 2 — Validate Arguments

If num1 and num2 are omitted on the command line, the defaults of 1 layer and 50 (100 square blocks) are used.

After the arguments are verified, the variable minusNum2 is calculated as the negative value of num2.

Next, the position variable center is calculated as coordinates X and Z being the same as the player world  position, but the Y coordinate is specified as 3, which is the same level as the grass in a flat world. Notice that the player need not be on the ground for center to be calculated correctly. By using this variable instead of player world position for later program actions, the reference is always the same even if the player moves. I often like to have my player at a high vantage point and moving around  so that I can see the action. I don’t want a program behaving erratically just because I move the player. For example, a fence built relative to player world position might be built, or partly built, in the air. Fixing a reference point like center solves that problem.

symmetry code 2B

Canvas Code — Part 2 of 2 — Place 1 or 2 Layers Around Center.

The guts of the code is the loop on index variable Y_level that runs from 0 to num1 -1. If num1 (the number of levels) is 1, the loop only runs once. If it is 2, the loop runs twice.

The fill command uses the block at Y_Level in canvasBlocks; therefore, the top canvas level is the first block in canvasBlocks and the second block in canvasBlocks is the underlayer (the layer of blocks under the top level).

Each time through the loop, the Y coordinate for the from and to are the same, thus only a single layer of blocks are laid. The first pass through the loop, the top layer is set. The second pass, if any, the underlayer is set.

The from and to coordinates of the fill  block  define a square around the variable center as shown in the drawing below.

drawing 1

Pattern on-chat Command

The size of the pattern and the number of blocks (num2) to be used are specified as chat command arguments. num1 is half the final square side. The pattern is left-right mirrored and upper-lower mirrored. It can also the thought of as a quarter of the final pattern rotated to each of the four quadrants.

The pattern on-chat code has three parts:

  1. Validation of the parameters.
  2. Setting the variable origin as the reference position. Then setting q1, q2, q3 and q4 as the lower left corner of each of the final quadrants.
  3. Generating a random pattern of num2 blocks in quadrant 1, then mirroring it appropriately in quadrants 2, 3 and 4.

In pattern arguments, the size of the square (num1) that forms each of the quadrants of the final square must be positive. If zero or negative, it is set to default 5, which will result in a final square of 10 blocks. num2 is the number of blocks to be used, which must be at least 2. The patternBlocks list must have at least two blocks, the minimum number required to create a pattern.

pattern code 1

Pattern Code — Part 1 of 3 — Argument Validation

After the arguments are validated the reference positions are set. origin is the set to the player’s initial world position except at grass level. q1, q2, q3 and q4 are set to the lower-left corner of each of the 4 quadrants, respectively.

quadrants

q1 is set to origin. q2 is num1 blocks to the right (south)  of q1. q3 is num1 blocks west (below in drawing)  and num1 blocks south (right)  of q1. q4 is num1 blocks west (below in drawing) of q1.

pattern code 2

Pattern Code — Part 2 of 3

quandrants 2

The goal is to create a final square with four quadrants as shown here. I think of the upper-left quadrant as not mirrored with the other three quadrants mirrored as shown.

single quandrat rows and columns

For each quadrant,  rows are thought of as starting at the lower left corner at  row 0, moving upward to row num1 – 1. Columns are thought of as starting at column 0, moving left to right to column num1-1.

Conceptually,  the pattern code strategy is to crate a pattern by loping through each row and column. For each (row, column) coordinate, a block is selected randomly form patternBlocks list. The selected block is then placed appropriately in each quadrant. In quadrant 1, the block is simply placed at position (row, column) relative to q1. In quadrant 2, the block is placed at (row, num1 -1 – column), which causes the placement to be the mirrored across the vertical boundary between the quadrants. The other two quadrants are similarly placed in mirror positions.

pattern code 3

Pattern Code — Part 3 of 3

The drawing below is an illustration of the mirroring of quadrant 1 position (5, 6)

rows columns mirror

Border on-chat Command

The border on-chat command calls the function “border” to do the work. It is implemented is a function so that it can be easily moved from one program to another.

After setting the reference point one block to the west and one block to the north of the lower-left corner of the large 4-quadrant square, the builder is employed to create a border around the square using the first block in borderBlocks list. The builder-algorithm is similar to that used my Builder Fence post.

symmetry code 4

Pattern Code — 3 of 3 — Mirror Quadrant 1 Random Pattern in Quadrants 2, 3 and 4.

border starting position

Just One More Favorite Pattern

halloween 4

Get the Code

Symmetric Patterns  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.

Remember Where You Started in MakeCode for Minecraft

In most of my programs, I need a variable that saves the starting position. For example, in Handy Compass I needed a reference point from which to print the four directions. I call such a reference point “origin.” Origin is the player world position except that it is always on the ground even if the player is flying or standing on a structure. Origin is on the ground where the player’s feet would be if the player standing on the ground. The X and Z coordinates of origin are the same as the player world position. The function setOrigin is designed for a flat world.

Sometimes I run  multiple programs at the same time, for example, The Art of Random Walks. In such a case, I  usually want origin to be the same for all programs and set only once.  This is accomplished in the following two steps:

  1. Make origin a global variable by declaring it outside all function and on chat blocks. Since origin is a position variable, it should be set to null, which means it has no value. The variable  origin cannot be set to zero because it is a position variable. A position variable consists of 3 values, one for each of the e 3 coordinates X, Y and Z.  In MakeCode blocks, global variables should be initialized in an on start block.
  2. In the setOrigin function, or any other program that might set the origin variable, first test to see if origin already has a value. Only if it is null (does not contain a position) should origin be (see code below).

Set Origin code

The on start block below sets the variable origin to null when the start button start button   is pressed. I program my on start block as is shown on the left below; however, MakeCode usually, eventually changes it to be as shown on the right. The two are equivalent, so I don’t get too excited.

The on chat command below is used to test the function. It calls setOrigin, then places a gold block under origin, which is be level with the grass in a flat world.

Set Origin Run Code

In the JavaScript below, note that origin is set outside the onChat and the function; therefore, it is a global variable and can be used by both the run on chat and the setOrigin function.  Also notice the use of the value “null.” I have not found such a value in the MakeCode blocks, so I switch to JavaScript to set it.

JavaScript

Get the Code

Remember Where You Started code is shared on Code Connection at this URL

https://makecode.com/_3wLH9K3Ashg1

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.

Handy Compass in MakeCode for Minecraft

 

I like knowing where I am. Handy Compass is a utility hat I use often in other programs. In a flat world, Handy Compass places a gold block level with the grass under the player. It then  prints the sign and coordinate name (e.g., +X, -Z) as well as the direction (e.g., E, N) in each of the four directions. An example of Handy Compass output is shown below.

Handy Compass Field 2

I use this compass  instead of the example compasses shown on the MakeCode for Minecraft website because Handy Compass is designed to be background to another program, not the feature.

How Handy Compass Works

Handy Compass is offered as a Chat Command, not a function,  so that it can be run asynchronously with the program it supports (e.g. The Art of Random Walks).

Handy Compass operates with the following steps:

  1. Says the program is running.
  2. Tests the position variable origin for whether or not it has been set before the function was called. If so, it is left as was, but if it was null (not set), it is set to the positon of the player’s feet.
  3. Says the coordinates of the origin.
  4. Places a gold block at origin, but one block down so that it is level with the ground.
  5. Calls a function for each of the four directions.
  6. Says that it is done.

handy compass code

Each of the four directions has an assonated function. Each function calculates X and Z for where to print the direction information. All printing is at vertical positon 20, which was chosen by trial and error. In each print block the direction of print is chosen so that if the player is facing the corresponding direction, the print reads from left to right. 

East

The function for East sets X to positive 50, meaning 50 blocks to the East from origin. The function prints towards the South  starting at Z = negative 20 blocks from origin, which was chosen by trial and error.

South

The function for South  sets X to positive  50, meaning 50 blocks to the South from origin. The function prints towards the West  starting at Z = positive 20 blocks from origin, which is chosen by trial and error.

West

The function for West sets X to negative 50, meaning 50 blocks to the West  from origin. The function prints towards the North starting at Z = positive 20 blocks from origin, which is chosen by trial and error.

North

The function for North  sets Z  to negative 50, meaning 50 blocks to the North from origin. The function prints towards the East starting at X = negative 20 blocks from origin, which was  chosen by trial and error.

Handy Compass Example Uses

See the Categories index for the blog for example uses of Handy Compass. A particularly nice example is The Art of Random Walks because Handy Compass run asynchronously, that is, the compass is created during the random walk.

Get the Code

Handy Compass code is shared on Code Connection at this URL

https://makecode.com/_Ti5fXbTs27qM

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.

Point East in MakeCode for Minecraft

In the real-world, the custom is that North is our primary reference direction. Once we know which direction is North, our mental map falls in to place: when we face North, we know that right is East, behind is South and left is West. So to find ourselves, all we have to do is find North. Finding North has progressed from using the stars through the compass to today’s GPS system.

In Minecraft, East is like real-world North.  if you think of yourself as facing East, South is to the right, North behind and West is left. So, all we need to do is find East to know where we are. Another reason to find East, is that relative to the player’s position, East is positive X and South is positive Z, making the Eastsouth quadrant the area of  (positive-X, positive-Z) coordinates from where the player stands. Using (positive-X, positive-Z) coordinates often makes moving and building easier to visualize.

Finding East

So which direction is East? An easy way is to plant a sunflower.

When looking at the back of the sunflower, the player is facing East, South is to the right, West is behind and North is to the left. Of course, when facing the sunflower, the player is facing West. Why do Minecraft sunflowers always face East? Imponderable. But, When I am building, I don’t want sunflowers scattered throughout my world. But, when I  am building, I don’t want sunflowers scattered throughout my world.east pointer

To point North, I use something more subtle that doesn’t get in the way of my structure. In some cases, I use a couple of blocks placed under the player’s feed to point East. I use the gold  block to make the “origin,” my usual name for the initial positon of the player. The blue block (lapis lazuli) is east of origin. I use these blocks as anchors for testing my mental map against the actions of my program. For example, when using the Builder to build a fence, I like to start at origin, move east, turn right, and so on, back to  origin.

East pointer with sunflowerBut, is the blue block pointing East from origin? Test it with a sunflower. The blue block is pointing the same direction as the sunflower, so East it is.

 

 

 

 

The Code

The East pointer code is implemented as a function because I use it in many different programs. Such routines are called “utilities” and are part of every programmers bag of tricks.

Point East code only

The function starts with a say block, which notifies the user that the function is running. Next, iIf the variable origin has not been set, it is set to the X and Z of the player world position with Y where the  player’s feet are (Y = 4)  in a flat world. For debugging purposes, a say block prints origin coordinates to the Command window. The gold block is placed under the original positon of the player’s feed with the blue block one block to the east. Point north chat

A run command launches the function debugging. The function is designed so that origin can be a global variable that is set before the function is called. In this case the once origin has been set, the player can be an another location and can move while the function executes.

This function is used frequently in programs documented in this blog, for example, Builder Fence.

Get the Code

The code is shared at https://makecode.com/_FxX9fCYx0iUL  where it can be downloaded and run in MakeCode for Minecraft.

Move Me: Better Ways to Move the Player in MakeCode for Minecraft

Move Me is a handy gadget  that I use when debugging my code. When on the hunt for programming bugs, a clean world area is needed every time the program is tested. To date, I have thought of five ways in which this can be done:

  1. The most obvious is to use the keyboard or buttons to fly the player far away from the trashed area to a clean area. My fingers get tired, I get lost, and flying is so boring.
  2. A better way than flying is using “/tp @s ~200 ~0 ~0” in the command line to move relative to the player 200 east, 0 up, and 0 south — or however far and in which ever direction you like. Typing this makes me crazy because I must look at the keyboard for the symbols I rarely use. And, of course, I make mistakes. When using this method, I type the commands I use often into a text document, which I keep open,  and copy/paste to the command line. Efficient, but I don’t like having still yet another open file, and going back and forth to it is distracting.
  3. Make a program that with one easy-to-remember chat command moves the player to a clean positon. Move Me is such a program and  is described in this post.
  4. Make a program that restores the used world area to it’s pristine condition. Flat Fixer is described in another post.
  5. Create a new world. Way too time consuming, but I use it when I want a really, really clean world.

When developing a new program, especially when leaning a new language as I have been doing with MakeCode, I usually try the program many, many, many times until it works correctly and I have settled on the programs features. Move Me is my favorite way to get to a clean world area.

Move Me

With just one chat command using Move Me, the player is moved from the mess on the left  to the pristine field  on the right so far away from the mess that it can’t be seen.

Move Me CodeMove Me has two parameters (arguments): E and S, which specify the distance to move east and south, respectively. Of course, negative E is west and negative S is north, so the program allows movement in all four directions. If both parameters are 0, there would be no movement. This case is used to trigger the default values of 200 E and 0  S. If a parameter is omitted, its value is 0. Typing “run” in the command line with no values for E and S is equivalent to E=0 and S=0, which  triggers the defaults, and is the same as typing “run 200 0.”

Notice that the teleport block specifies a relative positon. It causes the player to be moved E blocks east and S blocks south of where the player started. The up coordinate moves 0 blocks, meaning the player stays in the same vertical position.

This program has one big advantage over manually flying to a new location. In manual flying it is easy to accidently return to an old used location. Using Move Me and moving the same direction every time, the player never accidently returns to an old trashed area. In most cases, I just use “run” with no parameters. The default always move east, so does not return to any prior position.

Move Me takes some of the pain out of debugging.

Get the Code

This code is sometimes susceptible to the Chat Command arguments bug described the our prior post.

The code is shared at https://makecode.com/_2Hx6oYW928EU  where it can be downloaded an run in MakeCode for Minecraft.

 

Lucy in the Sky with Diamonds in MakeCode for Minecraft

Lucy in the Sky with Diamonds was a popular 1960s Beatles tune.  Before you ask, yes, I am old enough to have been there. The screenshot below is from a little MakeCode chat command using a print block with text “Lucy” and diamonds to do the printing. 

lucy

lucy code 2There are a few things we can learn from this code about blocks, positions and directions.

Which blocks (e.g., diamonds, grass) can be used to write in the sky?. Change diamonds to sunflowers. What happens? Lava? Water?

The position  position  means 50 blocks east, 5 blocks high and 0 blocks south relative to the player; that is, from where the player is standing.

The phrase along gives the direction to print. I think of the player as facing east, so printing along South means printing left to right. What happens if the along phrase is changed to each of the following:

  •  along north ?
  • along west ?
  • along east ?

Keeping Score in the Sky

field scoreIn Grandma’s Chickens, I used a similar  function to keep score of how many chickens the player zapped.

run

The “run” chat command  is for testing the function printScore

The first say block signals that  the program is actually running. The last say block indicates when it is complete.  Why are these needed? Sometimes when “run” is typed into the command line, the program does not start. This may be because  start button , the start button, was not pressed. Other times are more mysterious, but I have found that when repeated attempts to start a program fail, restarting Minecraft and MakeCode solves the problem once again proving the old adage “When in doubt, reboot.”

In the chat command “run,” the original player world position is saved in the variable “center.”  This allows the player to move while the program is running. This is desirable because the view of the what’s happening in Minecraft is often better if the player is allowed to move to a different vantage point rather than being required to stay in one place because all positions are relative to the player and change as the player moves.

The repeat loop in “run” calls the printScore function 5 times to test randomly selected values for score..

printScore Func

The function printScore performs as its name indicates. It first converts the number variable score to text, which is required by the print block. The say block outputs the score to the log window.

In the print block, by joining txtScore with trailing  spaces, the digits of any longer number that had been previously printed to the same location are erased.

Pay particular attention to the manner in which position is specified by the at phrase. The position is not specified as relative to the current player world positon but, rather, as relative to the original player world position, which was saved in the variable  “center.” Notice that printScore coord is a world position, not relative. The print position is center X plus 40, center Y plus 5, center Z minus 5. The value of these coordinates were determined by trying various numbers to find a visually appealing  positon.

Demo of App and Code

Get the Code

The code for Print Score and Lucy is shared at https://makecode.com/_HpX7bY2ehM3H . It can be downloaded and run in MakeCode for Minecraft.

 

 

 

 

Go to Ground in MakeCode for Minecraft

MakeCode for Minecraft coders sometimes assume that the player will be on the ground when the program starts. There is no harm in this except that some programs do weird things if the user forgets to move the player to the ground before running it. Users may find the weirdness difficult to understand. A wise coder would teleport the player to the ground as a first step in a program.

In a flat world with no complex structures, the player is teleported to the ground with code block below.

Go to Ground 1a

We can test this statement by wrapping it in a Chat command.

Go to Ground 1

Try flying the Player to various locations in the sky, then run the chat command to verify that the player is indeed teleported to the ground with no change in the X and Z coordinates.

A Reusable Go-to-Ground Function

Although only a single block is required to teleport the player to the ground, the block is so wide that often it cannot be read without scrolling to the right. Further, recoding the block for many programs can get old, Recoding can also introduce bugs because some little mistake is made in the recoding. I have, for example, mistakenly coded the Z coordinate as X, since X is the default in the “position get value of” block. As a remedy to all these issues, I created a little function that can be copied  to any program where it is needed.

Go to Ground 3

To test the function, I created the chat command “goToGround” shown below.

Go to Ground 2

Get the Code

The code for Go to Ground is shared at https://makecode.com/_8HhHxbTxMiu3. It can be downloaded and run in MakeCode for Minecraft.