Skip to content

Instantly share code, notes, and snippets.

@cglosser
Last active April 9, 2017 23:10
Show Gist options
  • Save cglosser/60dc1c80b8fab5a8808cb07f9fb273bc to your computer and use it in GitHub Desktop.
Save cglosser/60dc1c80b8fab5a8808cb07f9fb273bc to your computer and use it in GitHub Desktop.
*Basic* rule implementation of the Lunar Lockout puzzle game
import numpy as np
class Robot(object):
def __init__(self, pos, icon):
self.pos = pos
self.icon = icon
def move(self, dx):
self.pos += dx
def at(self, pos):
return self.pos == pos
class Game(object):
# This is *totally* backwards from (x,y) pairs/unit vectors because
# of row/column indexing for matrices.
directions = {
"up" : np.array([-1, 0]),
"down" : np.array([1, 0]),
"left" : np.array([0, -1]),
"right" : np.array([0, 1])
}
def __init__(self, robots, target = None):
self.robots = robots
if target is None:
self.target = np.array([2, 2])
else:
self.target = target
def draw(self):
# Easiest way to "draw" the gameboard is to put together one string and print it out
row = " |\n"
board = list(row*5) #...but strings are immutable, so we first build a list and then combine it into one string at the end
for robot in self.robots:
r, c = robot.pos
# len(row)*r + c turns a robot's position, (r,c), into a position in the string
board[len(row)*r + c] = robot.icon
return "".join(board) + "-"*(len(row) - 1)
def update(self, botID, d):
for idx, robot in enumerate(self.robots):
if botID == idx: continue
# This checks to see if the selected 'bot "slides" into another
# If so, move the bot to the correct position
for dx in range(5):
coord = self.robots[botID].pos + dx*Game.directions[d]
if (coord == robot.pos).all():
self.robots[botID].move((dx - 1)*Game.directions[d])
def play(self):
print("Move the astronaut (0) to the center of the grid!")
print(self.draw())
while (self.robots[0].pos != self.target).any():
print("\n\n")
try: # The try/except just "ignores" improper input
idx, direction = input("Enter an index and direction: ").split()
idx = int(idx)
self.update(idx, direction)
except ValueError:
pass
print(self.draw())
else:
print("You win! Toutes mes félicitations!")
# Specify the initial position of every robot (the Robot at index 0 is the astronaut)
robots = [
Robot(np.array([4, 4]), "0"), #astronaut -- must get to center of box!
Robot(np.array([0, 4]), "1"),
Robot(np.array([3, 3]), "2"),
Robot(np.array([1, 2]), "3"),
Robot(np.array([2, 1]), "4"),
]
if __name__ == "__main__":
g = Game(robots)
g.play() # Play the game :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment