Beispiel #1
0
def unit_form(request, id=None):
    if id:
        obj = get_object_or_404(Unit, id=id, company=request.company)
        scenario = 'Update'
    else:
        obj = Unit(company=request.company)
        scenario = 'Create'
    if request.POST:
        form = UnitForm(data=request.POST, instance=obj)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.company = request.company
            obj.save()
            if request.is_ajax():
                return render(request, 'callback.html', {'obj': {'name': obj.name, 'id': obj.id}})
            return redirect(reverse_lazy('list_units'))
    else:
        form = UnitForm(instance=obj)
    if request.is_ajax():
        base_template = 'modal.html'
    else:
        base_template = 'dashboard.html'
    return render(request, 'unit_form.html', {
        'scenario': scenario,
        'form': form,
        'base_template': base_template,
    })
Beispiel #2
0
 def post(self):
     req = self.request
     
     msg = ChatMessage()
     msg.text = req("text")
     msg.unitfrom = Unit.get_by_id(req("fromid"))
     msg.unitto = Unit.get_by_id(req("toid"))
     msg.put()
Beispiel #3
0
def set_owner(player, territory_name, game):
    territory = Territory.objects(
            name=territory_name,
            game_id=str(game.id)).first()
    unit=Unit(owner=player, unit_type="Infantry", number=0)
    unit.save()
    print unit
    territory.units.append(unit)
    return territory
Beispiel #4
0
  def get(self):
    #move the unit towards the x and y goto positions    
    #xy = re.match('tile(\d+)', self.request.get("tile_id")).groups()
    x_goto = int(self.request.get("x-goto"))
    y_goto = int(self.request.get("y-goto"))
    unitID = int(re.match('unit(\d+)', self.request.get("unitid")).group(1))

    destinationTile = Tile.gql("where x = :1 ans y = :2",x_goto, y_goto);

    if destinationTile.type.canTravel:
       # just select the unit with that id
       unit = Unit.get_by_id(unitID)
    
       if unit.x > x_goto:
          unit.x = unit.x - 1
       elif unit.x < x_goto:
          unit.x = unit.x + 1
       if unit.y > y_goto:    
          unit.y = unit.y - 1
       elif unit.y < y_goto:
          unit.y = unit.y + 1
        
       unit.put()

       self.response.out.write("ok")
    else:   
       self.response.out.write("obstructed")
Beispiel #5
0
    def get(self):
        units = Unit.gql("where user = :1", users.get_current_user() )

	if units.count() == 0:
	    unit = Unit()
	    unit.x = 20
	    unit.y = 20
	    unit.user = users.get_current_user()
	    unit.put()

        units = Unit.gql("where user = :1", users.get_current_user() )
	    
        json = {"units":[]}
        
        for unit in units:
            json["units"].append( {"x":unit.x, "y":unit.y, "id":unit.key().id(), "owner":unit.user.nickname() } )
            
        self.response.out.write(demjson.encode(json))
 def InsertFromGrid(self):
     try:
         cell_value = []
         row_index = self.m_gridSource.GetSelectedRows()[0]
         for i in range(0,3):
             cell_value.append(self.m_gridSource.GetCellValue(row_index,i))
         
         xldb =  Unit()
         Id =  str(cell_value[0])
         Ma =  str(cell_value[1])
         Ten =  str(cell_value[2])
         if Ma == "":
             return 0
        
         self.m_gridSource.AppendRows(1)
         kq = xldb.Insert(Ma,Ten)
         if kq>0:
             return 1
         else: 
             return 0
     except :
         return 0
 def m_btnThemOnButtonClick( self, event):
     kq = 0
     if self.CheckValid()==False:
         kq = self.InsertFromGrid()
         if(kq == 0):
             wx.MessageBox("Please fill all required fields","Messages",wx.OK|wx.ICON_WARNING)
             self.m_textunit_code.SetFocus()
             return
     else :
         Ma = self.m_textunit_code.GetValue()
         Ten = self.m_textunit_name.GetValue()
         # if(self.GetCountRow()>14):
         self.m_gridSource.AppendRows(1)
         xldb =  Unit()
         kq = xldb.Insert(Ma,Ten)
     if kq>0:
         self.OnLoadData()
         wx.MessageBox("Record added successfully","Messages",wx.OK|wx.ICON_INFORMATION)
         self.m_textunit_code.SetValue("")
         self.m_textunit_name.SetValue("")
     else: 
         wx.MessageBox("Error when trying add record","Messages",wx.OK|wx.ICON_WARNING)
Beispiel #8
0
    def _populate_units(self, project_obj):
        """ Fill Units collections """

        unit_project = UnitProject()
        unit_project.title.value = project_obj.project_title.value
        unit_project.id.value = project_obj.project_id.value

        if project_obj.operating_unit_id.value in self.units.pks:
            self.units.collection[project_obj.operating_unit_id.value].projects.value.append(unit_project.to_dict())
        else:
            unit = Unit()
            unit.op_unit.value = project_obj.operating_unit_id.value
            unit.projects.value.append(unit_project.to_dict())
            self.units.add(project_obj.operating_unit_id.value, unit)
Beispiel #9
0
  def get(self):

    map = memcache.get("map")
    HeightMapData = FetchImage("http://humanitymmo.appspot.com/static/earthmini.png")
    w,h = HeightMapData[:2]

    # should get the tiles, within proximity of units.
    # foreach unit, get tiles within range of the unit
    # in this instance limit it to 1 unit only
    unit = Unit.get_by_id( int(self.request.get("id")) )

    json = {"tiles":[],"enemyunits":[]}        

    fov =  2 # fov is how many tiles a unit can see around it
    xleft = max(unit.x - fov, 0)
    xright = min(unit.x + fov + 1, w)
    ytop = max(unit.y - fov, 0)
    ybottom = min(unit.y + fov + 1, h)

    # get heightmap based tiles
    for x in range(xleft, xright):
        for y in range(ytop, ybottom):
          # is the tile in the datastore
          curTile = Tile.gql("where x = :1 and y = :2", x,y)
          if curTile.count() > 0:
              if curTile.type.canTravel:
                 curAlt = 80
              else:
                 curAlt = 81

              json["tiles"].append( {"x":curTile.x,"y":curTile.y,"alt":curAlt} )
          else
              alt = GetHeightAt(x,y,HeightMapData)
              json["tiles"].append( {"x":x, "y":y, "alt":alt } )
              # write to datastore
              t = Tile()
              t.x = x
              t.y = y
              t.height = alt
              
              if alt < 81:
                # get tile type where name = water, then reference it

              else:
                # get tile type for land

              t.put()
          
    self.response.out.write(demjson.encode(json))
def get_units(total_intervals):
    f = open(units_dir)

    units_count = int(f.readline())
    units = []

    for index in range(units_count):
        unit_number = f.readline()
        unit_capacity = f.readline()
        unit_maintenance_count = f.readline()
        unit = Unit(unit_number, unit_capacity, unit_maintenance_count,
                    len(total_intervals))
        units.append(unit)

    return units
Beispiel #11
0
def get_units():
    units_object = []

    for url in urls.keys():
        file_path = f"cache/{url}"
        if not os.path.exists(file_path):
            html = requests.get(base_url + url).text
            print(f"requesting {base_url + url}")
            with open(file_path, "w") as f:
                f.write(html)
        with open(file_path, "r") as f:
            data = etree.HTML(f.read())

        for unit in data.xpath("//*[@id='content_container_']/ul/li"):
            code = unit.xpath(".//a/text()")[0].strip()
            name = unit.xpath("text()")
            if len(name) == 0:
                continue
            units_object.append(Unit(code, name[0].strip(), urls.get(url)))

    return units_object
Beispiel #12
0
def parse_csv(csv_record):
    """
    Parsing may be a little too strong of a description
    """
    # I'm not sure if this is a mistake in the csv file, the fact that it
    # was embedded in the PDF, or if it's just a gotcha
    price = float(csv_record[" Price "].strip().split("$")[1])
    cost = float(csv_record[" Cost"].strip().split("$")[1])
    shelf_life = int(csv_record["ShelfLife"].split("d")[0])
    last_sold = arrow.get(csv_record["lastSold"], "M/D/YYYY")

    return {
        "product_id": csv_record["ID"],
        "description": csv_record["Description"],
        "last_sold": last_sold,
        "shelf_life": shelf_life,
        "department": Department[csv_record["Department"]],
        "price": price,
        "unit": Unit(csv_record["Unit"]),
        "x_for": csv_record["xFor"],
        "cost": cost,
    }
Beispiel #13
0
def change_unit(id, do):
    id = int(id)

    if do == "add":
        s = Unit()
    else:
        s = mydb.session.query(Unit).filter(Unit.id_unit == id).one_or_none()

    form = UnitForm(request.form, obj=s)

    if do == "delete":
        mydb.session.delete(s)
        mydb.session.flush()
        return redirect(url_for('unit'))

    if form.button_save.data:
        form.populate_obj(s)
        mydb.session.add(s)
        if s.id_unit != id:
            return redirect(url_for('unit', id=s.id_unit))

    return render_template('change_unit.html', form=form)
Beispiel #14
0
def details(request, bldg_tag, city_tag):


    city = City.objects.filter(tag=city_tag)
    #old way... this doesn't work very reliably:
    #address = re.sub('_', ' ', bldg_tag)
    #buildings = Building.objects.filter(city=city).filter(address=address)
    buildings = Building.objects.filter(city=city).filter(tag=bldg_tag)
    if buildings.count():
        building = buildings[0]

        if not building.units.count():
            #must have a building with no associated units...
            #may only have one unit
            #or others may have been incorrectly created as separate buildings
            #either way we can start by making a new unit here
            #(and then merging in any others manually)

            unit = Unit()
            unit.building = building
            unit.number = ''
            # don't want to set this unless it's different:
            #unit.address = building.address 

            ## bedrooms
            ## bathrooms
            ## sqft
            ## max_occupants
            unit.save()
    else:
        building = None

    #print building.units.all()[0].tag
    #unit_url = reverse('unit_details', kwargs={'city_tag':building.city.tag, 'bldg_tag':building.tag, 'unit_tag':building.units.all()[0].tag})
    #print unit_url

        
    context = { 'building': building,
                'units': building.units.all(),
                'user': request.user,
                'redirect_field': REDIRECT_FIELD_NAME,
                }
    return render(request, 'details.html', context)
Beispiel #15
0
def edit():
    if request.method == 'GET':
        unit_models = Unit.query.all()
        class_models = Class.query.all()
        carousel_item_models = CarouselItem.query.all()
        main_link_models = MainLink.query.all()

        #Construct all the JSON maps
        content = [unit_model.toJSON() for unit_model in unit_models]
        dates = [
            class_model.pst_datetime.strftime('%m/%d/%y')
            for class_model in class_models
        ]
        carousel_items = [
            carousel_item_model.toJSON()
            for carousel_item_model in carousel_item_models
        ]
        main_links = [
            main_link_model.toJSON() for main_link_model in main_link_models
        ]

        return render_template('edit.html',
                               content=formatJSON(content),
                               carousel_items=formatJSON(carousel_items),
                               main_links=formatJSON(main_links),
                               dates=formatJSON(dates),
                               title="Edit JSON")
    else:  #POST method
        # try: #Todo - better error catching
        data = json.loads(request.form['all'])

        # for key, value in data.iteritems():
        #   print key, value
        content, dates, carousel_items, main_links = data['content'], data[
            'dates'], data['carousel_items'], data['main_links']
        print content, dates, carousel_items, main_links
        #Seconds since epoch at which a new PST day w/ physics begins
        epoch_day_offsets = [
            timegm(time.strptime(t, "%m/%d/%y")) for t in dates
        ]

        #Zip time info into the topics dictionary
        date_iter = iter(epoch_day_offsets)

        new_units = []
        #Populate the topics into their respective units, with the dates loaded in too
        for unit in content:
            unit_model = Unit()
            unit_model.title = unit['title']
            unit_model.description = unit['description']
            unit_model.visible = unit['visible']
            for cl in unit['classes']:
                class_model = Class()  #Make an empty model

                #Fill it with topical values
                for item in cl['items']:
                    class_model.addItem(item)
                class_model.homework = cl['homework']
                if 'additional' in cl:
                    class_model.additional = cl['additional']

                #Fill it with time values (could mess up here)
                t = date_iter.next(
                )  #Seconds since epoch of a new UTC day - could throw an error
                pst_dt = dt.utcfromtimestamp(
                    t)  #Datetime representing the local date and time
                class_model.epoch_time = t + PST_OFFSET  #Seconds since epoch of a new PST day
                class_model.pst_datetime = pst_dt
                class_model.day_of_week = int(pst_dt.strftime(
                    "%w"))  #1 = Monday, 2 = Tuesday, ..., 5 = Friday
                class_model.week_of_year = int(pst_dt.strftime("%W"))

                unit_model.addClass(class_model)
            new_units.append(unit_model)

        new_carousel_items = []
        #Add carousel items
        for item in carousel_items:
            new_item = CarouselItem()
            if 'title' in item:
                new_item.title = item['title']
            if 'description' in item:
                new_item.description = item['description']
            if 'src' in item:
                new_item.src = item['src']
            if 'alt' in item:
                new_item.alt = item['alt']
            new_carousel_items.append(new_item)

        new_main_links = []
        for link in main_links:
            new_link = MainLink()
            if 'link' in link:
                new_link.link = link['link']
            if 'media-type' in link:
                new_link.media_type = link['media-type']
            new_main_links.append(new_link)

        #Now that we have all the models, clear the database and push all the new values on
        Unit.query.delete()
        Class.query.delete()
        CarouselItem.query.delete()
        MainLink.query.delete()

        for unit_model in new_units:
            db.session.add(unit_model)
        for carousel_item_model in new_carousel_items:
            db.session.add(carousel_item_model)
        for main_link_model in new_main_links:
            db.session.add(main_link_model)
        db.session.commit()
        flash('Successfully updated database to reflect changes')
        # # except Exception as e:
        #   print "Error: " + repr(e)
        #   flash('Uncaught Exception: {0}'.format(e), category='error')
        return redirect(url_for('admin'))
Beispiel #16
0
 def post(self):
   unit = Unit()
   unit.x = int(self.request.get("x"))
   unit.y = int(self.request.get("y"))
   unit.user = users.get_current_user()
   unit.put()
Beispiel #17
0
        u2 = Unit(full_name="meter")
        u2.save(no_wiki=True)
        u3 = Unit(full_name="second")
        u3.save(no_wiki=True)
        u1.make_composition_links("meter,second")
        v1.add_units_links("meter,second")
        try:
            uget1 = u1.composition_links.get(full_name="meter")
            uget2 = u1.composition_links.get(full_name="second")
            uget3 = v1.units_links.get(full_name="meter")
            uget4 = v1.units_links.get(full_name="second")
        except (ObjectDoesNotExist, MultipleObjectsReturned), e:
            raise AssertionError
        v2 = Variable(full_name="Jon's Constant")
        v2.save(no_wiki=True)
        u4 = Unit(full_name="kilogram")
        u4.save(no_wiki=True)
        u4.make_composition_links("base")
        self.assertFalse(bool(u4.composition_links.all()))

    def test_definitions(self):
        e1 = Equation(full_name="Jon's Law")
        e1.save(no_wiki=True)
        v1 = Variable(full_name="Jon's Constant")
        v1.save(no_wiki=True)
        e1.add_defined_var(v1.full_name)
        self.assertEqual(e1.defined_var.full_name, v1.full_name)

    def test_equation_add_variables(self):
        e1 = Equation(full_name="Jon's Law")
        e1.save(no_wiki=True)
Beispiel #18
0
 def test_trade_units(self):
     player_one, player_two, game= init_test_game()
     trade= create_unit_trade(game, Unit.objects(owner=player_one), Unit.objects(owner=player_two), player_one, player_two)
     pass
Beispiel #19
0
 def test_infobase_add_from_sequence(self):
     v1 = Variable(full_name="acceleration")
     v1.save(no_wiki=True)
     u1 = Unit(full_name="ms")
     u1.save(no_wiki=True)
     u2 = Unit(full_name="meter")
     u2.save(no_wiki=True)
     u3 = Unit(full_name="second")
     u3.save(no_wiki=True)
     u1.make_composition_links("meter,second")
     v1.add_units_links("meter,second")
     try:
         uget1 = u1.composition_links.get(full_name="meter")
         uget2 = u1.composition_links.get(full_name="second")
         uget3 = v1.units_links.get(full_name="meter")
         uget4 = v1.units_links.get(full_name="second")
     except (ObjectDoesNotExist, MultipleObjectsReturned), e:
         raise AssertionError
Beispiel #20
0
 def test01(self):
     
     u1 = Unit(title="First Chapter")
     u1.save()
     self.assertEqual(u1.seq,1)
     u = Unit(title="First Section",parent=u1)
     u.save()
     self.assertEqual(u.seq,1)
     u = Unit(title="Second Section",parent=u1)
     u.save()
     self.assertEqual(u.seq,2)
     
     self.assertEqual(u.pk,3)
     try:
         #print "set parent to self"
         u.parent=u
         u.save()
         print "save() : done"
     except ModelValidationError,e:
         #s="\n".join([e.as_text() for m in e.messages])
         self.assertEqual(str(e),"Parent cannot be self")
Beispiel #21
0
    def process_data_tag(self, data):

        id = data.find('id').text
        name = data.find('name').text
        description = data.find('description').text
        updated_at = data.find('updated_at').text
        created_at = data.find('created_at').text

        category = []
        units = []
        images = []
        logo = []

        # processing all child tags of data
        for child in data:

            # getting <category> from data
            if child.tag == 'category':
                id = child.find('id').text
                name = child.find('name').text
                category.append(Category(id, name))

            # getting <units> from data
            if child.tag == 'units':
                for data_tag in child:
                    id = data_tag.find('id').text
                    name = data_tag.find('name').text
                    key = data_tag.find('key').text
                    value = data_tag.find('value').text
                    units.append(Unit(id, name, key, value))

            # getting <images> from data
            if child.tag == 'images':
                for data_tag in child:

                    id = data_tag.find('id').text
                    name = data_tag.find('name').text
                    thumb = data_tag.find('thumb').text
                    aspectRatio = data_tag.find('aspectRatio').text
                    listing_medium = data_tag.find('listing_medium').text
                    listing_small = data_tag.find('listing_small').text
                    listing_large = data_tag.find('listing_large').text
                    square_medium = data_tag.find('square_medium').text
                    square_small = data_tag.find('square_small').text
                    square_large = data_tag.find('square_large').text

                    images.append(
                        Image(id, name, thumb, aspectRatio, listing_medium,
                              listing_small, listing_large, square_medium,
                              square_small, square_large))

            # getting <logo> from data
            if child.tag == 'logo':
                for data_tag in child:

                    id = data_tag.find('id').text
                    name = data_tag.find('name').text
                    thumb = data_tag.find('thumb').text
                    aspectRatio = data_tag.find('aspectRatio').text
                    listing_medium = data_tag.find('listing_medium').text
                    listing_small = data_tag.find('listing_small').text
                    listing_large = data_tag.find('listing_large').text
                    square_medium = data_tag.find('square_medium').text
                    square_small = data_tag.find('square_small').text
                    square_large = data_tag.find('square_large').text

                    logo.append(
                        Logo(id, name, thumb, aspectRatio, listing_medium,
                             listing_small, listing_large, square_medium,
                             square_small, square_large))

        return Data(id, name, description, category, units, images, updated_at,
                    created_at, logo)
Beispiel #22
0
    def test01(self):

        u1 = Unit(title="First Chapter")
        u1.save()
        self.assertEqual(u1.seq, 1)
        u = Unit(title="First Section", parent=u1)
        u.save()
        self.assertEqual(u.seq, 1)
        u = Unit(title="Second Section", parent=u1)
        u.save()
        self.assertEqual(u.seq, 2)

        self.assertEqual(u.pk, 3)
        try:
            #print "set parent to self"
            u.parent = u
            u.save()
            print "save() : done"
        except ModelValidationError, e:
            #s="\n".join([e.as_text() for m in e.messages])
            self.assertEqual(str(e), "Parent cannot be self")
# add schools to DB from file
with open(data_dir + 'schools.csv', 'r') as fp:
    for line in fp:
        line = line.strip().split(',')[:2]
        if line[0] != '#':
            school = School(id=line[0], name=line[1])
            session.add(school)
    session.flush()

# add units to DB from file
with open(data_dir + 'units.csv', 'r') as fp:
    for line in fp:
        line = line.strip().split(',')[:1][0]
        if line[0] != '#':
            unit = Unit(name=line)
            session.add(unit)
    session.flush()

# add teachers to DB from file
with open(data_dir + 'teachers.csv', 'r') as fp:
    for line in fp:
        line = line.strip().split(',')[:3]
        if line[0] != '#':
            school = session.query(School).filter_by(name=line[2]).first()
            teacher = Teacher(id=line[0], name=line[1], school_id=school.id)
            session.add(teacher)
    session.flush()

# add students to DB from file
with open(data_dir + 'students.csv', 'r') as fp:
    def set_new_unit_data_into_db(data):
        new_unit_id = data["id"]
        new_unit_name = data['name']
        new_nuit_description = data['description'] if "description" in data else None
        new_unit_expansion = data['expansion']
        new_unit_age = data['age']
        new_unit_created_in = data['created_in']
        new_unit_cost = data['cost']
        #  ubit 43 reload_time constrain(not null) so I but any number to pass
        new_unit_build_time = data['build_time'] if "build_time" in data else 1
        # ubit 53  reload_time constrain not null, so I but any number to pass
        new_unit_reload_time = data['reload_time'] if "reload_time" in data else 1.2
        new_unit_attack_delay = data['attack_delay'] if "attack_delay" in data else None
        new_unit_movement_rate = data['movement_rate']
        new_unit_line_of_sight = data['line_of_sight']
        new_unit_hit_points = data['hit_points']
        new_unit_range = data['range'] if "range" in data else None
        #  ubit 53 attack constrain not null, so I but any number here to pass test
        new_unit_armor = data['armor']
        new_unit_attack = data['attack'] if "attack" in data else 1
        new_unit_armor = data['armor']
        new_unit_search_radius = data['search_radius'] if "search_radius" in data else None
        new_unit_accuracy = data['accuracy'] if "accuracy" in data else None
        new_unit_blast_radius = data['blast_radius'] if "blast_radius" in data else None
        new_unit_attack_bonuses = data['attack_bonus'].copy() if "attack_bonus" in data else None
        new_unit_armor_bonuses = data['armor_bonus'].copy() if "armor_bonus" in data else None

        #  see if the unit has attack/armor bounses
        attack_bonus = has_attack_bonus(new_unit_attack_bonuses)
        armor_bonus = has_armor_bonus(new_unit_armor_bonuses)

        try:
            #  save unit data into unit table
            new_unit = Unit(id=new_unit_id, name=new_unit_name, description=new_nuit_description, expansion=new_unit_expansion, age=new_unit_age, created_in=new_unit_created_in, cost=new_unit_cost, build_time=new_unit_build_time, reload_time=new_unit_reload_time, attack_delay=new_unit_attack_delay, movement_rate=new_unit_movement_rate, line_of_sight=new_unit_line_of_sight, hit_points=new_unit_hit_points, unit_range=new_unit_range, attack=new_unit_attack, armor=new_unit_armor, search_radius=new_unit_search_radius, accuracy=new_unit_accuracy, blast_radius=new_unit_blast_radius)
            new_unit.insert()
            #  in case unit has poth attack and armor bouns
            if ((attack_bonus is True) and (armor_bonus is True)):
                new_attack_bouns = AttackBouns(attackBouns=new_unit_attack_bonuses)
                new_armor_bouns = ArmorBouns(armorBouns=new_unit_armor_bonuses)
                new_unit.attack_bonuses = [new_attack_bouns]
                new_unit.armor_bonuses = [new_armor_bouns]
                new_attack_bouns.insert()
                new_armor_bouns.insert()

            #  in case unit has only armor bouns
            elif((attack_bonus is False) and (armor_bonus is True)):
                new_armor_bouns = ArmorBouns(armorBouns=new_unit_armor_bonuses)
                new_unit.armor_bonuses = [new_armor_bouns]
                new_armor_bouns.insert()

            #  in case unit has only attack bouns
            elif((attack_bonus is True) and (armor_bonus is False)):
                new_attack_bouns = AttackBouns(attackBouns=new_unit_attack_bonuses)
                new_unit.attack_bonuses = [new_attack_bouns]
                new_attack_bouns.insert()

        except (Exception, psycopg2.DatabaseError) as error:
            print('error during saving into database')
            print(error)
            return error
        finally:
            db.session.close()
Beispiel #25
0
def edit():
  if request.method == 'GET':
    unit_models = Unit.query.all();
    class_models=Class.query.all();
    carousel_item_models=CarouselItem.query.all();
    main_link_models=MainLink.query.all();
    
    #Construct all the JSON maps
    content=[unit_model.toJSON() for unit_model in unit_models]
    dates=[class_model.pst_datetime.strftime('%m/%d/%y') for class_model in class_models]
    carousel_items = [carousel_item_model.toJSON() for carousel_item_model in carousel_item_models]
    main_links = [main_link_model.toJSON() for main_link_model in main_link_models]

    return render_template('edit.html',
      content=formatJSON(content),
      carousel_items=formatJSON(carousel_items),
      main_links=formatJSON(main_links),
      dates=formatJSON(dates),
      title="Edit JSON")
  else: #POST method
    # try: #Todo - better error catching
      data = json.loads(request.form['all'])

      # for key, value in data.iteritems():
      #   print key, value
      content, dates, carousel_items, main_links = data['content'], data['dates'], data['carousel_items'], data['main_links']
      print content, dates, carousel_items, main_links
      #Seconds since epoch at which a new PST day w/ physics begins
      epoch_day_offsets = [timegm(time.strptime(t, "%m/%d/%y")) for t in dates]
      
      #Zip time info into the topics dictionary
      date_iter = iter(epoch_day_offsets)

      new_units = []
      #Populate the topics into their respective units, with the dates loaded in too
      for unit in content:
        unit_model = Unit()
        unit_model.title=unit['title']
        unit_model.description=unit['description']
        unit_model.visible = unit['visible']
        for cl in unit['classes']:
          class_model = Class() #Make an empty model

          #Fill it with topical values
          for item in cl['items']:
            class_model.addItem(item)
          class_model.homework=cl['homework']
          if 'additional' in cl:
            class_model.additional = cl['additional']

          #Fill it with time values (could mess up here)
          t = date_iter.next() #Seconds since epoch of a new UTC day - could throw an error
          pst_dt = dt.utcfromtimestamp(t) #Datetime representing the local date and time
          class_model.epoch_time = t + PST_OFFSET #Seconds since epoch of a new PST day
          class_model.pst_datetime = pst_dt
          class_model.day_of_week = int(pst_dt.strftime("%w")) #1 = Monday, 2 = Tuesday, ..., 5 = Friday
          class_model.week_of_year = int(pst_dt.strftime("%W"))

          unit_model.addClass(class_model)
        new_units.append(unit_model)

      new_carousel_items = []
      #Add carousel items
      for item in carousel_items:
        new_item = CarouselItem()
        if 'title' in item:
          new_item.title=item['title']
        if 'description' in item:
          new_item.description=item['description']
        if 'src' in item:
          new_item.src=item['src']
        if 'alt' in item:
          new_item.alt=item['alt']
        new_carousel_items.append(new_item)


      new_main_links = []
      for link in main_links:
        new_link = MainLink()
        if 'link' in link:
          new_link.link = link['link']
        if 'media-type' in link:
          new_link.media_type = link['media-type']
        new_main_links.append(new_link);

      #Now that we have all the models, clear the database and push all the new values on
      Unit.query.delete()
      Class.query.delete()
      CarouselItem.query.delete()
      MainLink.query.delete()

      for unit_model in new_units:
        db.session.add(unit_model)
      for carousel_item_model in new_carousel_items:
        db.session.add(carousel_item_model)
      for main_link_model in new_main_links:
        db.session.add(main_link_model)
      db.session.commit()
      flash('Successfully updated database to reflect changes')
    # # except Exception as e:
    #   print "Error: " + repr(e)
    #   flash('Uncaught Exception: {0}'.format(e), category='error')
      return redirect(url_for('admin'))
Beispiel #26
0
def handleGetMapRequest(inputs):
    """
    Gets the map state of the game from the given player's interest model.
    @returns A built Response with the following sets of data:
             map_tiles: a list of serialized MapTiles.
             units: a list of serialized Units.
             resource_templates: a list of ResourceTemplates.
             equipment: a list of Equipment, only including equiped items.
    NOTE: Eventually this will include a more detailed interest model, to allow
    for fog of war, but for now we return the entire world, and only use the
    interest model (player_id) to determine if a tile is a player home or enemy
    home.
  """

    # Make sure the player is already in the game.
    player_key = ndb.Key(urlsafe=inputs['player_id'])
    player = player_key.get()
    if not player.home_tile:
        # If the player does not have a home tile, then they aren't in the game, and
        # they need to join the game.
        logging.error('Player: ' + player_key.urlsafe() +
                      " is not in the game!")
        error_message = 'Player is not in the game.'
        return ResponseBuilder().setErrorMessage(error_message).build()

    # Get the tiles
    map_query = MapTile.query()
    if map_query.count() > 0:
        map_tiles = map_query.fetch()
        ## The map_object will be built up and built into the response.
        ## Its keys will be a the urlsafe key of the serialized maptile value.
        map_object = {'mapTiles': []}
        for tile in map_tiles:
            # Serialize the map tile into what the client needs.
            serialized_tile = {}
            serialized_tile['key'] = tile.key.urlsafe()
            serialized_tile['coordinate_x'] = tile.coordinate_x
            serialized_tile['coordinate_y'] = tile.coordinate_y
            serialized_tile['resources'] = []
            for resource_key in tile.resources:
                tile_resource = resource_key.get()
                resource = {}
                resource['saturation'] = tile_resource.saturation
                resource[
                    'template_key'] = tile_resource.resource_template.urlsafe(
                    )
                serialized_tile['resources'].append(resource)
            serialized_tile['unit_keys'] = []
            unit_keys = tile.units.fetch(keys_only=True)
            for unit_key in unit_keys:
                serialized_tile['unit_keys'].append(unit_key.urlsafe())
            serialized_tile['structure_keys'] = []
            structure_keys = tile.structures.fetch(keys_only=True)
            for structure_key in structure_keys:
                serialized_tile['structure_keys'].append(
                    structure_key.urlsafe())
            # Tell the client if this map tile is a home tile.
            serialized_tile['is_player_home'] = False
            serialized_tile['is_enemy_home'] = False
            if tile.is_home_tile:
                if tile.key == player.home_tile:
                    serialized_tile['is_player_home'] = True
                else:
                    # For now, anyone that isn't the player is an enemy.
                    serialized_tile['is_enemy_home'] = True
            map_object['mapTiles'].append(serialized_tile)

    # TODO: There is a lot of repetition here, find a way to DRY this up.
    # Get the units.
    unit_query = Unit.query()
    if unit_query.count() > 0:
        map_object['units'] = []
        units = unit_query.fetch()
        for unit in units:
            # Serialize the unit into what the client needs.
            serialized_unit = {}
            serialized_unit['key'] = unit.key.urlsafe()
            serialized_unit['unit_type'] = unit.unit_type
            serialized_unit['owner_key'] = unit.owner_key.urlsafe()
            serialized_unit['health'] = unit.health

            if unit.weapon:
                serialized_unit['weapon_key'] = unit.weapon.urlsafe()
            if unit.armor:
                serialized_unit['armor_key'] = unit.armor.urlsafe()

            location_tile = unit.location_tile.get()
            serialized_unit['coordinate_x'] = location_tile.coordinate_x
            serialized_unit['coordinate_y'] = location_tile.coordinate_y

            serialized_unit['has_order'] = unit.has_order
            if unit.has_order:
                serialized_unit[
                    'current_order_key'] = unit.current_order.urlsafe()

            map_object['units'].append(serialized_unit)

    # Get the resource_templates.
    rt_query = ResourceTemplate.query()
    if rt_query.count() > 0:
        map_object['resource_templates'] = []
        resource_templates = rt_query.fetch()
        for template in resource_templates:
            # Serialize the resource_template into what the client needs.
            serialized_rt = {}
            serialized_rt['key'] = template.key.urlsafe()
            serialized_rt['name'] = template.name
            serialized_rt['type'] = template.resource_type
            if template.resource_type == RESOURCE_TYPES_INT_MAPPING[METAL_KEY]:
                serialized_rt[
                    'metal_properties'] = template.metal_properties.to_dict()
            if template.resource_type == RESOURCE_TYPES_INT_MAPPING[WOOD_KEY]:
                serialized_rt[
                    'wood_properties'] = template.wood_properties.to_dict()
            if template.resource_type == RESOURCE_TYPES_INT_MAPPING[
                    LEATHER_KEY]:
                serialized_rt[
                    'leather_properties'] = template.leather_properties.to_dict(
                    )
            map_object['resource_templates'].append(serialized_rt)

    # Get the equipment.
    eq_query = Equipment.query()
    if eq_query.count() > 0:
        map_object['equipment'] = []
        equipment_list = eq_query.fetch()
        for equipment in equipment_list:
            # Serialize the equipment into what the client needs.
            serialized_eq = {}
            serialized_eq['key'] = equipment.key.urlsafe()
            serialized_eq['owner_key'] = equipment.player.urlsafe()
            serialized_eq['type'] = equipment.type
            if equipment.type == EQUIPMENT_TYPE_INT_MAPPING[ARMOR_KEY]:
                serialized_eq['armor_data'] = equipment.armor_data.to_dict()
            if equipment.type == EQUIPMENT_TYPE_INT_MAPPING[WEAPON_KEY]:
                serialized_eq['weapon_data'] = equipment.weapon_data.to_dict()
            map_object['equipment'].append()

    # Get the structures
    struct_query = PlayerStructure.query()
    if struct_query.count() > 0:
        map_object['structures'] = []
        structures = struct_query.fetch()
        for structure in structures:
            # Serialize the structure into what the client needs.
            serialized_struct = {}
            serialized_struct['key'] = structure.key.urlsafe()
            serialized_struct['owner_key'] = structure.owner_key.urlsafe()
            serialized_struct['type'] = structure.structure_type
            serialized_struct['health'] = structure.health
            location_tile = structure.location.get()
            serialized_struct['coordinate_x'] = location_tile.coordinate_x
            serialized_struct['coordinate_y'] = location_tile.coordinate_y
            if (structure.structure_type ==
                    STRUCTURE_TYPE_INT_MAPPING[HARVESTING_CAMP_KEY]):
                # We need to further serialize the camp data.
                camp_data = {
                    'tile_resource_key':
                    structure.harvesting_camp_data.tile_resource_key
                }
            map_object['structures'].append(serialized_struct)

    # The map_object is built, set it on the response data as a json string.
    if len(map_object['mapTiles']) > 0:
        return ResponseBuilder().setData(json.dumps(map_object)).build()
    # No tiles exist, the game has not started.
    else:
        return ResponseBuilder().setErrorMessage("No game has started.")