Lesson 5

Infinite loop

So far these programs start and end after a few command sequences. Now you will start a repeating loop so a process can take place and continue while you run around in the game. You will use a while True loop to begin.

The program below allows you to hit any block with a sword and turn it into pure GOLD! Here are some important concepts to note in the following program.

  • The keyword while True: starts a block of code that never stops. Everything INDENTED below it will happen over and over again.
  • The indents are very important in Python. The Python interpreter uses them to know what should repeat. Anything not indented does not repeat.
  • The for loop contained within is called a for each loop. It reads "for each block hit detected, save the hit's x,y,z position, then set a gold block in its place."
  • The pollBlockHits() method only registers blocks being hit by a sword! So the game has to be put in Creative mode by the teacher, then you have to get a sword from the unlimited inventory and hold it in your hand (if you don't know how just ask).

Important: There is nothing to stop this loop! The only way to interrupt a program from running if it has no way to end an infinite loop is to go back to Terminal and hit the control + c keys.

Did you have fun turning things into gold?

Now let's implement a system where some action can break out of the infinite loop and the program can be stopped from within the game. Here's one way:

  • Line 5: Create a variable that stores the position of the tile under the player. Call it "endGameBlock" because that will be the one you hit to end the game.
  • Line 6: Turn that block to diamond
  • Line 7: Create a "playing" variable and set it to True. This is a "boolean" type variable that can be either True or False.
  • Line 8: Instead of while True, start the loop with while playing. This is shorthand for "while playing is true"
  • Line 12: If the position of the block hit is the same as the endGameBlock from the start of the game, set the playing variable to False.
  • Line 14: If the block hit is NOT the same as the endGameBlock, turn the hit block to gold.
  • Line 19: Post to chat a game over message. Note that this is fully OUTDENTED, so it is not a part of the while playing loop. It happens AFTER that loop is finished.

Lesson 5 is done! Don't forget to answer questions for Lesson 5 in MyHewitt.