Coordinates Game in MakeCode for Minecraft

 

begin game

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

finish green

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

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

How to Play

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

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

The game loop, simply put is:

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

Code Design

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

drawing

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

The Code

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

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

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

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

all code with labels

run on-chat command

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

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

run code

Display  New Position Coordinates

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

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

postNewCoordinate

Available-Positions List

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

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

init array code

The get available position function does the following:

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

get available code

Process on-broken events

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

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

break code

Repairs

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

do repairs

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

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

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

fix red and green

axes markers

repair grass

Code Requires a Flat World

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

Get the Code

Coordinates Game code is shared on Code Connection at this URL

https://makecode.com/_8vKbsj7diit1

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

Negative Random Number Tester in MakeCode for Minecraft

 

main

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

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

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

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

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

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

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

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

The Plan

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

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

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

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

The Code

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

code all

The run on chat command performs the following:

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

run code

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

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

print pcts code

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

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

The gray block indicates that rounding is done in JavaScript.

convert pct to text

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

pad code

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

print pos

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

Get the Code

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

https://makecode.com/_EfC4c9WCUcuR

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

Faster FISH Print in MakeCode for Minecraft Aquarium

 

FISH

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

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

The Code

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

LOOPS

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

replace block code

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

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

code all.png

Aquarium code with new print routines.

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

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

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

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

prints.png

The four new print routines.

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

one print

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

Faster, Smaller and Easier to Understand

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

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

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

Get the Code

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

https://makecode.com/_YALWi6RbUXe2

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

Aquarium in MakeCode for Minecraft

 

main

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

glass view from door

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

at glass

A look through the glass of the main fish tank.

inside top view

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

inside tank

From inside the main fish tank.

from inside

Aquarium interior

slime in pool 2

Slime seems to be attracted to the salmon tank.

The Design

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

building from above

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

plan

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

Space and Time Challenges

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

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

print embedded

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

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

The Code

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

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

ALL CODE LABELED

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

run on-chat command

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

run code

Beware of Common Variables in Asynchronous Code

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

Set Dimensions and Define Corner Positions of Structures

define dims

define corners

Build Outer Building and Foundation

outer building code

do outer door

do foundation code

Build Tank and Populate with Fish

do tank code

do tank interior code

AQUA THINGS CODE

Build Porch

pool code
porch entry code

Build Two Porch Pools and Populate with Dolphins and Salmon

TWO POOLS CODE

pool code

Fast Print “FISH”

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

print fish one letter

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

print fish several letters

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

print fish main

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

Get the Code

Aquarium code is shared on Code Connection at this URL

https://makecode.com/_0kDWR4UsX9KP

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

Coordinates Tutor in MakeCode for Minecraft

 

main screen

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

How to Play Coordinates Tutor

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

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

{  X  Y  Z  }.

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

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

broken block

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

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

coor display

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

The MakeCode Code

The Code Assumes a Flat World

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

Coordinates Tutor Starts with the Run Command

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

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

run code

The Action Is in the Broken Events

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

The doBrokenEvent function does the following:

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

on break code

Searching for Air

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

find air code

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

test try position code

The MakeCode Bug that Wasn’t

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

Print the Broken Block Coordinate

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

post coordinates code

Simultaneous, Oscillating Print Until … Something Happens

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

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

print q flasher code

Get the Code

Coordinates Tutor  code is shared on Code Connection at this URL

https://makecode.com/_d7PAhvEH98iy

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

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

 

main

Strategy

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

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

MakeCode Code

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

The placeButtons Function

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

Call the placeButtons Function

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

on start and moveme

Code the on-broken Events

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

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

all buttons code

Get the Code

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

https://makecode.com/_iwCgCd5bsFxY

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

How to Use Shared MakeCode on Microsoft Code Connection for Minecraft

 

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

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

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

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

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

Step 2. Start Minecraft and Code Connection

code connection link to minecraft

Step 3. Link Code Connection to Minecraft

Copy the link from Code Connection by

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

Start a game in Minecraft and choose a world.

Choose world.png

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

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

Chat window with link

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

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

code connection language choices

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

side by side 2

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

after new projects button.png

Step 4. Load a MakeCode Program

side by side 2

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

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

Import choices

Step 5. Import a Shared MakeCode Program

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

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

Click the Go ahead! button go ahead button

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

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

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

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

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

 

field 70 seconds

Handy Timer

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

Handy Timer Strategy

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

The Code

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

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

Forever Loop: The Guts of Handy Timer

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

forever code

on-chat commands Control the Timer

The following on-chat commands control the timer:

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

go stop reset chat code

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

on start and reset code

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

delta code

moveMe chat Command

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

Is Handy Timer Accurate?

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

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

Handy Timer’s Future

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

We Will Do More Block-by-Block Tutorial Videos

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

Get the Code

Handy Timer code is shared on Code Connection at this URL

https://makecode.com/_3C89FjDJaEbR

To get and use the code, follow these steps.

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

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

Import Copy link

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

Click the Go ahead! button go ahead button.

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

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

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.