Пример #1
0
 def create(self, validated_data):
     level = Level(
         name=validated_data['name'],
         alias=validated_data['name'].lower(),
         active=validated_data['active']
     )
     level.save()
     return level
Пример #2
0
 def run(self):
     from models import Provider, Level, Game, User, Element
     keyword = self.manager.args.keyword
     api = Provider.get_provider_api()
     images = api.get_images(keyword)
     user = User.objects.filter(super=True)[0]
     game = Game.objects.get(code_name=self.manager.args.game_name)
     level = Level(name=self.manager.args.level_name, game=game, creator=user).save()
     for img in images:
         level.Elements(element=Element(content=img, tags=keyword, name=keyword).save())
     level.save()
Пример #3
0
    def post(self, version):
        
        if (self.valid_version(version)):
            name = self.request.get('name', default_value=None)
            description = self.request.get('description', default_value=None)
            image = self.request.get('image', default_value=None)
            level = self.request.get('level', default_value=None)
            severity = Level.get_severity(level)

            if name and description and severity and image:
                slug = slugify.slugify(name)
                status = Status.get_by_slug(slug)

                # Update existing resource
                if status:
                    status.description = description
                    status.severity = severity
                    status.image = image
                    status.name = name
                    status.put()
                    self.json(status.rest(self.base_url(version)))
                # Create new service
                else:
                    status = Status(name=name, slug=slug, description=description, 
                        severity=severity, image=image)
                    status.put()
                    self.json(status.rest(self.base_url(version)))
            else:
                self.error(400, "Bad Data")
        else:
            self.error(404, "API Version %s not supported" % version)
Пример #4
0
 def post(self):
     
     format = self.request.get('format', 'json').lower()
     id = self.request.get('level_id', None)
     if id is None:
         res = {"response": {"error": "no level id with submission"}}
     else:
         level = Level.get_by_id(long(id))
         user_name = self.request.get('user')
         user = User.all().filter('name =', user_name).get()
         if user is None:
             user = User(name = user_name)
             user.put()
         score = self.request.get('score', 0)
         words_found = self.request.get('words_found').split(",")
              
         submission = Submission()
         submission.user = user
         submission.level = level
         submission.score = score
         submission.words_found = words_found
         submission.time = datetime.datetime.now()
         submission.put()
         
         res = {"response": {"status" : "OK"}}
     
     if format == "json":
         self.response.out.write(simplejson.dumps(res))
     elif format == "xml":
         self.response.out.write(dict2xml(res).to_string())
Пример #5
0
    def post(self, version, status_slug):

        
        if (self.valid_version(version)):
            status = Status.get_by_slug(status_slug)
            if status:
                name = self.request.get('name', default_value=None)
                image = self.request.get('image', default_value=None)
                description = self.request.get('description', default_value=None)
                level = self.request.get('level', default_value=None)
                severity = Level.get_severity(level)
                
                if description:
                    status.description = description
                    
                if image:
                    status.image = image
                    
                if name:
                    status.name = name
                    
                if severity:
                    status.severity = severity
                
                if description or name or image or severity:
                    status.put()
                    
                self.json(status.rest(self.base_url(version)))
            else:
                self.error(404, "Status %s not found" % status_slug)
        else:
            self.error(404, "API Version %s not supported" % version)
Пример #6
0
def get_current_level():
    level = memcache.get('level')
    if level is None:
        now = datetime.datetime.now()
        #level = Level.all().filter('time <=', now).filter('time >=', now - datetime.timedelta(seconds = GAME_LENGTH + HIGHSCORE_LENGTH)).get()
        #memcache.set('level', level)
        level = Level.all().get()
    return level
Пример #7
0
 def get(self, version):
     logging.debug("LevelsListHandler#get")
     
     if (self.valid_version(version)):
         
         self.json({"levels": Level.all()})
         
     else:
         
         self.error(404, "API Version %s not supported" % version)
Пример #8
0
    def cancel_game(self, request):
        """Delete the specified game."""
        game = get_by_urlsafe(request.urlsafe_game_key, Game)
        if game.game_over:
            return game.to_form('Game completed. Cannot delete.')

        # delete any levels
        level_keys = Level.query(Level.game == game.key).fetch(keys_only=True)
        ndb.delete_multi(level_keys)

        game.key.delete()
        return StringMessage(message='Game deleted.')
Пример #9
0
from utils import get_confirmation, show_and_select, print, now
from datetime import datetime as dt, timedelta, date
from models import Route, Level, Clock, LogRow
from calc import calculate_amount_of_sleep
from constants import ALTER_LOG


@Route.new(Level(0))
def welcoming(config, log):
    print(f"\nGood {Clock.part_of_day()}. Please select:")

    exclude = []
    if log.empty:
        exclude.append(2) 


    case = show_and_select([
        "calculate sleep duration",
        "tune the previous sleep session",
        "update configuration",
        "quit",
        ], exclude=exclude)

    return Level(case)


@Route.new(Level(1))
def calc(config, log):
    sleep_for = calculate_amount_of_sleep(log.content, config.rest_per_day)

    if sleep_for < timedelta():
Пример #10
0
  def get(self):
    """Handles get requests."""
    level_name = self.request.get('level')

    curr_level = Level.gql("WHERE level = '%s'" % level_name)
    if curr_level.count() != 1:
      message = 'Level %s not found' % level_name
      template_vals = {'can_play': False,
                       'message': message}
      path = os.path.join(os.path.dirname(__file__),
                          'templates',
                          'game_play.html')
      self.response.out.write(template.render(path, template_vals))
      return

    curr_level = curr_level.get()
    user = users.get_current_user()
    next_level = curr_level.next_level  # To disable
    if curr_level.owner is None:
      levels_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                            "AND item_name = '%s'") %
                                           (user.federated_identity(),
                                            'Levels'))
      if not levels_purchased.count():
        if level_name != '1':
          message = 'You don\'t have access to Level %s' % level_name
          template_vals = {'can_play': False,
                           'message': message}
          path = os.path.join(os.path.dirname(__file__),
                              'templates',
                              'game_play.html')
          self.response.out.write(template.render(path, template_vals))
          return
        else:
          next_level = ''
    elif curr_level.owner != user:
      message = 'You don\'t have access to Level %s' % level_name
      template_vals = {'can_play': False,
                       'message': message}
      path = os.path.join(os.path.dirname(__file__),
                          'templates',
                          'game_play.html')
      self.response.out.write(template.render(path, template_vals))
      return

    sprite_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                          "AND item_name = '%s'") %
                                         (user.federated_identity(),
                                          'Sprite'))
    sprite = ('translate_robot-lb64'
              if sprite_purchased.count() else 'android-64')

    static_blocks = pickle.loads(str(curr_level.static_blocks))
    move_blocks = pickle.loads(str(curr_level.move_blocks))
    player_start = pickle.loads(str(curr_level.player_start))
    door = pickle.loads(str(curr_level.door))
    # pickle outputs str and expects it back, though app engine
    # stores and returns from the DB as unicode
    template_vals = {'can_play': True,
                     'entity_size': curr_level.entity_size,
                     'canvas_height_blocks': curr_level.canvas_height_blocks,
                     'canvas_width_blocks': curr_level.canvas_width_blocks,
                     'step_size': curr_level.step_size,
                     'sprite': sprite,
                     'base_blocks': curr_level.base_rows,
                     'player_start': player_start,
                     'door': door,
                     'static_blocks': static_blocks,
                     'move_blocks': move_blocks,
                     'next_level': next_level}

    path = os.path.join(os.path.dirname(__file__),
                        'templates',
                        'game_play.html')
    self.response.out.write(template.render(path, template_vals))
Пример #11
0
from models import Level, OfficialScores, db


level_ids = dict()
levels = Level.query.all()
for level in levels:
    level_ids[level.internal_name] = level.level_id

site = urllib2.urlopen('http://nebula.zachtronicsindustries.com/spacechem/score')
scores = site.read()
deserialized = json.loads(scores)

for level in deserialized:
    # if a new level has been added, need to insert it first
    if level not in level_ids:
        new_level = Level()
        new_level.internal_name = level
        new_level.slug = level
        researchnet_pattern = re.compile(r'^published\-(\d+\-\d+)$')
        if researchnet_pattern.search(level):
            new_level.number = researchnet_pattern.search(level).groups()[0]
            new_level.name = 'ResearchNet Published '+new_level.number
            new_level.order1 = new_level.number.split('-')[0]
            new_level.order2 = new_level.number.split('-')[1]
            new_level.category = 'researchnet'
        else:
            new_level.number = 'X-X'
            new_level.name = 'Unknown Name'
        db.session.add(new_level)
        db.session.commit()
        level_ids[level] = new_level.level_id
Пример #12
0
  def post(self):
    """Handles post requests."""
    user = users.get_current_user()
    builder_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                           "AND item_name = '%s'") %
                                          (user.federated_identity(),
                                           'Builder'))
    can_build = (builder_purchased.count() > 0)

    level_name = self.request.get('level')
    if level_name in ['1', '2', '3', '4', '5']:
      self.SendError('%s is already a level' % level_name, can_build)
      return
    else:
      existing = Level.gql("WHERE owner = USER('%s') AND level='%s'"
                           % (user.email(), level_name))
      if existing.count():
        self.SendError('%s is already a level' % level_name, can_build)
        return

    # Validate base_rows
    max_column = 23
    max_row = 9

    base_rows = self.request.get('base_rows', None)
    try:
      base_rows = int(base_rows)
      if base_rows < 0 or base_rows > max_row:
        self.SendError(('%s is invalid for rows at bottom '
                        'of screen' % base_rows), can_build)
        return
    except (ValueError, TypeError):
      self.SendError(('%s is invalid for rows at bottom '
                      'of screen' % base_rows), can_build)
      return

    # Validate static
    static = self.ParseRowsFromRequest('static')
    if static is None:
      self.SendError(('Static Blocks invalid. Please use '
                      'integers and separate rows by commas'), can_build)
      return

    # Validate moveable
    moveable = self.ParseRowsFromRequest('moveable')
    if moveable is None:
      self.SendError(('Moveable Blocks invalid. Please use '
                      'integers and separate rows by commas'), can_build)
      return

    # Update static or fail if moveable and static share blocks;
    # also fail if a moveable block would end up hovering
    for column, row_list in moveable.iteritems():
      destination = static[column] if column in static else []
      for row in row_list:
        if row in destination:
          self.SendError(('Moveable and Static Blocks can\'t occupy '
                          'the same place'), can_build)
          return
        elif row > base_rows:  # if in row base_rows, block will be supported
          if row - 1 not in row_list + destination:
            self.SendError('Moveable can\'t hover', can_build)
            return

    # Validate door
    door_column = self.request.get('door_column', '')
    door_row = self.request.get('door_row', '')
    try:
      door_column = int(door_column)
      door_row = int(door_row)
      # Door must be on screen;
      # Door has height of 2 blocks, so can't start in the top row
      if (door_row < base_rows or door_row > max_row - 1 or
          door_column < 0 or door_column > max_column):
        self.SendError('Door out of bounds', can_build)
        return

      # Door must not conflict with squares
      if door_column in static:
        if (door_row in static[door_column] or
            door_row + 1 in static[door_column]):
          self.SendError('Door conflicts with Static Blocks', can_build)
          return
      elif door_column in moveable:
        if (door_row in moveable[door_column] or
            door_row + 1 in moveable[door_column]):
          self.SendError('Door conflicts with Moveable Blocks', can_build)
          return
    except (ValueError, TypeError):
      self.SendError('Door values invalid', can_build)
      return

    door = {'row': door_row,
            'column': door_column}

    # Validate player
    player_column = self.request.get('player_column', '')
    player_row = self.request.get('player_row', '')
    try:
      player_column = int(player_column)
      player_row = int(player_row)
      # Player must start on screen
      if (player_row < base_rows or player_row > max_row or
          player_column < 0 or player_column > max_column):
        self.SendError('Player out of bounds', can_build)
        return

      # Make sure no collisions with obstacles; though
      # Player *CAN* start in the door if the creator wants it
      if player_column in static and player_row in static[player_column]:
        self.SendError('Player conflicts with Static Blocks', can_build)
        return
      elif player_column in moveable and player_row in moveable[player_column]:
        self.SendError('Player conflicts with Moveable Blocks', can_build)
        return

      # Player must start on ground
      if player_row != base_rows:
        block_below = False
        if player_column in static:
          if player_row - 1 in static[player_column]:
            block_below = True
        if player_column in moveable:
          if player_row - 1 in moveable[player_column]:
            block_below = True

        if not block_below:
          self.SendError('Player must start grounded', can_build)
          return
    except (ValueError, TypeError):
      self.SendError('Player values invalid', can_build)
      return

    player_start = {'x': player_column*64,  # default entity_size
                    'y': 64*(10 - (player_row + 1))}  # default canvas_height

    new_level = Level(owner=user,
                      level=level_name,
                      base_rows=base_rows,
                      static_blocks=DBPIckle(static),
                      move_blocks=DBPIckle(moveable),
                      door=DBPIckle(door),
                      player_start=DBPIckle(player_start))
    new_level.put()

    self.redirect('/play?level=%s' % level_name)
Пример #13
0
def build_levels():
    for l in levels:
        for g in Level.GENDER_CHOICES:
            level = Level(name=l, gender=g[0])
            level.save()
Пример #14
0
  def get(self):
    """Handles get requests."""
    user = users.get_current_user()

    logged_in = (user is not None)
    if logged_in:
      # explicity disobeying:
      # http://code.google.com/appengine/docs/python/users/userclass.html
      # "If you use OpenID, you should not rely on this email address to
      # be correct. Applications should use nickname for displayable names."
      # In limited experience, it seems nickname == federated_identity
      display_name = user.email()
      sign_out = users.create_logout_url(self.request.uri)

      now = int(time.time())
      now_plus_one = now + 3600
      identity = user.federated_identity()

      request_info = {'currencyCode': 'USD',
                      'sellerData': identity}
      basic_jwt_info = {'iss': SELLER_ID,
                        'aud': 'Google',
                        'typ': 'google/payments/inapp/item/v1',
                        'iat': now,
                        'exp': now_plus_one,
                        'request': request_info}

      # Start off assuming the user has bought everything there is to buy
      can_purchase = False

      # Check every possible item to see if user has purchased
      levels_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                            "AND item_name = '%s'") %
                                           (identity, 'Levels'))
      levels = ['1']
      levels_token = ''
      if levels_purchased.count() > 0:
        levels.extend(['2', '3', '4', '5'])
      else:
        can_purchase = True
        request_info.update({'name': 'Levels', 'price': '0.50'})
        levels_token = jwt.encode(basic_jwt_info, SELLER_SECRET)

      sprite_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                            "AND item_name = '%s'") %
                                           (identity, 'Sprite'))
      sprite_token = ''
      if sprite_purchased.count() == 0:
        can_purchase = True
        request_info.update({'name': 'Sprite', 'price': '0.50'})
        sprite_token = jwt.encode(basic_jwt_info, SELLER_SECRET)

      builder_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                             "AND item_name = '%s'") %
                                            (identity, 'Builder'))
      user_levels = []
      builder_token = ''
      if builder_purchased.count() == 0:
        can_purchase = True
        request_info.update({'name': 'Builder', 'price': '2.00'})
        builder_token = jwt.encode(basic_jwt_info, SELLER_SECRET)
      else:
        level_query = Level.gql("WHERE owner = USER('%s')" % user.email())
        for level in level_query:
          user_levels.append(level.level)

      source_purchased = PurchasedItem.gql(("WHERE federated_identity = '%s' "
                                            "AND item_name = '%s'") %
                                           (identity, 'Source'))
      source_token = ''
      if source_purchased.count() == 0:
        can_purchase = True
        request_info.update({'name': 'Source', 'price': '8.00'})
        source_token = jwt.encode(basic_jwt_info, SELLER_SECRET)

      no_purchases = (levels_token and sprite_token and
                      builder_token and source_token)
      template_vals = {'logged_in': logged_in,
                       'display_name': display_name,
                       'sign_out': sign_out,
                       'levels': levels,
                       'user_levels': user_levels,
                       'levels_jwt': levels_token,
                       'sprite_jwt': sprite_token,
                       'builder_jwt': builder_token,
                       'source_jwt': source_token,
                       'can_purchase': can_purchase,
                       'no_purchases': no_purchases}
    else:
      # let user choose authenticator
      continue_url = self.request.GET.get('continue', None)
      dest_url = self.request.uri if continue_url is None else continue_url

      # Thanks to Wesley Chun
      # http://code.google.com/intl/pl/appengine/articles/openid.html
      providers = []
      for display, link in OPEN_ID_PROVIDERS:
        providers.append((users.create_login_url(dest_url=dest_url,
                                                 federated_identity=link),
                          display))

      template_vals = {'logged_in': logged_in,
                       'user_continue': continue_url,
                       'providers': providers}

    path = os.path.join(os.path.dirname(__file__), 'templates', 'index.html')
    self.response.out.write(template.render(path, template_vals))
Пример #15
0
def update_conf(config, log):
    config.update()
    config.get_data()

    return Route(Level(0))
Пример #16
0
 def get(self):
     level = Level()
     level.grid = "abcdefghijklmnopqrstuvwxyzaabcdefghijklmnopqrstuvwxyzaabcdefghijklmnopqrstuvwxyzaabcdefghi"
     level.word_bank = ["abc", "def", "ghi", "klmnop"]
     level.time = datetime.datetime.now()
     level.put()
Пример #17
0
def cli(config, log, case=Level(0)):
    if route := Route.get(case):
Пример #18
0
            [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ','c',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ','c',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ','c',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ','c',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            [' ',' ',' ',' ','c',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' '],
            ['c','c','c','c','c','c','c','c','c','c','c','c','c','c','c','c'],
        ]

xRes, yRes = (int)(gameScale * 256), (int)(gameScale * 256)
level = Level(16, 16, 2)
level.setAllTiles(tileData)
level.setAllDecorations(decorationData)

def loadTextures():
    global playerTextures, wallTextures, ceilingTextures, floorTextures

    playerTextures = loadCharacterSpritesheet('assets/' + playerType + '.png', 32, 32, 10, 10, xScale=gameScale, yScale=gameScale, colorkey=-1)
    wallTextures = loadSpritesheet('assets/wall.png', 16, 32, xScale=gameScale, yScale=gameScale)
    ceilingTextures = loadSpritesheet('assets/ceiling.png', 16, 16, xScale=gameScale, yScale=gameScale)
    floorTextures = loadSpritesheet('assets/floor.png', 16, 16, xScale=gameScale, yScale=gameScale)

def loadLevel(tileData, decorationData, outputLevel):
    for y in range(0, 16):
        for x in range(0, 16):
            if tileData[y][x] == 'W':
Пример #19
0
    [
        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
        ' ', ' '
    ],
    [
        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
        ' ', ' '
    ],
    [
        ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
        ' ', ' '
    ],
]

xRes, yRes = (int)(gameScale * 256), (int)(gameScale * 256)
level = Level(16, 16, 2)
level.setAllTiles(tileData)
level.setAllDecorations(decorationData)


def loadTextures():
    global playerTextures, wallTextures, ceilingTextures, floorTextures

    items1_Names = [
        'Ящик', 'Открый ящик', 'Сундук', 'Открый сундук', 'Бочка',
        'Открытая бочка', 'Мешочек', 'Мешок', 'Большой мешок'
    ]  ###список с именами объектов в таком же порядке, как в tileset-картинке
    itemSprites1 = loadSpritesheet(
        'assets/Items1.png', 16, 32, xScale=gameScale,
        yScale=gameScale)  #режем вещи Items1.png на отдельные картинки-объекты
    for i in range(
Пример #20
0
    def test_get_distance_view(self):
        from django.test import RequestFactory
        from django.core.urlresolvers import reverse
        from views import distance
        from models import Level, StairWell
        factory = RequestFactory()
        well = StairWell(building='ASP', shaft='South-East')
        well.save()

        l0 = Level(stairwell=well, floorNumber=0,
                   steps=0)  # steps for this one should never matter.
        l0.save()
        l1 = Level(stairwell=well, floorNumber=1)
        l1.save()
        l2 = Level(stairwell=well, floorNumber=2)
        l2.save()
        l3 = Level(stairwell=well, floorNumber=3)
        l3.save()
        l8 = Level(stairwell=well, floorNumber=8)
        l8.save()

        rq = factory.get(reverse('distance'),
                         data={
                             'qr_id_1': l0.pk,
                             'qr_id_2': l3.pk
                         })

        response = distance(rq)
        self.assertIsNotNone(response)
        data = json.loads(response.content)
        self.assertIsNotNone(data['distance'])
Пример #21
0
from main import DBPIckle
from models import Level


level_one = Level(level='1', next_level='2', base_rows=4,
                  static_blocks=DBPIckle({7: [4, 5], 13: [4], 17: [4, 5]}),
                  move_blocks=DBPIckle({2: [4], 10: [4]}),
                  door=DBPIckle({'row': 4, 'column': 23}),
                  player_start=DBPIckle({'x': 256, 'y': 320}))
level_one.put()
level_two = Level(level='2', next_level='3', base_rows=4,
                  static_blocks=DBPIckle({12: [4, 5], 23: [4, 5, 6]}),
                  move_blocks=DBPIckle({0: [4, 5], 3: [4], 22: [4]}),
                  door=DBPIckle({'row': 7, 'column': 23}),
                  player_start=DBPIckle({'x': 256, 'y': 320}))
level_two.put()
level_three = Level(level='3', next_level='4', base_rows=3,
                    static_blocks=DBPIckle(
                        {0: [3, 4], 1: [3, 4], 2: [3, 4],
                         3: [3, 4], 4: [3, 4], 5: [3, 4],
                         11: [3, 4], 12: [3, 4], 13: [3, 4],
                         14: [3, 4], 15: [3, 4], 16: [3, 4],
                         17: [3, 4], 18: [3, 4], 19: [3, 4],
                         20: [3, 4], 21: [3, 4], 22: [3, 4],
                         23: [3, 4]}),
                    move_blocks=DBPIckle({0: [5]}),
                    door=DBPIckle({'row': 5, 'column': 23}),
                    player_start=DBPIckle({'x': 256, 'y': 256}))
level_three.put()
level_four = Level(level='4', next_level='5', base_rows=2,
                   static_blocks=DBPIckle(
Пример #22
0
def correct_back(config, log):
    return Route(Level(0))