def deal_hand(self, participant): """ Deal a (randomly selected) hand from the game's answer deck. """ deck_size = len(self.answer_deck) if deck_size < config.SIZE_OF_HAND: logging.warn("not enough cards") return None # this case, where the participant already has a hand dealt, 'should' not # actually come up. (should it be an error if it does?) if participant.cards: return participant.cards participant.cards = [] for _ in range(0, config.SIZE_OF_HAND): # note: since the deck is already shuffled, probably don't really need to # select randomly from it... idx = random.randint(0, deck_size-1) card = self.answer_deck[idx] participant.cards.append(card) del self.answer_deck[idx] deck_size -= 1 model.put_multi([participant, self]) logging.debug( "participant %s got hand %s", participant.plus_id, participant.cards) logging.debug("answer deck is now: %s", self.answer_deck) return participant.cards
def get(self): pkey = Publisher.create('Museum of Vertebrate Zoology').put() ckey = Collection.create('Birds', pkey).put() start = int(self.request.get('start')) size = int(self.request.get('size')) logging.info('start=%s, size=%s' % (start, size)) count = -1 created = 0 path = os.path.join(os.path.dirname(__file__), 'data.csv') reader = csv.DictReader(open(path, 'r'), skipinitialspace=True) dc = [] dci = [] while start >= 0: reader.next() start -= 1 for rec in reader: if created == size: model.put_multi(dc) model.put_multi(dci) rec = dict((k.lower(), v) for k, v in rec.iteritems()) # lowercase all keys dc.append(Record.create(rec, ckey)) dci.append(RecordIndex.create(rec, ckey)) created += 1 self.response.out.write('Done. Created %s records' % created)
def get(self): pkey = Publisher.create("Museum of Vertebrate Zoology").put() ckey = Collection.create("Birds", pkey).put() start = int(self.request.get("start")) size = int(self.request.get("size")) logging.info("start=%s, size=%s" % (start, size)) count = -1 created = 0 path = os.path.join(os.path.dirname(__file__), "data.csv") reader = csv.DictReader(open(path, "r"), skipinitialspace=True) dc = [] dci = [] while start >= 0: reader.next() start -= 1 for rec in reader: if created == size: model.put_multi(dc) model.put_multi(dci) rec = dict((k.lower(), v) for k, v in rec.iteritems()) # lowercase all keys dc.append(Record.create(rec, ckey)) dci.append(RecordIndex.create(rec, ckey)) created += 1 self.response.out.write("Done. Created %s records" % created)
def _calculate_scores(self, game): # for all active participants, calculate everyone's scores, based on # yet-to-be-defined metrics. As a strawman method, just set a score for each # participant based upon how many others voted for that person. participants = game.participants() pvotes = self._build_votes_dict(participants) for p in participants: p.score = pvotes.get(p.plus_id, 0) # accumulate game score and hangout_score with this round's results. p.game_score += p.score p.hangout_score += p.score model.put_multi(participants) return participants
def testPutMulti(self): ent1 = model.Model(key=model.Key('MyModel', 1)) ent2 = model.Model(key=model.Key('MyModel', 2)) ent3 = model.Model(key=model.Key('MyModel', 3)) res = model.put_multi((ent1, ent2, ent3)) self.assertEqual(res, [ent1.key, ent2.key, ent3.key])
def _tx(): dirty = False hangout = cls.get_by_id(hangout_id) if not hangout: hangout = cls(id=hangout_id) dirty = True if hangout.current_game: game = hangout.current_game.get() else: game = Game.new_game(hangout) game.put() hangout.current_game = game.key dirty = True if dirty: model.put_multi([hangout, game]) return game
def _tx(): game = game_key.get() participant = cls.get_by_id(plus_id, parent=game_key) if not participant: participant = cls(id=plus_id, parent=game_key) participant.channel_id = str(participant.key) participant.channel_token = channel.create_channel( participant.channel_id) participant.playing = True # deal the hand for the participant. # TODO - deal with the case where the player did not get any cards, # indicated if hand is None. hand = game.deal_hand(participant) # if not hand: # react usefully if there were not enough cards for their hand. model.put_multi([participant, game]) return participant
def post(self): # Parameters checked by frontend name = self.request.get('name') source_name = self.request.get('source') # Get source source = sources.get(source_name) if not source: logging.error('Cannot harvest without a source') self.error(404) # Update job status to 'error' job = get_job(name, source_name, 'error', msg='Unsupported source') cache.add(key, job) return # Check cache for harvest job key = get_job_cache_key(name, source_name) job = cache.get(key) if not job: self.error(404) self.response.headers['Content-Type'] = "application/json" self.response.out.write('{"error":"unknown job %s"}' % key) return count = 0 # Update job status to 'working' cache.add(key, get_job(name, source_name, 'working', msg=count)) # Get points from source and put them into datastore in batches pcount = 0 for points in self.get_points(name, source): logging.info('HARVEST BACKEND MEMORY = %s after %s points' % (runtime.memory_usage().current(), count)) entities = [] for p in points: pkey = Key('Point', '%s-%s-%s' % (source_name, name, pcount)) pcount += 1 entities.append(Point(key=pkey, lat=p[0], lng=p[1])) entities.append(PointIndex.create(pkey, p[0], p[1], name, source_name)) model.put_multi(entities) count += len(points) cache.add(key, get_job(name, source_name, 'working', msg=count)) # Update job status to 'done' # TODO: Done now or after backend rendering completes? cache.add(key, get_job(name, source_name, 'done', msg=count))
def getcells(cls, cell_keys): """Gets CouchDBCell entities corresponding to a set of cell keys. Arguments: cell_keys - A set of cell key strings (e.g., 9-15). Returns: A dictionary of cell key to CouchDBCell. """ logging.info(cell_keys) cells = {} # Get cached cells cached = memcache.get_multi(cell_keys) cells.update(cached) # Calculate any uncached cell keys cell_keys = cell_keys.difference(cached.keys()) cachecells = False # Check datastore for any uncached cell keys if len(cell_keys) > 0: cachecells = True stored = cls.fromds(cell_keys) cells.update(stored) # Calculate any cell keys not in datastore cell_keys = cell_keys.difference(stored.keys()) # Check CouchDB for any cells not in datastore if len(cell_keys) > 0: cachecells = True couched = cls.fromcouchdb(cell_keys) cells.update(couched) # Put cells from CouchDB into datastore model.put_multi(couched.values()) # Cache cells if cachecells: memcache.set_multi(cells) return cells
def start_new_game(cls, hangout_id, old_participants): """If there is a current game, set its end time. Then create a new game and set it as the current hangout game, using the participant list of the previous game. Returns the new game. """ hangout = cls.get_by_id(hangout_id) if not hangout: # TODO: should this be an error instead? hangout = cls(id=hangout_id) if hangout.current_game: current_game = hangout.current_game.get() current_game.end_time = datetime.datetime.now() # get the current active participants # TODO: do we need to set these to inactive? don't think so, # since parent game will no longer be current, and we retrieve by parent # game. # old_participants = current_game.participants() new_game = Game.new_game(hangout) new_game.put() # save now to generate key # associate new participant objects, using plus_id of the old obj, # with the new game. new_participants = [] for p in old_participants: newp = Participant(id=p.plus_id, parent=new_game.key) # keep the same channel id and token. # TODO - are there any issues in doing this? # (channel id is based on participant key from original game, but thus # far we don't ever need to reconstruct the keys). newp.channel_id = p.channel_id newp.channel_token = p.channel_token newp.hangout_score = p.hangout_score newp.playing = True new_participants.append(newp) new_game.select_new_question() # deal cards to the (copied-over) participants new_game.deal_hands(new_participants) hangout.current_game = new_game.key model.put_multi(new_participants) model.put_multi([hangout, current_game, new_game]) return new_game
def start_new_round(self, participants): """ start a new round of the given game. """ # first check that we have not maxed out the number of rounds for this # game. # The calling method 'should' have checked this already. if self.current_round >= (config.ROUNDS_PER_GAME - 1): # TODO - assuming it makes sense to have this be an exception, should # define a 'GameException' subclass or similar. raise Exception("Have reached last round in game; can't start new one.") self.state = 'start_round' # select a new question card for the round self.select_new_question() self.current_round += 1 # now reset the participants' votes, card selections, and round score. # Keep the game and hangout scores. logging.info("in start_new_round, with participants %s", participants) for p in participants: p.vote = None p.selected_card = None p.score = 0 self.put() model.put_multi(participants)
def populate(n): xs = [Foo() for i in xrange(n)] ks = model.put_multi(xs)