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.

Negative Random Number Tester in MakeCode for Minecraft

 

main

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

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

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

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

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

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

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

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

The Plan

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

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

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

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

The Code

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

code all

The run on chat command performs the following:

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

run code

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

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

print pcts code

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

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

The gray block indicates that rounding is done in JavaScript.

convert pct to text

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

pad code

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

print pos

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

Get the Code

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

https://makecode.com/_EfC4c9WCUcuR

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

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.

The Art of Random Walks in MakeCode for Minecraft

A random walk is the path traveled by taking a step, then randomly turning either left or right, then repeating: a step, a random turn, a step, a random turn, and so on. Although a random walk sounds simple and is easy to code, it is an enormously important subject in many branches of science, such as physics, biology, economics and mathematics. Google Scholar lists 2,380,000 academic research papers on the subject.

1000 2 1

The science of random walks is not the subject of this blog. Rather, our aims are  to improve our coding skills in MakeCode for Minecraft and to explore random walk patterns as art.

Demo and How It Works

Program Inputs

  1. steps — the number of steps in the walk, maximum 3000, default 100.
  2. stepSize — the number of blocks in a single step, maximum of 10, default 3.
  3. blockGroup — is the group of blocks that can be used to create a random walk. The values can be 0, 1 or 2, default 0.
    • blockGroup 0 is LapisLazuliBlock or TNT depending or the random direction  (left or right).
    • blockGroup 1 choses a block randomly from a colorful array of choices.
    • blockGroup 2 choses a block randomly from a variations of black choices.

The Code

A simple random walk program called Agent Wanderer is found on Microsoft MakeCode for Minecraft site. The code below provides more flexibility by providing three arguments (see above) and using the Builder, which is faster than the Agent. the code below is shared at https://makecode.com/_AF0cdjKVu4zq, where it can be downloaded and run in MakeCode for Minecraft.

Random Walk Code

The code also includes a few utility Chats or function, which I plan to document in other posts. The utilities are:

  • Move Me — moves the player to the east and/or south the specified number of blocks.  Good for moving to a clean spot in the world.
  • Handy Compass– prints directions on the sky asynchronously. Handy for knowing the direction a random walk moves.
  • Go to Ground — moves the player to be “on the ground,” which is Y=4 in a flat world.
  • Canvas — replaces grass over a large area to create a white background for a random walk.

Further Explorations

  1. Add code to determine the percentage of the time does a random walk wander to the north, to the south, and so on?
  2. Add a counter for the number of  right turns as opposed to left turns.
  3. Add a counter for the number of blocks that are south of the origin, east of the origin, and so on.
  4. How often does a walk return to land on  the origin block during its path?
  5. Instead of replacing blocks that have already been replaced, stack them; thus, counting the number of times each block has been traversed.

A particularly intriguing activity is to try replacing

run chat command dir

with

 

call function dirFunction
What happens? Why?  This will be covered soon in another blog.

 

 

 

Counting Random 0s and 1s in MakeCode for Minecraft

Real-world games like Monopoly and Yahtzee use dice rolls to pick random numbers. Arbitrary decision like who goes first or which end of the field a team starts are decided by the flip of coin, which can be thought of as a random number either 0 or 1.

A coin flip has a 50% chance of landing on heads and a 50% chance of landing on tails. This is called a “50/50 chance” or “50-50 chance,” which means the same thing. Heads or tails is a “binary” choice because  there are only two possible outcomes. Other binary choices include  yes or no, true or false and 0 or 1.

Computer games, including games written in MakeCode for Minecraft, also use random numbers to make the games interesting and  unpredictable. For example, the game Grandma’s Chickens uses random numbers to decide where and when lightening will strike killing chickens and burning holes in the fence so that the chickens can escape.

If you flip a coin 20 times, will it land on heads 10 times and tails 10 times? You might think so because the chances are 50/50. But does it?

Let’s Experiment Using MakeCode for Minecraft

We’ll explore this by using MakeCode for Minecraft  to pick a random numbers that are either 0 or 1, where. 1 will represent heads, 0 tails. The MakeCode block that picks a random number that is either 0 or 1 is

random 0 to 1

By picking 20 such numbers and counting 1’s and 0’s separately,  we might be able to answer our question. The result of our code will be similar to that shown below. The yellow blocks are the count of 0’s, the blue blocks 1’s. The output from three runs of the program are shown.

50 50

Only one of these three results picked 10 0’s and 10 1’s. In the lingo of heads and tails, one time we tossed a coin 20 times, the result was 13 tails and 7 heads, another was 11 tails and 9 heads and the last was 10 tails and 10 heads. Why? Two reasons:

  1. 20 random numbers is a ridiculously small sample. I bet you have experienced this in games when it seems like dice throws are anything but random.
  2. These are computer-generated random numbers, which are called “pseudorandom numbers” because they are not perfectly random.

Let’s see the code in action.

The Code

The MakeCode for Minecraft file is available at this URL https://makecode.com/_eE2HJCDXU81R, which can be pasted into a browser or imported in MakeCode for Minecraft. The code below is explained in the above video.

Count 1 and 0 Code

 

Grandma’s Chickens v2.0

See more demonstration and code for Grandma’s Chickens is in More Grandma’s Chickens 2.0.

Chicken Rain, a tutorial program on Microsoft’s Code Connection Microsoft Makecode, was the inspiration for our game Grandma’s Chickens. We stayed motivated while learning Makecode for Minecraft by modifying Chicken Rain until it became this version of the game. We have several more ideas for improvements, but first we will explore the code for this version.