https://s3-us-west-2.amazonaws.com/secure.notion-static.com/92d437ae-6589-4bfe-aff1-29a5e5133dbd/10-game-starting-in-5.png

In this last exercise, we’ll create a mini game in Minecraft with Python.

What you’ll learn:

# Killer Drop
# Race from one end of the course to the other while blocks randomly disappear beneath you!
# Jim Christian
# Coding in Minecraft

# Import the Minecraft API
import mcpi.minecraft as minecraft
import mcpi.block as block
import time
import random

# Set the variables
height = 10
maxrange = 10
gameTime = 20

# Create the connection to minecraft
mc = minecraft.Minecraft.create()
# Get the player's position
pos = mc.player.getPos()
# Convert player position numbers
pos = minecraft.Vec3(int(pos.x), int(pos.y), int(pos.z))

# This function creates a grid of randomly selected Minecraft blocks
def randomAdd():
    # loops for maxrange
    for up in range(0,maxrange):
        field = random.randint(12,49)
        mc.setBlocks(pos.x, pos.y + height, pos.z, pos.x+1, pos.y + height, pos.z, field)
        pos.x = pos.x + 1
    time.sleep(1)
    
# This function changes the blocks around the player to air two times a second.    
def randomRemove():
    field = 0
    for up in range(0, gameTime*2):
        area = random.randint(0,2)
        pos = mc.player.getTilePos()
        addX = pos.x + area
        minusX = pos.x - area
        addZ = pos.z + area
        minusZ = pos.z - area
        varsX = [addX, minusX]
        varsZ = [addZ, minusZ]
        mc.setBlock(random.sample(varsX, 1), pos.y - 1, random.sample(varsZ, 1), field)
        time.sleep(.5)

# This function runs the randomAdd function, then resets the starting point to complete the game grid.
def setGrid():
    mc.postToChat("Building the grid.")
    time.sleep(2)
    mc.postToChat("Watch out for falling blocks!")
    #loops for maxrange
    for up in range(0,maxrange):
        randomAdd()
        pos.x = pos.x - maxrange
        pos.z = pos.z + 1
    time.sleep(1)

# This function moves the player to the gaming grid and puts a stone block underneath them, just in case.
def movePlayer():
    mc.setBlock(pos.x, pos.y + height, pos.z - 5, 1)
    time.sleep(1)
    mc.player.setPos(pos.x, pos.y + (height+5), pos.z - 5)

def startGame(n):
    # Set the game grid
    setGrid()
    # Begin the countdown
    mc.postToChat("Game starting in...")
    while n > 0:
        mc.postToChat(str(n) + "...")
        n = n -1
        time.sleep(1)
    mc.postToChat("Start!")
    # Move the player to the game grid
    movePlayer()
    time.sleep(2)
    # Start removing blocks!
    randomRemove()
    mc.postToChat("Game Over.")
    
startGame(5)