def _get_team_map_win_loss(team, map): team_a_count = Game.query().filter(Game.map == map).filter(Game.team_a == team.name).count() team_b_count = Game.query().filter(Game.map == map).filter(Game.team_b == team.name).count() win_count = Game.query().filter(Game.map == map).filter(Game.winner == team.name).count() game_count = team_b_count + team_a_count per = 0 if not game_count else round(100 * float(win_count)/game_count) return [map, game_count, win_count, per]
def cancel_game(self, request): """ Cancels a Blackjack Marathon game based on key. """ profile_key = Profile.get_profile_from_user().key Game.cancel_game(profile_key, request.urlsafe_game_key) return StringMessage(message='Game cancelled successfully.')
def get(self): # Can't provide an ordering here in case inequality filters are used. base_query = Game.all() count = base_query.count() results = base_query.fetch(count) #db.delete(results) # for game in results: # resultsobj = resultsobj + simplejson.dumps({"latitude":game.location.lat,"longitude":game.location.lon,"name":game.name,"type":game.game_type}) # objs = simplejson.dumps(resultsobj) public_attrs = Game.public_attributes() results_obj = [ _merge_dicts({ 'lat': result.location.lat, 'lng': result.location.lon, }, dict([(attr, getattr(result, attr)) for attr in public_attrs])) for result in results] #for song in results: #print song.type # for result in query: # resultsobj.push( "Title: " + result.address self.response.out.write(simplejson.dumps({ 'status': 'success', 'count': count, 'results': results_obj }))
def test_points_multiple_games(self): game1 = Game( #tournament = self.tournament1, time = self.time, location = self.location, teamA=self.team1, teamB=self.team2, score_teamA=3, score_teamB=1, ) game2 = Game( #tournament = self.tournament1, time = self.time, location = self.location, teamA=self.team1, teamB=self.team2, score_teamA=1, score_teamB=1, ) game1.save() game2.save() self.assertEquals(self.team1.points, 4) self.assertEquals(self.team2.points, 1) game1.delete() game2.delete()
class GameView(TemplateView): template_name = 'gameshow/game.html' def _start_game(self): player = Player.objects.create(name="Some Name", score=0) self.thegame = Game() self.thegame.players = player self.thegame.title = 'My Game Title' self.thegame.description = "Blah Blah Blah" self.thegame.save() def post(self, request, *args, **kwargs): form = GameScore(request.POST) if form.is_valid(): messages.add_message(self.request, messages.INFO, message="Enjoy your game!") return redirect('game_main') else: return self.get(request, form=form) def get_context_data(self, **kwargs): self._start_game() return { 'form': GameScore() if not kwargs.get('form') else kwargs['form'], 'game': self.thegame, }
def createGame(self, request): """ a player creates a game of a unique name """ if request.game_name is None: raise endpoints.UnauthorizedException( 'game_name is required to create a game') player = Player.query(Player.displayName == request.player_name).get() if not player: raise endpoints.NotFoundException( 'No player found with name: {}' .format(request.player_name)) elif Game.query(Game.name == request.game_name).get(): raise endpoints.ConflictException( 'A Game with that name already exists!') else: # allocate new Game ID with Player key as parent # allocate_ids(size=None, max=None, parent=None, **ctx_options) # returns a tuple with (start, end) for the allocated range, # inclusive. p_key = player.key g_id = Game.allocate_ids(size=1, parent=p_key)[0] # make Game key from ID; assign initial values to the game entity g_key = ndb.Key(Game, g_id, parent=p_key) data = {} # is a dict data['key'] = g_key data['name'] = request.game_name data['board'] = ['' for _ in range(9)] Game(**data).put() taskqueue.add(params={'email': player.mainEmail, 'gameInfo': repr(request)}, url='/tasks/send_confirmation_email') game = g_key.get() return game._copyGameToForm
def open_or_new_games(request): if not request.COOKIES.get('nickname', ''): return HttpResponseRedirect(reverse(set_nickname)) if request.method == 'POST': form = NewGameForm(request.POST) if form.is_valid(): nickname = re.sub(r'\W', '', request.COOKIES.get('nickname', '')) num_players = form.cleaned_data['number_of_players'] game = Game(name=nickname, num_players=num_players) game.save() try: player = game.add_player(nickname, True) request.session['player_id'] = player.id request.session['game_id'] = game.id except Game.InvalidPlayer as x: pass #TODO: add session error message return HttpResponseRedirect(reverse(current_game)) else: form = NewGameForm() return direct_to_template(request, 'open_or_new_games.html', {'form': form })
def create_game(self, request) : """Create new conference.""" #get the user ID first and make sure they're authorised user = endpoints.get_current_user() if not user: raise endpoints.UnauthorizedException('Authorization required') user_id = getUserId(user) #now create the game entity and insert it game = Game(owner=user_id, player1=GameMiniForm.get('player1'), player2=GameMiniForm.get('player2'), name=GameMiniForm.get('name')) playerTurn = 1 #set the player turn randomly if bool(random.getrandbits(1)) : playerTurn = 1 else : playerTurn = 2 game.playerTurn = playerTurn game_key = game.put() url_key = game_key.urlsafe() #return all of the game details, including a game key return GameForm(id=url_key, owner=user_id, player1=game.player1, player2=game.player2, name=game.name)
def get(self, name): if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) logging.info('Iniciando busca') results = search_metacritic(name, 'game') logging.info('Fetch concluido') output = [] for result in results: query = Img.all() query.filter('url =', result[1]) img = query.fetch(1)[0] query = Game.all() query.filter('cover =', img) if not query.count(): platform = str(result[1])[:str(result[1]).rfind('/')].replace('/game/','') game = Game(name=str(result[0]),cover=img,platform=platform,score=str(result[2])) game.put() else: game = query.fetch(1)[0] output.append([img.key().id(), result[0], game.key().id()]) template_values = {'results': output} path = os.path.join(os.path.dirname(__file__), 'search.html') self.response.out.write(template.render(path, template_values))
def post(self): """reset points/refresh image""" user = users.get_current_user() game = Game() this_player = game.selectOne(config.JIVE_PROFILE_TBL, "fullname, title, picture_binary, id", "`email` = {}", [user.email()]) jsonstring = self.request.body jsdict = json.loads(jsonstring) if jsdict.get("reset-game"): game.deleteGameProgress(str(this_player[3])) base64string = base64.encodestring('{0}:{1}'.format(config.jive_username,config.jive_password))[:-1] name = this_player[0] content = "<body><p>" + name + " just reset their game in <a href='https://medifaces-demo-1.appspot.com/' class='jive-link-community-small'>Medifaces</a></p><p></p><p><em>Posted by <a href='https://mdsol.jiveon.com/docs/DOC-14722'>ExpressBot</a></em></p></body>" data = json.dumps({"visibility": "place", "parent": config.jive_placeUrl + "/"+ str(config.jive_medifaces_space), "type":"update", "content":{ "type":"text/html", "text":content}}) result = urlfetch.fetch(method=urlfetch.POST, url=config.jive_contentUrl, deadline=15, headers={"X-Jive-Run-As": "email " + user.email(), 'Authorization': 'Basic ' + base64string, "Content-Type": "application/json"}, payload=data).content broadcast('%s just reset their game!' % user.email()) ret = {"result": "Game progress successfully reset"} elif jsdict.get("refresh-img"): ret = self.refreshPhoto(this_player, user.email(), game) elif jsdict.get("gender"): gender = jsdict.get("gender") ret = self.changeGender(this_player, user.email(), game, gender) else: logging.error("POST request without correct data") ret = {"error": "Something went wrong. Sorry about that. Try reloading this page."} self.response.write(json.dumps(ret))
def create_game(game_type, room_id): if request.method == 'GET': dealer = Player() session.add(dealer) game = Game(game_type) session.add(game) deck = Hand() session.add(deck) game.deck = deck if game_type == 'Blackjack': i = 1 while i <= 5: seat = Seat(i) game.seats.append(seat) session.commit() i += 1 game.time = datetime.datetime.now() game.dealer = dealer dealer_hand = Hand() dealer.hands.append(dealer_hand) game.players.append(current_user) session.commit() if room_id != 0: room = session.query(GameRoom).filter(GameRoom.id == room_id).all()[0] room.current_game = game return redirect(url_for('game_room', room_id=room_id)) else: room = GameRoom() room.current_game = game session.commit() return redirect(url_for('game_room', room_id=room.id))
def post(self): game = Game() #Check logged in user = users.get_current_user() if not user: self.response.write(json.dumps(dict(error="Dude, you gotta be logged in! Try reloading this page."))) return this_player = game.selectOne(config.JIVE_PROFILE_TBL, "fullname, title, picture_binary, id", "`email` = {}", [user.email()]) if this_player is None: logging.info("couldn't find player in jive_profile table (email: '{0}')".format(email)) self.response.write(json.dumps({"result":"refresh"})) return #Get the json passed from the client page jsonstring = self.request.body jsdict = json.loads(jsonstring) if 'filterchange' not in jsdict: ret = self.choice_picked(game, this_player, jsdict) else: ret = self.new_filter(game, this_player, jsdict) self.response.write(json.dumps(ret))
def test_make_deck_shuffle_hit(self): # setup player = Player('cory', 'password') game = Game('Blackjack') game.players.append(player) h = Hand() h2 = Hand() game.hands.append(h) player.hands.append(h2) cards = piece_maker(suits, card_values, 1) h.cards.extend(cards) cards_app.session.commit() # end of setup # deck is made in setUp() with piece_maker() ha game.deck = h game.hands.append(h2) deck = game.deck hand2 = h2 cards_app.session.flush() assert deck.cards != shuffle(deck) hand_before_hit = len(hand2.cards) deck_before_hit = len(deck.cards) hit(hand2, 1) cards_app.session.commit() # do we still have 52 cards after hitting? assert len(set(deck.cards)) + len(set(hand2.cards)) == 52 assert len(deck.cards) == deck_before_hit-1 assert len(hand2.cards) == hand_before_hit+1
def startGame(session): """ Starts the new game in one of the sessions. """ game = Game() game.session = session
def _get_team_win_loss(team): team_a_count = Game.query().filter(Game.team_a == team.name).count() team_b_count = Game.query().filter(Game.team_b == team.name).count() game_count = team_b_count + team_a_count win_count = Game.query().filter(Game.winner == team.name).count() per = round(100 * float(win_count)/game_count) return [_get_team_name_link(team.name), team.elo, game_count, win_count, per]
def game(request): #check if authed # print "user " + str(request.user) if not request.user.is_authenticated(): return HttpResponse('Unauthorized', status=401) if request.method == 'GET': #return a list of games available return get_json(list(Game.objects.all())) elif request.method == 'POST': # make sure authed try: json_data = json.loads(request.body) # user = this user new_game = Game(status = Game.OPEN) new_game.save() new_game.players.add(request.user) amounts = json_data['amounts'] for i, amount in enumerate(amounts): new_pile = Pile( position = i, amount = amount, game = new_game ) new_pile.save() return get_json(new_game) except Exception, e: return HttpResponseServerError("Malformed data!")
def post(self): user = users.get_current_user() if not user: self.redirect(users.create_login_url("/")) return game_name = self.request.get("game_name") if not game_name: self.response.write("No game name specified") return game_key = db.Key.from_path("Game", game_name) game = db.get(game_key) if not game: game = Game(key_name=game_name) game.put() logging.info("Game: {0}".format(game)) player = Player(user=user, parent=game) player.put() token = channel.create_channel("{0}:{1}".format(game_name, user.user_id())) logging.info("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token)) self.redirect("/game?gamename={0}&token={1}".format(game.key().id_or_name(), token))
def post(self): """ CREATE a new Game entity """ self.record_usage() namespace_manager.set_namespace(users.get_current_user().user_id()) param_map = {} param_map['player_faction'] = self.request.get('player_faction') param_map['player_warcaster'] = self.request.get('player_warcaster') param_map['opponent_name'] = self.request.get('opponent_name', '') param_map['opponent_faction'] = self.request.get('opponent_faction') param_map['opponent_warcaster'] = self.request.get('opponent_warcaster') param_map['result'] = self.request.get('result') param_map['size'] = int(self.request.get('size', 0)) param_map['won'] = self.request.get('won') == 'true' param_map['draw'] = self.request.get('draw') == 'true' param_map['teaching'] = self.request.get('teaching') == 'true' param_map['location'] = self.request.get('location', '') param_map['game_type'] = self.request.get('game_type', '') date = self.request.get('date') try: real_date = datetime.datetime.strptime(date,'%m/%d/%Y') except (ValueError): real_date = datetime.datetime.strptime(date,'%Y-%m-%d') param_map['date'] = real_date param_map['created_at'] = datetime.datetime.now() logging.error(param_map) game = Game(**param_map) game.put() self.response.out.write(game.key.urlsafe())
def get_sendable_board(game, side): board = game.get_board() # Only continue if the game hasn't finished if game.has_ended(): if side == 1: return Game.reverse_board(board) else: return board if side == 0 and not game.blue_setup: board[0] = unknown_row(side) board[1] = unknown_row(side) board[2] = unknown_row(side) board[3] = unknown_row(side) return board else: hidden_side_board = hide_side(board, side) if side == 1: return Game.reverse_board(hidden_side_board) else: return hidden_side_board
def test_blackjack_player_wins(self): player = Player('cory','password') game = Game('Blackjack') hand = Hand() player.bank = 100 player.hands.append(hand) game.hands.append(hand) game.players.append(player) bank_before_bet = player.bank # cards_app.session.commit() cards_app.session.flush() bet(hand, 50) cards = [Card(sequence=1), Card(sequence=10)] hand.cards.extend(cards) count_blackjack(hand) evaluate_hit(hand) # player wins with nautral evaluate_hit assert player.bank == bank_before_bet - 50 # player stands on 18, dealer stands on 17 hand.cards = [Card(sequence=10), Card(sequence=8)] bet(hand, 50) game.dealer = Player('cory','password') dealer = game.dealer dealer.cards = [Card(sequence=10), Card(sequence=17)] dealer_hand = Hand() dealer_hand.cards = dealer.cards
def __setupNewGame(player): game = Game(player1=player) # Randomize whether computer starts, or player if random.randint(1,2) == 1: game.nextTurn() return game
def __setupGame(self, startingBoard, turns): startingBoard = self.__translateBoard(startingBoard) player1 = Player(name="player1") player2 = Player(name="player2") game = Game(player1=player1, player2=player2) game.board = startingBoard game.turn = turns return game
def save_product(product_info, imgs_no_downloand): from models import GameImage, PricesGame, Game import requests prices = None imgs_downloand = None game = None try: if 'gift' not in product_info: product_info['gift'] = None if 'stock' not in product_info: from product import STOCK_CHOICE product_info['stock'] = STOCK_CHOICE.get('reserva') if 'pegi' not in product_info: product_info['pegi'] = None if not Game.objects.filter(Q(name=product_info['title']) & Q(plataform=product_info['platform'])).exists(): imgs_downloand = [] if imgs_no_downloand: for img in imgs_no_downloand: filename = get_filename(img) request_imagen = requests.get(img) if request_imagen.status_code is 200: image = GameImage(name=product_info['title']) image.save_image(filename, request_imagen.content) imgs_downloand.append(image) product_info['imagenes'] = imgs_downloand if imgs_downloand else None img = product_info['src'] filename = get_filename(img) request = requests.get(img) if request.status_code is 200: image = GameImage(name=product_info['title'][:15]) image.save_image("main." + filename.split('.')[1], request.content) product_info['imagen'] = image else: product_info['imagen'] = None prices = PricesGame() prices.add_price(product_info) product_info['prices'] = prices game = Game() game.add_game(product_info) else: prices = PricesGame() prices.add_price(product_info) product_info['prices'] = prices game = Game.objects.get(Q(name=product_info['title'])&Q(plataform=product_info['platform'])) game.prices.add(prices) except Exception: if prices: prices.delete() if 'imagen' in product_info: product_info['imagen'].delete() if imgs_downloand: for imagen in imgs_downloand: imagen.delete() if game: game.delete()
def handlefbrequestcallback(request): fp = open( 'tmp.3.log', 'w' ) print >> fp, request request_str = ( request.GET.get('request') ) request_to = ( request.GET.get('to') ) #request_from = ( request.GET.get('from') ) request_id = ( request.GET.get('id') ) request_from = request.session['fb_id'] #if request_to: # request_to = int(request_to.encode('ascii')) #if request_from: # request_from = int(request_from.encode('ascii')) #if request_id: # request_id = int(request_id.encode('ascii')) print >> fp, "request id", request_id print >> fp, "request string", request_str print >> fp, "request to", request_to print >> fp, "request from", request_from print >> fp, "request fb id", request.session['fb_id'] try: m_to = Member.objects.get(fb_id=request_to) except: # need to make member m_to = Member(fb_id=request_to) try: m_from = Member.objects.get(fb_id=request_from) except: # need to make member m_from = Member(fb_id=request_from) # name is set gamename = "%s_%s_%s" % ( request_from, request_to, time.asctime(time.gmtime()) ) r = Room(name=gamename) r.fb_request_id = request_id r.save() g = Game(room=r) # game name and room name duplicated g.name = gamename g.save() p = Player(game=g,turn=0) p.member = m_from p.save() # TODO assumes two player game - generalize p = Player(game=g,turn=1) p.member = m_to p.save() #return HttpResponseRedirect('requestpage.html') return HttpResponseRedirect( reverse('lupalo.views.lupalo') ) # Redirect after POST
def post(self): gameName = self.request.get("gameTitle") creator = self.request.get("user") newGame = Game(parent = PARENT_KEY, gameName = gameName, goals = [], gameCreator = creator) newGame.put() self.redirect(self.request.referer)
def DoGet(self): additional_values = { 'active_games': Game.all_active(), 'available_games': Game.all_available(), 'completed_games': Game.all_completed(), } self.template_values.update(additional_values) self.render_to_response("games.html")
def get_game(self, request): """ gets a single game """ game = get_by_urlsafe(request.urlsafeKey, Game) if game == 'Invalid Key': game = Game() return game.get_form(message="Game not found.") else: return game.get_form(message="game retrieved.")
def make_game_with_master(session, add_gm_to_game=True): game_master = make_users(1)[0] session.add(game_master) session.flush() game = Game(title='test game', password='******', starting_money=3) session.add(game) session.flush() if add_gm_to_game: game.add_game_master(user_id=game_master.id) return (game_master, game)
def test_registering_second_player(self): game = Game() game.register_player() self.assertEqual('Player 1', game.player_1.name) self.assertEqual('Player 2', game.player_2.name) self.assertEqual(0, game.player_1.location) self.assertEqual(False, game.player_1.in_motion) self.assertEqual(0, game.player_2.location) self.assertEqual(False, game.player_2.in_motion) self.assertEqual('locked', game.status)
def new_game(self, request): """Creates new game. Tipp: You need the urlsafe_key later""" player1 = Player.query(Player.name == request.player1).get() player2 = Player.query(Player.name == request.player2).get() if not (player1 and player2): raise endpoints.NotFoundException('No user with this name in the database') game = Game.new_game(player1.key, player2.key) # player.key gives a specific entity from the kind (Player) # and inputs this to new_game return Game.to_form(game, 'Good luck playing TICTACTOE!')
def get(self): """Send a reminder email to each User with an email about games. Called every hour using a cron job""" app_id = app_identity.get_application_id() users = User.query(User.email != None) for user in users: games = Game.query(Game.user == user.key).filter(Game.game_over != True).fetch() print(games) if len(games) > 0: print('remind me') subject = 'This is a reminder!' body = 'Hello {}, {} games of tictactoe are still active!'.format(user.name, len(games)) # This will send test emails, the arguments to send_mail are: # from, to, subject, body mail.send_mail('noreply@{}.appspotmail.com'.format(app_id), user.email, subject, body)
def test_DB_create_games_02(self): newGame = Game(gameId=10101, date="2000-01-01T00:00:00.000Z", season=1, homeTeamAbbr="", awayTeamAbbr="", homeTeamScore=12, awayTeamScore=15, postseason=False, city="") db.session.add(newGame) db.session.commit() query1 = Game.query.filter_by(gameId=10101).first() self.assertEqual(newGame, query1) db.session.delete(newGame) db.session.commit() query2 = Game.query.filter_by(gameId=10101).first() self.assertNotEqual(newGame, query2)
def test_DB_create_games_03(self): newGame = Game(gameId=1, date="1900-10-05T12:34:45.000Z", season=99, homeTeamAbbr="ABC", awayTeamAbbr="CBA", homeTeamScore=1, awayTeamScore=0, postseason=True, city="Austin") db.session.add(newGame) db.session.commit() query1 = Game.query.filter_by(gameId=1).first() self.assertEqual(newGame, query1) db.session.delete(newGame) db.session.commit() query2 = Game.query.filter_by(gameId=1).first() self.assertNotEqual(newGame, query2)
def get(self): today = datetime.date.today() statMap = {} game_list = [] namespace_manager.set_namespace(users.get_current_user().user_id()) query = Game.query() games = query.fetch(1000) for game in games: faction = game.player_faction if not faction in statMap: statMap[faction] = self.initialize_stats() statMap[game.player_faction]['count'] += 1 if game.won: statMap[game.player_faction]['wins'] += 1 if not game.teaching and not game.draw: statMap[game.player_faction]['nt_count'] += 1 months_ago = self.how_many_months_ago(game.date, today) if months_ago < 12: statMap[game.player_faction]['history'][months_ago] += 1 self.response.out.write(json.dumps(statMap))
def collect_game_data(opponent_uid=0, game=None): if not game: uid_list = [current_user.id, opponent_uid] user1_id = random.choice(uid_list) uid_list.remove(user1_id) game = Game( user1_id=user1_id, user2_id=uid_list[0], ) db.session.add(game) db.session.commit() return { 'gid': game.id, 'uid': current_user.id, 'oid': opponent_uid, 'udata': collect_user_data(), 'odata': collect_user_data(opponent_uid), 'state': game.state, 'X': game.user1.username, 'O': game.user2.username }
def get(self): """Send a reminder email to player who currently has games in progress""" players = Player.query(Player.email != None) for player in players: games = Game.query( ndb.OR(Game.playerOne == player.key, Game.playerTwo == player.key)).filter( Game.gameOver == False) if games.count() > 0: subject = 'Tic Tac Toe Reminder' body = 'Hello {}, you have {} games in progress. Their' \ ' keys are: {}'.format(player.name, games.count(), ', '.join(game.key.urlsafe() for game in games)) logging.debug(body) mail.send_mail( 'noreply@{}.appspotmail.com'.format( app_identity.get_application_id()), player.email, subject, body)
def all_v2(self, lang, lang_name, page, page_size): data = self.game_table.scan( FilterExpression=Attr('language').eq(lang))['Items'] totalCount = len(data) if not 1 < page_size <= totalCount: page_size = totalCount start_index = page_size * (page - 1) end_index = page_size * page data = data[start_index:end_index] return { "totalCount": totalCount, "page": page, "pageSize": page_size, "language": { "code": lang, "name": lang_name }, "results": [Game.to_api_structure(x) for x in data] }
def postGame(): try: # Add players addPlayer1 = Players(request.json['players'][0]) addPlayer2 = Players(request.json['players'][1]) db.session.add(addPlayer1) db.session.add(addPlayer2) # Add new Game newGame = Game('IN PROGRESS', '', request.json['columns'], request.json['rows']) db.session.add(newGame) db.session.commit() # Star new game session session = GameSession(addPlayer1.id, addPlayer2.id, newGame.id) db.session.add(session) db.session.commit() return jsonify({'gameId': str(newGame.id)}) except: return jsonify({"Error": "400"}), 400
def createGame(self, request, context): print("Create game request received") account = self.__get_account(request.playerID) ### # Code to create game and player entries goes here game = Game(status=GameStatus.CREATED, suspect_id=random.randrange(start=1, stop=6, step=1), room_id=random.randrange(start=7, stop=15, step=1), weapon_id=random.randrange(start=16, stop=21, step=1)) self.session.add(game) player = Player(account_id=account.id, game_id=game.id, number=1, name=request.name) self.session.add(player) ### self.session.commit() return self.__stream_updates(player)
def __email_task(): try: logging.info("Email task started") yesterday = datetime.datetime.now() - datetime.timedelta(days=1) stale_game_q = Game.query(Game.active == True, Game.updated < yesterday) stale_games = {} for game in stale_game_q.iter(): player_key = game.active_player_key if not player_key in stale_games: stale_games[player_key] = [] stale_games[player_key].append(game.key.id()) __send_emails(stale_games) logging.info("Email task complete") except Exception as e: # It can be dangerous to allow exceptions to bubble up to the job # scheduler in this case -- depending on what happens, it can get # stuck in a retry loop and start spamming our users. # Instead, log the problem and raise a "stop doing that!" exception. msg = "Unhandled exception during email task, aborting" logging.exception(msg) raise deferred.PermanentTaskFailure(msg)
def test_eat_food(): game = Game(width=10, height=10) g = Engine.create_game_state(game.id, game.width, game.height) Engine.add_snakes_to_board(g, [SNAKE_1]) Engine.add_food_to_board(g, [3, 1]) g.sanity_check() with open('lib/game/data/eat_food.in') as f: start_state = f.read().strip() assert(g.to_string().strip() == start_state) g = Engine.resolve_moves(g, [MOVE_RIGHT_1]) g.sanity_check() g = Engine.resolve_moves(g, [MOVE_RIGHT_1]) g.sanity_check() with open('lib/game/data/eat_food.out') as f: end_state = f.read().strip() assert(g.to_string().strip() == end_state.strip()) assert(len(g.food) == 0)
def get(self): """Send a reminder email to each User with an email about games. Called every 3 hours using a cron job""" app_id = app_identity.get_application_id() # Get unfinished games users = User.query() for user in users: # Get all the users games. games = Game.query(Game.user == user.key, Game.game_over == False) for game in games: logging.debug(game) subject = 'This is a reminder from HangmanApi!' body = ('Hello {}, ready to finish your game? ' 'Your topic was {}, and you still have' ' {} attempts left!').format(user.name, game.topic, game.attempts_remaining) # This will send test emails, the arguments to send_mail are: # from, to, subject, body mail.send_mail('noreply@{}.appspotmail.com'.format(app_id), user.email, subject, body)
def create_game(current_user): if not current_user.is_authenticated: return error("User must be authenticated", 403) body = flask.request.get_json() if body is None: return error("Could not decode body as JSON", 400) title = body.get("title") if (title is None) or (type(title) is not str): return error("Title required", 400) user_emails = body.get("users") if (user_emails is None) or (type(user_emails) is not list): return error("Emails of other players required", 400) if len(user_emails) < 1 or len(user_emails) > 5: return error("Player count is out of range", 400) users = [current_user] for user_email in user_emails: user = User.get_or_none(User.email == user_email) if user is None: return error("Unknown user", 400) else: users.append(user) game = Game.create(title, users) UserGame.create(current_user, game, UserRole.OWNER) # TODO: [1:] is kinda gross for user in users[1:]: UserGame.create(user, game, UserRole.PLAYER) for usergame in game.usergames: send_sync_notification(usergame.user_id) return success(game_id=game.id)
def new_game(self, request): """Creates new game""" user = User.query(User.name == request.name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') try: # create hidden blanks array hidden = [] # applylowercase to answer request.answer.lower() # fill hidden array with blanks for char in request.answer: if char == " ": hidden.append(",") else: hidden.append("_") guesses = [] date = datetime.datetime.now() # check if request.attempts_remaining is empty if not request.attempts_remaining: request.attempts_remaining = 6 game = Game.new_game(user.key, request.topic, request.answer, hidden, guesses, date, request.attempts_remaining) # store active game urlsafe into user for reference later user.activeGameKeys.append(game.key.urlsafe()) user.put() except ValueError: raise endpoints.BadRequestException('Cant create game') msg = 'Good luck playing Hangman!' game.add_to_history(msg, 'NONE') return game.to_form(msg)
def get(self): self.response.headers['Content-Type'] = 'application/json' param_key = SeedGenParams.from_url(self.request.GET) verbose_paths = self.request.GET.get("verbose_paths") is not None params = param_key.get() if params.generate(preplaced={}): players = [] resp = {} if params.tracking: game = Game.from_params(params, self.request.GET.get("game_id")) key = game.key resp["map_url"] = uri_for("map-render", game_id=key.id(), paths=" ".join(params.logic_paths)) resp["history_url"] = uri_for("game-show-history", game_id=key.id()) for p in range(1, params.players + 1): if params.tracking: seed = params.get_seed(p, key.id(), verbose_paths) else: seed = params.get_seed(p, verbose_paths=verbose_paths) spoiler = params.get_spoiler(p).replace("\n", "\r\n") players.append({ "seed": seed, "spoiler": spoiler, "spoiler_url": uri_for('gen-params-get-spoiler', params_id=param_key.id(), player=p) }) resp["players"] = players self.response.out.write(json.dumps(resp)) else: log.error("param gen failed") self.response.status = 500
def get(self, game_id, type, num, ext): game = Game.query(Game.id == game_id).get() try: num = int(num) except: self.response.write('Invalid ' + type + ' number.') self.error(404) return if type == 'screenshot': # Check that the requested image exists for the game. if (not game.screenshots) or (len(game.screenshots) <= num): self.response.write('Screenshot ' + ` num ` + ' not found for game ' + game_id + '.') self.error(404) return # Output the screenshot. self.response.headers['Content-Type'] = get_content_type( game.screenshots[num], ext) self.response.write(game.screenshots[num]) elif type == 'thumbnail': # Check that the requested image exists for the game. if (not game.thumbnails) or int(num) >= (len(game.thumbnails)): self.response.write('Thumbnail ' + ` num ` + ' not found for game ' + game_id + '.') self.error(404) return # Output the thumbnail. self.response.headers['Content-Type'] = get_content_type( game.thumbnails[num], ext) self.response.write(game.thumbnails[num]) else: self.error(404)
def get(self): app_id = app_identity.get_application_id() open_games = Game.query(Game.status.IN(['p1 move','p2 move'])).fetch() emails_to_send = [] for g in open_games: if g.status == 'p1 move': user_email = g.p1.get().email elif g.status == 'p2 move': user_email = g.p2.get().email if user_email: emails_to_send.append((user_email, g.key.urlsafe())) for e in emails_to_send: subject = 'Your turn!' body = 'Just a reminder: It\'s your turn in the Battleship game with id {}!'.format(e[1]) # from, to, subject, body mail.send_mail('noreply@{}.appspotmail.com'.format(app_id), e[0], subject, body)
def get(self): """Send a reminder email to each User with an email about games. Called every hour using a cron job""" app_id = app_identity.get_application_id() games = Game.query(Game.game_over == False) users = User.query() user_keys = [] for game in games: if game.user_one not in user_keys: user_keys.append(game.user_one) if game.user_two not in user_keys: user_keys.append(game.user_two) for user in users: if user.key in user_keys: subject = 'This is a reminder!' body = ('Hello {}, you still have an' ' active Crazy Eights Game!').format(user.name) # This will send test emails, the arguments to send_mail are: # from, to, subject, body mail.send_mail('noreply@{}.appspotmail.com'.format(app_id), user.email, subject, body)
def add_game(): try: current_user = get_current_member_object() game_id = request.form.get('game') title = request.form.get('title') link = request.form.get('link') if game_id is not '0': game = Game.query.filter_by(id=game_id).one_or_none() if game not in current_user.ownership: current_user.ownership.append(game) db.session.commit() else: new_game = Game(title=title, link=link) db.session.add(new_game) current_user.ownership.append(new_game) db.session.commit() except Exception as e: db.session.rollback() return jsonify({'success': False}), e.status_code finally: current_user_id = current_user.id db.session.close() return redirect(f'/members/{current_user_id}')
def get_user_rankings(self, request): """Returns user rankings""" users = User.query() for user in users: total_rankings = 0 ranking = 0 games = Game.query(ancestor=user.key) for count, game in enumerate(games): # calculate ranking correct_guesses = (len(game.correct_guesses) - game.correct_guesses.count('_')) total_guesses = correct_guesses + len(game.incorrect_guesses) score = Score.query(ancestor=game.key).get() if score.points > 0 and total_guesses > 0: ranking = score.points / total_guesses + score.points total_rankings += ranking if total_rankings > 0: user.ranking = total_rankings / count user.put() users = User.query().order(-User.ranking) return UserForms(users=[user.to_form() for user in users])
def getCards(payload): username = payload['username'] gameId = payload['gameId'] games = Game.objects(gameID=gameId) dataA = [game.playerADataField for game in games] binDataA = dataA[0] dataB = [game.playerBDataField for game in games] binDataB = dataB[0] playerA = pickle.loads(binDataA) playerB = pickle.loads(binDataB) recipient_session_id = clients[username] if username == playerA.name: playerACards = playerA.cards playerACardsList = [] for card in playerACards: jsonStrA = json.dumps(card.__dict__) playerACardsList.append(jsonStrA) emit('assign cards', playerACardsList, room=recipient_session_id) print('playerA emitted') elif username == playerB.name: playerBCards = playerB.cards playerBCardsList = [] for card in playerBCards: jsonStrB = json.dumps(card.__dict__) playerBCardsList.append(jsonStrB) emit('assign cards', playerBCardsList, room=recipient_session_id) print('playerB emitted') else: print('Something is up.') print('it ran') print('username: '******'playerA: ' + playerA.name + 'playerB: ' + playerB.name)
def addGame(platform_id): checkIfUserLoggedIn() platform = session.query(Platform).filter_by(id=platform_id).one() if request.method == 'POST': input_date = request.form['release_date'].split('-') year = int(input_date[0]) month = int(input_date[1]) day = int(input_date[2]) release_date = datetime.date(year, month, day) newGame = Game(title=request.form['title'], developer=request.form['developer'], publisher=request.form['publisher'], release_date=release_date, platform_id=platform.id, user_id=platform.user_id, multiplayer=request.form['multiplayer'], multiplatform=request.form['multiplatform'], online_multiplayer=request.form['online_multiplayer']) session.add(newGame) session.commit() flash('New Game - %s Successfully Created' % (newGame.title)) return redirect(url_for('showPlatforms', platform_id=platform_id)) else: return render_template('addgame.html', platform_id=platform_id)
def new_game(self, request): """Creates new game""" user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') url = 'http://www.setgetgo.com/randomword/get.php' try: result = urlfetch.fetch(url) if result.status_code == 200: target = result.content target_list = {} for i in target: target_list[i] = False game = Game.new_game(user.key, request.attempts, target, target_list) except urlfetch.Error: logging.exception('Caught exception fetching url') # Use a task queue to update the average attempts remaining. # This operation is not needed to complete the creation of a new game # so it is performed out of sequence. taskqueue.add(url='/tasks/cache_average_attempts') return game.to_form('Good luck playing Hangman!')
def checkGameState(self, request): game_id = request.game_id game = Game.query(Game.game_id == game_id).get() if game == None: print("\n\n Game doesnt exist for ID: {0} \n\n".format(game_id)) return StringMessage( message="Game doesnt exist for ID: {0} ".format(game_id)) state = GuessANumberApi._check_game_state(game_id) if state == "no_more_moves": print("\n\n Game Ended, No Winners: {0} \n\n".format(game_id)) return StringMessage( message="Game Ended, No Winners: {0} ".format(game_id)) if state == "no_winners_yet": print("\n\n No Winners Yet, Game Continues: {0} \n\n".format( game_id)) return StringMessage( message="No Winners Yet, Game Continues: {0} ".format(game_id)) print("\n\n Game Won By: {0} \n\n".format(state)) return StringMessage(message="Game Won By: {0} ".format(state))
def new_game(self, request): """Creates new game""" if 1 > request.attempts or request.attempts > 14: raise endpoints.BadRequestException( 'Attempts should not be less than 1 or ' 'greater than 14!') user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( 'A User with that name does not exist!') try: target = self.pickaWord() game = Game.new_game(user.key, request.attempts, target[0], target[1], [ '{} created a new game'.format(user.name), ]) except: print 'mark 1: something wrong with creating a new game' # Use a task queue to update the average attempts remaining. # This operation is not needed to complete the creation of a new game # so it is performed out of sequence. taskqueue.add(url='/tasks/cache_average_attempts') return game.to_form('Good luck playing Hangman!')
def new_game(request): opponent = None if 'opponent' in request.GET: try: opponent = Player.objects.get( user__username=request.GET.get('opponent')) except: pass if opponent is None: opponent = random.choice( list( Player.objects.filter(logged_in=True).exclude( pk=request.player.pk))) if opponent is None: # no one is available to play, wait a while return HttpResponse(json.dumps({'status': 'Waiting for other players'})) sides = [request.player, opponent] #random.shuffle(sides) g = Game.start_new_game(*sides) for p in sides: p.update_play_time() return HttpResponseRedirect('/game/{}/'.format(g.id))
def test_add_Game3(self): with app.test_request_context(): game3 = Game(id=1000000, is_expansion=False, primary_name="game3", alt_names="alt_game3", image="www.test_image3.com", desc="This is a test game 3.", raw_desc="Test game 3", year=1980, min_players=10, max_players=15, rating=2.5) db.session.add(game3) db.session.commit() gamequery = db.session.query(Game).filter_by(id="1000000").first() self.assertEqual(gamequery.min_players, 10) self.assertEqual(gamequery.max_players, 15) self.assertEqual(gamequery.rating, 2.5) db.session.delete(game3) db.session.commit()
def get(): """Send a reminder email to the user who's turn it is for each game that is active. Called every hour using a cron job""" app_id = app_identity.get_application_id() # Get all in progress games games = Game.query(Game.game_over == False) for game in games: # Get first player or second player based on whos turn if game.whos_turn == 1: user = game.player_one.get() else: user = game.player_two.get() # If the user has an email send them a little reminder if user.email is not None: subject = 'Freaky TicTacToe Reminder' body = 'Hello {}, it is currently your turn in the game [ {} ]. Please return to the game.'\ .format(user.name, game.key.urlsafe()) mail.send_mail('noreply@{}.appspotmail.com'.format(app_id), user.email, subject, body)
class SendReminderEmail(webapp2.RequestHandler): """Send a reminder email to each User with an email who has games in progress. Email body includes a count of active games and their urlsafe keys Called every hour using a cron job""" users = User.query(User.email is not None) for user in users: games = Game.query(Game.user == user.key).\ filter(Game.game_over is False) if games.count() > 0: subject = 'This is a reminder!' body = 'Hello {}, you have {} games in progress. Their' \ ' keys are: {}'.\ format(user.name, games.count(), ', '.join(game.key.urlsafe() for game in games)) logging.debug(body) # This will send test emails, the arguments to send_mail are: # from, to, subject, body mail.send_mail( 'noreply@{}.appspotmail.com'.format( app_identity.get_application_id()), user.email, subject, body)
def create_game(): json_data = request.get_json() # Validate Input if not json_data: return jsonify({'message': 'No input data provided'}), 400 if 'game_id' in json_data and 'players' in json_data: game_id = json_data['game_id'] players = json_data['players'] if game_id in games: return jsonify({'message': 'Game with game id already exists.'}, 400) game = Game(game_id, players) games[game_id] = game result = game_schema.dump(game) return jsonify({'message': 'Created new game.', 'game': result}) else: return jsonify({ 'message': 'A game id and a list of player names must be provided to create a game.' }), 400