Skip to content

Instantly share code, notes, and snippets.

@mwufi
Created February 7, 2019 21:03
Show Gist options
  • Save mwufi/dfb320c107c88a2a3470b1740a66b3d5 to your computer and use it in GitHub Desktop.
Save mwufi/dfb320c107c88a2a3470b1740a66b3d5 to your computer and use it in GitHub Desktop.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import curses
import sys
from pycolab import ascii_art
from pycolab import human_ui
from pycolab import things as plab_things
from pycolab.prefab_parts import sprites as prefab_sprites
from six.moves import xrange # pylint: disable=redefined-builtin
LEVELS = [
# the only level
[
'##############################',
'# ....... A E#',
'############### ############',
'# ** * #',
'##############################',
]
]
FG_COLOURS = {
'A': (999, 500, 0), # Player wears an orange jumpsuit.
'#': (700, 700, 700), # Normal wall, bright grey.
' ': (200, 200, 200), # Floor.
'.': (0, 250, 0), # Spikes.
'*': (0, 200, 200), # Berries.
'E': (0, 200, 200), # Exit!
}
BG_COLOURS = {
'A': (200, 200, 200),
'#': (800, 800, 800),
'.': (100, 300, 100),
'*': (999, 800, 800),
' ': (200, 200, 200),
'E': (999, 800, 800),
}
class PlayerSprite(prefab_sprites.MazeWalker):
"""The player
parent class handles basic movement + collision detection. The
special drape handles the consumption of berries?
"""
def __init__(self, corner, position, character):
super(PlayerSprite, self).__init__(
corner, position, character, impassable='#')
def update(self, actions, board, layers, backdrop, things, the_plot):
del backdrop # Unused.
# Handles basic movement
if actions == 0: # go upward?
self._north(board, the_plot)
elif actions == 1: # go downward?
self._south(board, the_plot)
elif actions == 2: # go leftward?
self._west(board, the_plot)
elif actions == 3: # go rightward?
self._east(board, the_plot)
elif actions == 9: # quit?
the_plot.terminate_episode()
# Did we walk into a spike? If so, we win!
if layers['.'][self.position]:
the_plot.add_reward(-1)
# Did we walk into a berry? If so, we win!
if layers['*'][self.position]:
the_plot.add_reward(10)
# Did we walk into an exit? If so, we win!
if layers['E'][self.position]:
the_plot.terminate_episode()
def make_game(level_idx):
"""level_idx has to be 0, because we only have 1 level
"""
return ascii_art.ascii_art_to_game(
art=LEVELS[level_idx],
what_lies_beneath=' ',
sprites={'A': PlayerSprite},
update_schedule=[['A']],
z_order=['A'])
def main(argv=()):
game = make_game(int(argv[1]) if len(argv) > 1 else 0)
ui = human_ui.CursesUi(
keys_to_actions={
# Basic movement.
curses.KEY_UP: 0,
curses.KEY_DOWN: 1,
curses.KEY_LEFT: 2,
curses.KEY_RIGHT: 3,
-1: 4, # Do nothing.
# Quit game.
'q': 9,
'Q': 9,
},
delay=50,
colour_fg=FG_COLOURS,
colour_bg=BG_COLOURS)
ui.play(game)
if __name__ == "__main__":
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment