Skip to content
This repository has been archived by the owner on Aug 7, 2024. It is now read-only.

Commit

Permalink
Merge 89b7709 into d4511aa
Browse files Browse the repository at this point in the history
  • Loading branch information
danalex97 authored Aug 31, 2017
2 parents d4511aa + 89b7709 commit 7013c0b
Show file tree
Hide file tree
Showing 23 changed files with 636 additions and 81 deletions.
2 changes: 0 additions & 2 deletions aimmo-game-creator/tests/test_worker_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@
from json import dumps

from httmock import HTTMock

from worker_manager import WorkerManager


class ConcreteWorkerManager(WorkerManager):
def __init__(self, *args, **kwargs):
self.final_workers = set()
Expand Down
112 changes: 112 additions & 0 deletions aimmo-game/simulation/custom_map.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import abc

from simulation.levels.levels import LEVELS

from simulation.location import Location
from simulation.game_state import GameState
from simulation.world_map import WorldMap
from simulation.world_map import WorldMapStaticSpawnDecorator
from simulation.world_map import DEFAULT_LEVEL_SETTINGS
from simulation.world_map import Cell

from simulation.pickups import HealthPickup
from simulation.pickups import InvulnerabilityPickup
from simulation.pickups import DamagePickup

class BaseGenerator(object):
__metaclass__ = abc.ABCMeta

def __init__(self, settings):
self.settings = settings

def get_game_state(self, avatar_manager):
return GameState(self.get_map(), avatar_manager, self.check_complete)

def check_complete(self, game_state):
return False

@abc.abstractmethod
def get_map(self):
pass

class BaseLevelGenerator(BaseGenerator):
__metaclass__ = abc.ABCMeta

def __init__(self, *args, **kwargs):
super(BaseLevelGenerator, self).__init__(*args, **kwargs)
self.settings.update(DEFAULT_LEVEL_SETTINGS)

class TemplateLevelGenerator(BaseLevelGenerator):
__metaclass__ = abc.ABCMeta

def __init__(self, *args, **kwargs):
super(TemplateLevelGenerator, self).__init__(*args, **kwargs)
self.settings.update(DEFAULT_LEVEL_SETTINGS)

################################################################################

class Decoder():
__metaclass__ = abc.ABCMeta

def __init__(self, code):
self.code = code

@abc.abstractmethod
def decode(self, json, world_map):
pass

class ScoreCellDecoder(Decoder):
def decode(self, json, world_map):
x, y = int(json["x"]), int(json["y"])
world_map = WorldMapStaticSpawnDecorator(world_map, Location(x, y))
world_map.get_cell(Location(x, y)).generates_score = True

class ObstacleDecoder(Decoder):
def decode(self, json, world_map):
x, y = int(json["x"]), int(json["y"])
world_map.get_cell(Location(x, y)).habitable = False

class PickupDecoder(Decoder):
def decode(self, json, world_map):
x, y = int(json["x"]), int(json["y"])
if json["type"] == "invulnerability":
world_map.get_cell(Location(x, y)).pickup = InvulnerabilityPickup(Location(x, y))
if json["type"] == "health":
world_map.get_cell(Location(x, y)).pickup = HealthPickup(Location(x, y), int(json["health_restored"]))
if json["type"] == "damage":
world_map.get_cell(Location(x, y)).pickup = DamagePickup(Location(x, y))

################################################################################

class JsonLevelGenerator(TemplateLevelGenerator):
def _register_json(self, json_map):
self.json_map = json_map
self.world_map = WorldMap.generate_empty_map(15, 15, self.settings)

def _register_decoders(self):
self.decoders = [
ScoreCellDecoder("2"),
ObstacleDecoder("1"),
PickupDecoder("3"),
PickupDecoder("4"),
PickupDecoder("5")
]

def _json_decode_map(self):
def find_element_by_code(json, code):
for element in json:
if element["code"] == str(code):
yield element

for decoder in self.decoders:
for element in find_element_by_code(self.json_map, decoder.code):
decoder.decode(element, self.world_map)


class Level1(JsonLevelGenerator):
def get_map(self):
self._register_json(LEVELS["level1"])
self._register_decoders()
self._json_decode_map()

return self.world_map
1 change: 0 additions & 1 deletion aimmo-game/simulation/game_state.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from simulation.avatar import fog_of_war


class GameState(object):
"""
Encapsulates the entire game state, including avatars, their code, and the world.
Expand Down
Empty file.
31 changes: 31 additions & 0 deletions aimmo-game/simulation/levels/levels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from parsers import CellParser
from pprint import pprint

class RawLevelGenerator():
def __init__(self):
pass

def by_parser(self, parser):
self.parser = parser
return self

def by_map(self, map):
self.parser.parse_map(map)
return self

def by_models(self, models):
self.parser.register_models(models)
return self

def generate_json(self):
return self.parser.map_apply_transforms()

LEVELS = {
"level1" : RawLevelGenerator().by_parser(CellParser()).by_map("level1.txt").by_models(["objects.json"]).generate_json()
}

def main():
pprint(LEVELS["level1"])

if __name__ == '__main__':
main()
6 changes: 6 additions & 0 deletions aimmo-game/simulation/levels/maps/level1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
1 1 1 1 1 1 1 1
1 0 5 2 2 2 0 1
1 2 2 2 2 1 1 1
1 1 1 4 0 1 3 1
1 2 2 2 2 0 0 1
1 1 1 1 1 1 1 1
36 changes: 36 additions & 0 deletions aimmo-game/simulation/levels/models/objects.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
[
{
"code": "2",
"id" : "class:CellTransform.compute_id",
"x" : "class:CellTransform.get_x",
"y" : "class:CellTransform.get_y"
},
{
"code": "1",
"id" : "class:CellTransform.compute_id",
"x" : "class:CellTransform.get_x",
"y" : "class:CellTransform.get_y"
},
{
"code": "3",
"id" : "class:CellTransform.compute_id",
"x" : "class:CellTransform.get_x",
"y" : "class:CellTransform.get_y",
"type" : "health",
"health_restored": "5"
},
{
"code": "4",
"id" : "class:CellTransform.compute_id",
"x" : "class:CellTransform.get_x",
"y" : "class:CellTransform.get_y",
"type" : "invulnerability"
},
{
"code": "5",
"id" : "class:CellTransform.compute_id",
"x" : "class:CellTransform.get_x",
"y" : "class:CellTransform.get_y",
"type" : "damage"
}
]
98 changes: 98 additions & 0 deletions aimmo-game/simulation/levels/parsers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import json
import abc
import os

from transforms import CellTransform

def call_method(o, name):
x = getattr(o, name)()
return x

class Parser():
__metaclass__ = abc.ABCMeta

def __init__(self):
self._SCRIPT_LOCATION = os.path.abspath(os.path.dirname(__file__))
self._MAPS_FOLDER = os.path.join(self._SCRIPT_LOCATION, "maps")
self._MODELS_FOLDER = os.path.join(self._SCRIPT_LOCATION, "models")
self.models = []
self.transforms = {}
self.map = []

def parse_model(self, model_name):
with open(os.path.join(self._MODELS_FOLDER, model_name)) as data_file:
model = json.load(data_file)
return model

def parse_map(self, map_name):
with open(os.path.join(self._MAPS_FOLDER, map_name)) as content_file:
content = content_file.read()
lines = content.split('\n')
cells = [list(filter(lambda x: x != '', line.split(" ")))
for line in lines]
cells = list(filter(lambda x: x != [], cells))
self.map = cells

def register_model(self, model):
self.models.append(self.parse_model(model))

def register_models(self, models):
for model in models:
self.register_model(model)

# overwrites transform if present
def register_transform(self, transform):
self.transforms[transform.__class__.__name__] = transform

@abc.abstractmethod
def register_transforms():
pass

def feed_string(self, input_str):
if isinstance(input_str, unicode):
input_str = str(input_str)

# e.g. class:CellTransform.compute_id
if input_str.startswith("class:"):
model_class = input_str.split(":")[1].split(".")[0]
model_method = input_str.split(":")[1].split(".")[1]

out = call_method(self.transforms[model_class], model_method)
return str(out)
else:
return input_str

def feed_json(self, code):
def populate(json, model):
if isinstance(model, list):
for item in model:
json.append(populate({}, item))
elif isinstance(model, basestring):
json = self.feed_string(model)
else:
for item in model:
json[item] = populate({}, model[item])
return json

for model_list in self.models:
for model in model_list:
if model["code"] == code:
return populate({}, model)
return None

def map_apply_transforms(self):
objects = []
for x in xrange(len(self.map)):
for y in xrange(len(self.map[x])):
code = self.map[x][y]

self.register_transforms(x, y)
object_json = self.feed_json(code)
if object_json != None:
objects.append(object_json)

return objects

class CellParser(Parser):
def register_transforms(self, x, y):
self.register_transform(CellTransform(x, y))
15 changes: 15 additions & 0 deletions aimmo-game/simulation/levels/transforms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import hashlib

class CellTransform():
def __init__(self, x, y):
self.x = x
self.y = y

def compute_id(self):
return hash(str(self.x) + ":" + str(self.y))

def get_x(self):
return self.x

def get_y(self):
return self.y
47 changes: 5 additions & 42 deletions aimmo-game/simulation/map_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,27 +13,13 @@
from simulation.world_map import WorldMapStaticSpawnDecorator
from simulation.world_map import DEFAULT_LEVEL_SETTINGS

LOGGER = logging.getLogger(__name__)


class _BaseGenerator(object):
__metaclass__ = abc.ABCMeta

def __init__(self, settings):
self.settings = settings

def get_game_state(self, avatar_manager):
return GameState(self.get_map(), avatar_manager, self.check_complete)

def check_complete(self, game_state):
return False

@abc.abstractmethod
def get_map(self):
pass
from simulation.custom_map import BaseGenerator
from simulation.custom_map import BaseLevelGenerator
from simulation.custom_map import Level1

LOGGER = logging.getLogger(__name__)

class Main(_BaseGenerator):
class Main(BaseGenerator):
def get_map(self):
height = self.settings['START_HEIGHT']
width = self.settings['START_WIDTH']
Expand Down Expand Up @@ -167,26 +153,3 @@ def pop(self):

def __len__(self):
return len(self.heap)


class _BaseLevelGenerator(_BaseGenerator):
__metaclass__ = abc.ABCMeta

def __init__(self, *args, **kwargs):
super(_BaseLevelGenerator, self).__init__(*args, **kwargs)
self.settings.update(DEFAULT_LEVEL_SETTINGS)


class Level1(_BaseLevelGenerator):
def get_map(self):
world_map = WorldMap.generate_empty_map(1, 5, self.settings)
world_map = WorldMapStaticSpawnDecorator(world_map, Location(-2, 0))
world_map.get_cell(Location(2, 0)).generates_score = True
return world_map

def check_complete(self, game_state):
try:
main_avatar = game_state.get_main_avatar()
except KeyError:
return False
return main_avatar.score > 0
2 changes: 1 addition & 1 deletion aimmo-game/simulation/world_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def _min_max_from_dimensions(cls, height, width):

@classmethod
def generate_empty_map(cls, height, width, settings):
new_settings =DEFAULT_LEVEL_SETTINGS.copy()
new_settings = DEFAULT_LEVEL_SETTINGS.copy()
new_settings.update(settings)

(min_x, max_x, min_y, max_y) = WorldMap._min_max_from_dimensions(height, width)
Expand Down
1 change: 0 additions & 1 deletion aimmo-game/tests/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from simulation.location import Location
from simulation.turn_manager import state_provider
from simulation.world_map import WorldMap
from simulation.world_state import WorldState

import service

Expand Down
Empty file.
Loading

0 comments on commit 7013c0b

Please sign in to comment.