def game_new(request): if request.method.upper() not in ["POST"]: return HttpResponseBadRequest() num_players = request.POST.get("num_players", None) nick = request.POST.get("nick", None) if not num_players: return _json_error("'num_players' field is required.") if not nick: return _json_error("'nick' field is required.") game = Game(num_players=num_players) game.save() player = Player(nick=nick, secret=Player.generate_secret(), game=game) player.save() return _json_response({ "game": game.to_dict(), "player": player.to_dict(show_secret=True), "game_url": request.build_absolute_uri(reverse( "game-player-state", kwargs={"pk": game.pk, "secret": player.secret})), })
def setup_match(): #get games from mongodb games = mongo.db.AISinglePlayer game = Game() #Interesting safari test situation if '=' in game.gameID: game.gameID = game.gameID.replace('=', '') game.playerColor = 'white' #means black is AI color dictGame = game.__dict__ print(dictGame) games.insert(dictGame) return jsonify({'color': game.playerColor, 'id': game.gameID}), 201
def test_games_3(self): y = Year(2008) db.session.add(y) g = Game(1,"Fallout 3", rating = 87, release_year = 2008) y2 = Year(2004) db.session.add(y2) g2 = Game(2,"TES IV: Oblivion", rating = 100, release_year = 2004) db.session.add(g) db.session.add(g2) db.session.commit() q = Game.query.all() self.assertEqual(len(q), 2) db.session.remove()
def on_create_game(bot_id): bot = Bot.query.get(bot_id) game = Game(bot) db.session.add(game) db.session.commit() play_live_game_task.delay(game.id) return game.uuid
def test_games_2(self): y = Year(2008) db.session.add(y) g = Game(1, "Fallout 3", rating = 87, release_year = 2008) db.session.add(g) db.session.commit() self.assertTrue(g in db.session) # https://pythonhosted.org/Flask-Testing/ db.session.remove()
def test_games_1(self): y = Year(2008) db.session.add(y) g = Game(1, "Fallout 3", rating = 87, release_year = 2008) db.session.add(g) db.session.commit() q = Game.query.all() self.assertEqual(len(q), 1) db.session.remove()
def playMove(): '''contain:, x, y, id''' requestBody = json.loads(request.get_data()) print(requestBody) '''START OF VALIDITY CHECKS''' game = None rbid = requestBody['id'] #Safari issue fix if '=' in requestBody['id']: rbid = requestBody['id'].replace('=', '') #get data from mongodb games = mongo.db.AISinglePlayer gameDict = games.find_one({'gameID': rbid}) game = Game(gameDict) if not gameDict: return jsonify({'err_msg': 'No game found'}), 404 #Check if the board has a winner and return winner if game.gameOver: return jsonify({'err_msg': 'The game is over!'}), 401 '''END OF VALIDITY CHECKS ''' '''Add the move to the game board''' x = int(requestBody['x']) y = int(requestBody['y']) try: game.makeMove(x, y) except (ValidationFailed) as e: jsonify(e.body), e.status_code game.checkWinner('white') comp_row, comp_col = game.makeAIMove(x, y) game.checkWinner('black') winner = game.winner if game.winner is None: winner = '' #update the data in mongodb gameDictRes = game.__dict__ myquery = {'gameID': rbid} newvalues = {"$set": gameDictRes} games.update_one(myquery, newvalues) print(game.gameOver) return jsonify({ 'Computer_Move_Row': comp_row, 'Computer_Move_Col': comp_col, 'Winner': winner, 'GameOver': game.gameOver }), 201
def testAI(): game_test = Game() game_test.playerColor = 'white' board_test = [] for x in range(0, 19): board_test.append([''] * 19) game_test.board = board_test game_test.move = 4 board_test[0][0] = 'white' board_test[1][1] = 'white' board_test[2][2] = 'white' board_test[3][3] = 'white' ''' board_test[16][17] = 'black' board_test[15][18] = 'black' board_test[18][1] = 'black' board_test[18][2] = 'black' ''' game_test.board = board_test comp_row, comp_col = game_test.makeAIMove(5, 6) print(board_test) return jsonify({'comp_row': comp_row, 'comp_col': comp_col}), 200
u10.save() id=11 username='******' password='******' u = User.objects.filter(id=id) if u.exists(): u11 = u[0] print("El usuario con id = %d ya existe"%id) else: print("No existia un usuario con id = %d , creando..."%id) u11=User(id=id,password=password,username=username) u11.save() print("Asignando catUser a usuario...") g = Game(catUser = u10) g.save() print("Comprobando si existe algun juego sin raton") g1 = Game.objects.filter(mouseUser__isnull=True) if g1.exists(): g = g1[0] print("hay un juego con el usuario raton vacio") else: print("No hay un juego con el usuario raton vacio") g.mouseUser = u11 g.save() print("Ejecutando los movimientos pedidos...") m1 = Move(origin = 59, target = 52, game = g)
def db_import(): global year_cache global header db.drop_all() db.configure_mappers() db.create_all() game_cache = [g.game_id for g in Game.query.all()] platform_cache = [] # GAME DATA PULLING # data: id, name, release_date url = "https://www.igdb.com/api/v1/games" r = requests.get(url, params = header) j = r.json() # while len(j["games"]) > 0: while header["offset"] < 100: # pp = pprint.PrettyPrinter(indent = 4) # pp.pprint(j) games = j["games"] # loop through games for game in games: game_id = game["id"] if(game_id not in game_cache): game_cache += [game_id] name = game["name"] release_year = int((re.split("-", game["release_date"]))[0]) #check year cache before adding a new year if(release_year not in year_cache): y = Year(release_year) db.session.add(y) year_cache += [release_year] url_specific_game = "https://www.igdb.com/api/v1/games/" + str(game_id) r = requests.get(url_specific_game, params = header) #get specific game information game_info = r.json()["game"] #image image_url = None if("cover" in game_info and "url" in game_info["cover"]): image_url = "https:" + game_info["cover"]["url"] #rating rating = 0.0 if("rating" in game_info): rating = game_info["rating"] g = Game(id=game_id, name=name, image_url=image_url, rating=rating, release_year=release_year) #loop through platforms for v in game_info["release_dates"]: c = None platform = v["platform_name"] if platform not in platform_cache: platform_cache += [platform] c = Platform(platform) db.session.add(c) else: c = Platform.query.filter_by(platform_name = platform).first() g.associated_platforms.append(c) if "genres" not in game_info: continue add_genres(game_info["genres"], g) add_companies(game_info["companies"], g) #add game db.session.add(g) db.session.commit() r = requests.get(url, params = header) j = r.json() header["offset"] += 25
if u.exists(): u11 = User.objects.get(id=id) else: u11 = User(id=id, username=username, password=password) u11.save() #Cree un juego asignado al usuario con id=10. El id correspondiente al segundo #usuario sera NULL. Si os hiciera falta en el futuro, el id del nuevo juego se #puede obtener como nombre_objeto_juego.id tras persistir el objeto de tipo juego (o equivalente). id=1 catUser=u10 g = Game.objects.filter(catUser=u10) if g.exists(): g1 = g[0] else: g1 = Game(id=id, catUser=catUser) g1.save() #Busque un juego con un solo usuario asignado. Para ellos se puede usar la funcion #filter con argumento (nombreUser2__isnull=True) donde nombreUSer2 es el atributo #del nombre de usuario del segundo usuario #El usuario con id=11 se une al juego encontrado en el paso anterior. Para hacer #un update de un objeto solo teneis que asignarle los nuevo valores y guardarlo (save()) g = Game.objects.filter(mouseUser__isnull=True) if g.exists(): g1 = g[0] g1.mouseUser=u11 g1.save() else: print("No existen juegos sin raton")
def create_game(request): game = Game (catUser=request.user) game.save() request.session["gameID"] = game.id
if u2.exists(): u11 = u2[0] print "El usuario con id=11 ya existe, obtenida su instancia" else : u11 = User ( id=11 , username = '******', password= '******') u11.save() print "Creado usuario con id=11" #Busca si hay algun juego con car id 10 y sin mouse, y sino lo crea print "Buscamos juegos con el usuario10 como gato y sin raton" g = Game.objects.filter(catUser=u10) if g.exists(): game = g[0] print "Obtenido la instancia del juego gato=usuario10 y sin raton" else : game = Game (catUser=u10) game.save() print "El usuario 10 no tiene ningun juego com gato y sin raton. Lo hemos creado" #Busca un juego sin mouse, y si hay pone como mouse id 10 print "Buscamos juegos sin raton" g2 = Game.objects.filter(mouseUser__isnull=True) if g2.exists(): game = g2[0] game.mouseUser= u11 game.save() print "Encontrado juego sin raton, unimos al usuario 11 como raton" #movimiento por user 10 de 2 a 11 m1 = Move(origin=2, target=11, game=game) game.cat2 = 11;