Esempio n. 1
0
    def __call__(self, screen, replay=True, *args, **kwargs):
        try:
            if replay == True:
                self.engine.listeners.add(self.listener)
                self.engine.fast_forward()
                self.progress(screen)
            else:
                self.engine.fast_forward()
                self.engine.listeners.add(self.listener)

            StaticAnimation().render(screen, self.engine.state)

            while self.engine.complete == False:
                StaticAnimation().render(screen, self.engine.state)
                try:
                    self.engine.record()
                except units.RequiresInput:
                    self.draw_health(screen)
                    self.highlight_char(screen)
                    action = self.get_input(screen)
                    self.engine.current_actor.set_next_action(action)
                    continue
                except utils.InvalidMove as e:
                    self.message(screen, e.message)
                    continue

                # Render
                self.progress(screen)

        except QuitError:
            with open(utils.data_file("autosave.json"), 'w') as f:
                f.write(json.dumps(self.engine.past, indent=2))
            from ui.cursesUI.titleScreen import TitleScreen
            return TitleScreen()
        except:
            with open(utils.data_file("autosave.json"), 'w') as f:
                f.write(json.dumps(self.engine.past, indent=2))
                raise

        if self.engine.complete and 'red' in self.engine.remaining_teams:
            if self.level > MAX_LEVELS:
                from ui.cursesUI.titleScreen import TitleScreen
                return TitleScreen()
            self.message(screen, "Congrats, you've beaten the level")
            return LevelScreen(self.level + 1)
        else:
            self.message(screen, "I'm sorry, you've died.")
            from ui.cursesUI.titleScreen import TitleScreen
            return TitleScreen()

        logger.debug("Game Complete")
Esempio n. 2
0
def get_background():
    background = curses.newwin(28, 58)
    background.border()

    with open(utils.data_file('background.txt')) as f:
        for i, row in enumerate(f.readlines(), start=1):
            background.addstr(i, 1, row[:-1], curses.A_DIM)

    return background
Esempio n. 3
0
def load_level(filename):
    """Load a level from a history file."""
    result = []
    with open(utils.data_file(filename), 'r') as f:
        level = json.loads(f.read())
    for turn in level:
        computed = []
        for action in turn:
            computed.append(
                CreateAction(action)
            )  # Turn every action into an action object, not just a dict
        result.append(computed)
    return result
Esempio n. 4
0
    def __call__(self, stdscr):
        win = curses.newwin(28, 58)
        win.border()
        stdscr.timeout(100)

        file_path = utils.data_file('TitleScreen.txt')
        with open(file_path, 'r') as f:
            for i, line in enumerate(f.readlines()):
                win.addstr(i + 2, 1, line.rstrip(), self.get_color(i))

        # Scrolling thanks.
        thanks_iterator = cycle(range(0, len(self.THANKS)))

        for i in thanks_iterator:
            win.overwrite(stdscr)
            thanks = self.THANKS[i:] + self.THANKS[:i]
            stdscr.addstr(24, 1, thanks[:56])

            result = self.handle(stdscr.getch())
            if result:
                return result
Esempio n. 5
0
    def __init__(self):
        super(LoadingSplash, self).__init__()

        splash_path = utils.data_file("resources/uv-cdat-splash.svg")

        import cdat_info

        with open(splash_path) as splash_file:
            splash = splash_file.read()

        cdat_version = cdat_info.version()
        font_size = 39 if isinstance(cdat_version[-1], int) else 22
        cdat_version = ".".join([str(p) for p in cdat_version])
        splash = splash.format(cdat_version=cdat_version,
                               version_font=font_size,
                               gui_version=QtGui.qApp.applicationVersion())
        import tempfile
        _, path = tempfile.mkstemp()
        with open(path, 'w') as f:
            f.write(splash)
        pixmap = QtGui.QPixmap(path, "svg")
        os.remove(path)
        self.setPixmap(pixmap)
Esempio n. 6
0
def generate_level(number):
    with open(utils.data_file('levels.json'), 'r') as f:
        data = json.load(f)
        level = data[str(number)]

    results = []
    remaining_cells = copy.copy(grid.VALID_CELLS)

    # Add a hero
    results.append(
        CreateAction({
            "type": "Spawn",
            "target": [10, 0],
            "element": {
                "type": "Hero",
                "team": "red"
            }
        }))
    remaining_cells.remove((10, 0))

    # Add the enemies
    for kind, count in level.items():
        for i in range(0, count):
            location = random.choice(remaining_cells)
            results.append(
                CreateAction({
                    "type": "Spawn",
                    "target": location,
                    "element": {
                        "type": kind,
                        "team": "blue"
                    }
                }))
            remaining_cells.remove(location)
    logger.info(results)

    return [results]
Esempio n. 7
0
from collections import defaultdict
import json

import utils
import abilities

import logging
logger = logging.getLogger(__name__)

# Load the defaults for the various Game Elements from a file.
with open(utils.data_file("elements.json")) as f:
    INITIAL_DATA = json.load(f)


class RequiresInput(utils.HopliteError):
    """Error used to notify the UI that the current actor requires user input"""
    pass


class Unit(dict):
    """Class used for all Game Elements (With the exception of heroes, who subclass it).
       It's implemented following a Entity-Component Model."""

    # Create a counter for each type of game element.  Used to assign IDs.
    counters = defaultdict(lambda: utils.Counter())

    def __init__(self, **kwargs):
        super(Unit, self).__init__(**kwargs)
        type = kwargs['type']  # Grab type from kwargs, for cleanliness
        initial_data = INITIAL_DATA[type]  # Get the Unit's INITIAL_DATA