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.

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.

More Grandma’s Chickens 2.0: A Makecode for Minecraft Game

 

Grandma’s Chickens is a game in which the player kills as many chickens as possible racing against the lightning strikes that may kill  chickens  and ocelots that may  eat them before the player can score a kill. Also, lightning might strike the fence making a hole through which chickens can escape.

A cowardly (or impatient) player will choose to use the sword, which is provided in the player inventory. In this case, chickens are killed with a single strike and the fence and ground will not be destroyed accidently. A more difficult version is to use the hand rather than the sword. In this case, it takes a few strikes to kill each chicken and it is frustratingly easy to accidently make holes in the fence or ground. During all this action, the score is updated in the sky. The game can be varied using the on-chat arguments for the size of the fence, the number of chickens and the number of ocelots.

Field GrandmasChickens

Strategy for the Design of the Grandma’s Chickens Game

The strategy for building Grandma’s Chickens was to spawn chickens and ocelots at random positions inside a wooden fence with the player at the center. The player can start killing chickens while they are being  spawned. The on-chicken-killed event keeps score and every few kills randomly spawns a lightning bolt at a random position inside and including the fence. If lightning strikes the fence, a hole is burned in the fence through which chickens can escape. When a chicken is killed, the score is updated by the on-chicken-killed event and printed in the sky.

The Code for Grandma’s Chickens

The key code is the on-chat command “run” and the on-chicken-killed event.

The steps for then on-chat command “run” and described in the following paragraphs.

Step 1: Set the global variable origin, which will be where the west-north corner of the fence is positioned.

Step 2: Store the arguments in global variables– nBLocksPerFenceSide, nChickens and nOcelots. Check the variables for allowed values, switching to defaults if needed. Say these values before and after the validity checks to be sure there is not a problem, like the one described in a MakeCode for Minecraft on Chat Command Arguments Problem (Bug?). Notice that if no arguments are given — “run” — the values are all zero and the defaults are used.

GrandmasChickes Code 1
Grandma’s Chickens Part 1 of 4

Step 3: Calculate fence parameters including the west-north corner (same as origin), the opposing east-south corner  and the center. If the argument for the number of blocks per side is even, increase it d by 1 so that it is odd. This enables an exact center block for the fence; that is, the center block has the exact same number of blocks on the left, right, in front and behind. Yes, I realize that this is being a bit too meticulous. It’s a programmer thing.

GrandmasChickes Code 2

Grandma’s Chickens Run —  Part 2 of 4

Step 4: Move the player to just outside the fence so she will not be in the way. Yes, I know that this is probably not necessary.

Step 5: Build the fence according to the previously calculated parameters.

Step 6: Call the function makeEastPointerFromOrigin, which helps the programmer visualize the fence construction.

Step 7: Give the player a sword to provide the option of striking chickens with a more powerful weapon than just the hand. Using a sword makes the game easier to play, but personally, I prefer the more difficult version using the hand.

Step 8: Initialize the score to zero and print it in the sky.

GrandmasChickes Code 3

Grandma’s Chickens Run —  Part 3 of 4

Step 9: Set the boundaries for spawning chickens and ocelots one block inside the fence. Spawn the number of chickens and ocelots specified by the global variables nChickens and nOcelots, which were set to the values passed in the on-chat arguments or to the default values if on-chat had no arguments or were invalid values.

GrandmasChickes Code 4

Grandma’s Chickens Run —  Part 4 of 4

Grandmas chickens on start On start initializes the values for the global variables. Here it was automatically generated by MakeCode as JavaScript statements. 

An essential part of the Grandma’s Chickens game is the on-animal-chicken-killed event, which  is run when a chicken is killed by the player. Each time the event is triggered, 1 is added to the score and the score is printed in the sky. A random number is picked from the sequence 0, 1, 2. If the random number is 1, a lightning -bolt projectile is spawned at or inside the fence. The number 1 is arbitrary and could have been any of the three number 0, 1 or 2. It simply enables a 1 in 3 chance of the lightning striking.  If the lightning hits the fence, it burns a hole in the fence through which chickens and ocelots can escape. The lightning also sets fire to the grass, which can be annoying when one is in a panic to kill chickens.

Grandmas Chickens kill
grandmas chickens giveswords

The function giveMeSwords first clears the player’s inventory and then gives the player a sword that can be used to kill chickens more efficiently than just the hand. A function was chosen to implement this code rather than coding it inline, so that other items could be easily added to the player inventory to experiment with the game without cluttering the main code. For example, I have considered providing fence blocks so that the player can repair the fence.

Don’t Worry About the Chickens

I know you might be concerned about all those chickens being killed. Don’t be. They were born to be eaten by the hungry folks in the Minecraft world. On the humble farm where I grew up, chickens were feast food. I can still remember the anticipation of a festive meal when my mother was in the yard plucking the chicken feathers from a fine bird that my father had just killed.

Of course, We Are Working on Grandma’s Chickens 3.0

We have lots of ideas for making Grandma’s Chickens even more interesting and fun. We hope you have some, too. We would very much like for you to build on our code.

Get the Code

Grandma’s Chickens 2.0  code is shared on Code Connection at this URL

 https://makecode.com/_RFUKHraM7Tbp

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.

Bang! — Simulating an On-TNT-Exploded Event in MakeCode for Minecraft

 

Bang Code

The Bang program  places TNT in the ground of a flat world. It then places a  flint and steel item in the player inventory. The player is teleported to within a few blocks above the TNT so that the TNT can be ignited. 

I wanted the player to be way high above the TNT area so that the full effect of the explosion could be seen. After igniting the TNT, it is hard to manually fly the player rapidly enough and high enough to catch the full view. What I needed was a TNT-Exploded event that, when triggered, would teleport the player high enough to get the desired view. But after reading, searching and experimenting, I didn’t find a way to do this with MakeCode’s built-in events (e.g., on block destroyed).

My solution was to simulate a TNT-Exploded event. The key idea was that after the event is enabled, it repeatedly tests the block under origin. The block is originally grass,  then replaced by TNT, and  when the TNT explodes, it is destroyed and replaced by air. When the event is enabled and the test for air succeeds, the TNT has exploded and the player is teleported high in the sky.

Before running bang, be sure the player is flying; otherwise, she will fall all the way to  bedrock after the teleport. I would like to find a way to programmatically put the player in flying mode, but haven’t found it as of this writing.

The implementation of the TNT-Exploded event uses the global variable TNT_eventEnabled, which is false until the TNT is in place and the player is in position to ignite it. Once the event is enabled, the forever loop, which runs repeatedly, proceeds to test for air under origin. When air is found, the player is teleported sky high and the event is disabled so that it will run only once for each run of bang.

Event

Bang is a companion program to Flat Fixer. Using the two programs, Bang can make a mess and Flat Fixer can clean it up again and again and …

Get the Code

Bang! code is shared on Code Connection at this URL

https://makecode.com/_LC4dzUPe4bYg

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.

Builder Fence with Size and Block Arguments in MakeCode for Minecraft

 

I had wanted to build a fence from the first day I saw MakeCode for Minecraft. Why? To hold all those raining chickens, of course, Due to one of my most endearing flaws, I couldn’t just build a simple, straight-forward fence. I set out to discover the easies, most understandable and fastest way to build a fence using MakeCode  in the Minecraft world.

I explored fences using MakeCode fill, line, and place . I giggled as I watched that funny little agent struggle to build a fence. I compared and raced various fence algorithms against each other. All that exploration may be the subject of a future post, but this post is about the winner (so far) — a fence using the MakeCode builder.

Although I started with a simple fence with a fixed size and material, I wasn’t content with that. I wanted a “utility” fence that I could use in various programs. To that end, I added an argument (parameter) so that the fence could be any size, although it is limited to being square. I also added an argument to specify the material (e.g., wood, stone) from which the fence is constructed. Two fences are shown below.

fence field stone and wood

How Builder Fence Works

The on chat command that launches Builder Fence has two arguments. num1 is the number of blocks per side. num2 is the index of the block to be used to build the fence. Notice that nBlocksPerSide and fenceBlockIndex are global variables, which are set to the respective values of the arguments. The arguments num1 and num2 should not be used as global variable unless you want to make yourself really crazy. The global variables are required because in MakeCode blocks, functions cannot have arguments — too bad, but maybe someday …

The two global variables are not validated here because they are validated in the buildFence function. After the global variables are set, the function setOrigin is called before the function builderFence is called.

Builder Fence Code

The array fenceChoices contains blocks that can be chosen for the fence. The on chat  argument num2, which is stored in global variable fenceBlockIndex may have values 0, 1 or 2 specifying the wood, stone or sunflower fence, respectively. More choices can be added to this array, and doing so does not require any other change to the builderFence code.

Builder Fence Code 4

The function builderFence (below) does the magic. It expects two global variables to have been set prior to calling it: nBlocksPerSide and fenceBlockIndex. The function validateBuilderFenceParams is called to make sure the two global variables are within the allowed values, and, if not, are set to default values. builderFence then calls makeEastPointerFromOrigin and setOrigin, which sets origin if it has not been already set. After this initialization, the real fence-building action starts.

The main part of builderFence starts when the builder teleports to origin. By facing the builder East and doing right turns, the fence will be to the east-south  of origin (the positive X and Z quadrant). This knowledge may be important to a program that calls builderFence.

Builder Fence Code 2

The mark placed by the builder just before the repeat block, is be the starting place of a path that will be traced. During each of the four passes through the repat loop, the builder moves forward one block fewer than nBlocksPerSide then turns right. One  fewer blocks is required because the builder  is standing on one of the blocks before it  moves making the total blocks on each side be the correct number. Only after the builder has traveled the entire path (after the loop), the builder does the trace path with the block from the array fenceChoices designated by fenceBlockIndex

Future Fences

An obvious upgrade to the fence described here, is to enable the fence to have a different width and length rather than be square. Also, other fence material options would be good. I have also experimented with fences that are more than one block high.

Get the Code

Builder Fence  code is shared on Code Connection at this URL

https://makecode.com/_RHMLRD0KUXeC

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.

MakeCode for Minecraft on Chat Command Arguments Problem (Bug?)

I have been stymied by this problem for a couple of months. Because I was just learning MakeCode for Minecraft, I first assumed that either I did not understand Chat arguments or that I had misused them. This problem was exacerbated by the fact it was intermittent, that it, sometimes it happened and sometimes it didn’t.

After much experimentation, I am convinced that the problem is with MakeCode for Minecraft itself, not my code. Yes, I know this sounds ridiculously arrogant, because most of time we coders think a bug is being caused by something outside our program, we are usually wrong.

Consider the two Chat Commands below: moveme and test. Each has two arguments. They differ only in the name of the Chat Command and the names of the arguments. Both programs say the values of the arguments to the Command window.

MC

The JavaScript is shown below.

js

The Command window shows that test shows the correct values for the arguments, but Moveme shows the arguments as 0 0, not 3 5, which was specified on the on Chat line of code.

mov2

Interestingly, if the moveMe Chat Command name is changed, the runs correctly. Even more interestingly as shown in the video above, it the name is changed back to moveMe, the bug reappears.

Get the Code

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