def get(self): self.check_user() # create new game and save game = games.Game() game.save() # redirect client to this new game return webapp2.redirect(game.get_url())
def run(): pygame.init() screen = pygame.display.set_mode(WINDOW_SIZE) engine.display_simple_message("Jumping Jack Python", duration=consts.SHORT_DISPLAY_DURATION) game = games.Game() while game.play_again: levels.introduce_level(game) level = levels.select_level(game) game = level.play() if game.status == game.QUIT: print("Bye") game.play_again = False game.status = None elif game.status == game.WIN: game.status = None elif game.status == game.LOSE: game.status = None if game.lives == 0: lose.display_lose_game(game) game.reset() else: lose.display_lose_level()
def get_nearest_game(new_game, knn_path, raw_data_file_path): ''' use the KNN model trained in 'knn_model.py' to find a suitable historical template for the new headline we will generate. new_game - Game object for which we wish to find a nearest historical game knn_path - string - location of the KNN model saved to file raw_data_file_path - string - location of the data file returns a Game object of the nearest historical game to new_game ''' #assemble a feature vector for the given game X_new = f.assemble_feature_vector(new_game) #load the KNN model trained by 'knn_model.py' headline_knn = joblib.load(knn_path) #find the most similar historical game and pull its game ID for future #reference prediction = headline_knn.predict(X_new) historical_id = int(prediction[0][1]) #load the historical game's data as a Game object and return it return g.Game(historical_id, df_path=raw_data_file_path), historical_id
def startClassic(): state = State() game = g.Game(state) state.game = game state.current = game if state.mainMenu.items[0].text != 'Resume': state.mainMenu.items.insert(0, m.MenuItem('Resume', resume))
def run(): pygame.init() screen = pygame.display.set_mode(WINDOW_SIZE) game = games.Game() game.won_levels += 1 level = levels.select_testlevel(game) game = level.play()
def getGames(self, trackedGames): # TODO this does not work any longer, we use regex now cur = self.conn.cursor() cur.execute( 'SELECT `MonitorID`, `Name`, `Process`, `Parameter`, `ProcessPath`, `IsRegex` FROM `monitorlist`') for row in cur: trackedGames[row["MonitorID"]] = games.Game( row["Name"], row["Process"], row["Parameter"], row["ProcessPath"], row["MonitorID"], row["IsRegex"]) cur.execute('SELECT `MonitorID`, `AbsoluteProcess`, `Start`, `End` FROM `sessions`') # get sessions for row in cur: if row["MonitorID"] in trackedGames: game = trackedGames[row["MonitorID"]] game.addSession(games.Session(game, datetime.datetime.fromtimestamp( row["Start"]), datetime.datetime.fromtimestamp(row["End"]), row["AbsoluteProcess"], )) else: logging.error("Game {} does not exist but has sessions".format(row["MonitorID"])) cur.close()
def set_game_status(self, status, map_id, clock_limit, score_limit): ''' Sets the current game status based on the given parameters. Args: status (string): The current status of the game. map_id (string): The unique identifier of the current map. clock_limit (integer): The maximum number of seconds unil game end. score_limit (integer): The maximum score until game end. Returns: game (Game): Returns the registered game model. ''' if not status or not map_id: return games.EMPTY game = None current_game = self.get_game() if (current_game == games.EMPTY or (current_game.valid and status == games.Game.STARTING)): # Create a new model when the game is starting game = games.Game(status, map_id, clock_limit, score_limit) self.games.append(game) self._log('Game started: %s %s' % (game.id, game.map_id)) else: game = self.get_game() if game.map_id != map_id: self._log('Game updated: %s %s' % (game.id, map_id)) # Update the game to reflect the new state game.status = status game.map_id = map_id game.clock_limit = clock_limit game.score_limit = score_limit # Update the id mapping for the game self.id_to_game[game.id] = game # Update the game status convenience flags game.starting = (status == games.Game.STARTING) game.playing = (status == games.Game.PLAYING) game.ending = (status == games.Game.ENDING) return game
def simulate(inning_to_start_at_second=None, n=1): """ Simulate a game provided an inning to start runners on 2nd base and the number of simulations desired""" outcomes = [] for _ in range(1, n + 1): cubs = teams.Team('Cubs') marlins = teams.Team('Marlins') g = games.Game(home_team=cubs, away_team=marlins, late_inning_base_change=inning_to_start_at_second) g.play_game() outcomes.append({ 'inning': g.inning, 'top_flag': not g.bottom_of_inning, 'home_team_runs': g.home_team.runs, 'away_team_runs': g.away_team.runs, 'total_runs': g.home_team.runs + g.away_team.runs }) return outcomes
def play_game(self, training_callback): """Play a game, calling training_callback every iteration. Returns a history of the game.""" game = games.Game(self.ale) while not game.game_over(): if ((random.uniform(0, 1) < self.compute_epsilon()) or (game.number_frames() < 4)): action = random.choice(range(self.number_of_actions)) print 'chose randomly', action, else: rewards = self.nnet.predict_rewards([game.last_state()]) action = np.argmax(rewards) print 'chose q-func ', action, 'based on rewards', rewards, self.frames_played += 1 game.move(action) print 'reward', game.rewards[-1] if (self.frames_played % self.minibatch_size) == 0: training_callback() return game
def checkData(): if check(mode1Var.get(), ['n', 'h', 'N', 'H', 'normal', 'hardcore'], "Invalid Mode 1", "Invalid Mode 1"): if check(mode2Var.get(), ['n', 's', 'N', 'S', 'normal', 'short'], "Invalid Mode 2", "Invalid Mode 2"): playing = 1 enterWindow.destroy() func.popup(func.root, "Pass Device", "Pass Device to %s\n\n" % name1Var.get(), \ 500, 500) global scrabble if name2Var.get() == "CPU": scrabble = games.GameWithCPU(name1Var.get(), mode1Var.get(), mode2Var.get()) else: scrabble = games.Game(name1Var.get(), name2Var.get(), mode1Var.get(), mode2Var.get()) scrabble.startGame() scrabble.main() playing = 0
def instruction_handler(self, instructions): if 'increment' in instructions[0]: self.reminder_counter[0] += 1 if 'ptoggle on' in instructions[0]: self.points_toggle = True if 'ptoggle off' in instructions[0]: self.points_toggle = False if instructions[1]['sendmsg'] is not None: self.send_message(instructions[1]['sendmsg']) if instructions[1]['sendwhisper'] is not None: self.whisper(instructions[1]['sendwhisper'][0], instructions[1]['sendwhisper'][1]) if instructions[1]['appendcooldown'] is not None: self.append_cooldown = instructions[1]['appendcooldown'] if instructions[1]['game_instruction'] == 'start': self.game = games.Game(instructions[1]['game_name']) self.active_game = True if instructions[1]['game_instruction'] == 'stop': self.active_game = False if instructions[1]['game_instruction'] == 'winner': self.game.winner(instructions[1]['game_instruction']) if instructions[1]['game_instruction'] == 'record': self.game.record() if 'shutdown' in instructions[0]: self.send_message(f'{config.exit_msg}') sys.exit() return
else: # print(jsonify({response}).get_json()) return jsonify(response) # return 'OK', 200 elif request.method == 'POST': print("POST REQUEST!") update_json = request.get_json() if update_json['action'] == "playCard": card_json = update_json['card'] print("Playing card = " + str(card_json)) if len(update_json) == 2: print("Playing normal card") game.setCurrentCard(card_json['id'], user) elif len(update_json) == 3: print("Playing wild card") game.setCurrentCard(card_json['id'], user, update_json['color']) game.nextPlayer() return 'OK', 200 elif update_json['action'] == "pickCard": print("Pick up Card request!") game.pickUpCard(user) game.nextPlayer() return 'OK', 200 if (__name__ == '__main__'): # sys.stdout = sys.stderr = open('server-log.txt', 'wt') app.config['TEMPLATES_AUTO_RELOAD'] = True game = Game.Game() app.run(host='0.0.0.0', port=80)
help= 'print the template headline and game ID along with the new headline') parser.add_argument('-m', '--model', help='filename of the trained KNN model to use') args = parser.parse_args() #take the given game ID and create a Game object for it if args.game_id == None: game_id = 401126819 else: game_id = args.game_id new_game = g.Game(game_id) #get the nearest game (as a Game object), according to the saved KNN model #and the saved data if args.model == None: knn_path = knn_model.knn_path else: knn_path = args.model raw_data_file_path = dataframe_builder.raw_data_file_path historical_game, historical_id = get_nearest_game(new_game, knn_path, raw_data_file_path) #create the headline for the new game by find/replacing names in the old #headline
def get(self): user = users.get_current_user() if user: if users.is_current_user_admin(): gameData = [{ 'id': 'fastgame', 'title': 'The Fast Game', 'description': 'A fast-paced tile game.', 'embedCode': '<embed src=\"/public/game_files/fastgame/fastgame.swf\" height=\"440\" width=\"440\" />', 'releaseDate': 'TBD', 'version': '1.0', 'status': 'Work-in-progress', 'credits': 'Created and programmed by <a href=\"/people#jfranzen\">Jack Franzen</a><br />Graphics by <a href=\"/people#jfranzen\">Jack Franzen</a> (with a few sprites from <a href=\"/people#deliasen\">Derek Eliasen</a>)' }, { 'id': 'icr', 'title': 'Inverse Cube Runner', 'description': 'The idea for <i>Inverse Cube Runner</i> came from playing <i>Cube Runner</i> and wondering how it would work as a competitive multiplayer game. Now you can control the ship or the cubes.', 'embedCode': '<applet code=\"/public/game_files/icr/Game.class\" width=\"600\" height=\"550\">You must have the latest version of Java installed to play this game.</applet>', 'releaseDate': 'February 15<sup>th</sup>, 2010', 'version': '5.1', 'status': '“Complete”', 'credits': 'Created and programmed by <a href=\"/people#zyaro\">Zachary Yaro</a>', 'changelog': ''' <ul> <li> (5.1) Made the line for placing cubes in inverted/2 player mode more fair to the flyer </li> <li> (5.1) Fixed flyer being drawn off-center </li> <li> (5.1) Fixed hitboxes not resizing when the game is not displayed in 800×600 </li> <li> (5.0) Made debug mode option available in the public version of the game </li> <li> (5.0) Made improvements to scaling so it can be displayed on screens with lower resolution (or for people with too many toolbars :P). </li> <li> Inverse Cube Runner released! </li> <li> (Dev) Fixed minor debug mode display glitch. </li> <li> (Dev) Added more music ("Star Fox: Space Armada") and edited the in-game versions of the background music so they loop better and have smaller file sizes. Also changed the way the game accesses the sound files. </li> <li> (Dev) Added more debug information. </li> <li> Fixed collision detection glitches with variable cube size. </li> <li> Modified program to work with different applet heights without much change in difficulty. </li> <li> Fixed two-player cube movement glitch. </li> <li> Changed movement so cubes move, not the player. </li> <li> Added shadow under flyer. </li> <li> (Dev) Changed "In-Game Speed Change" to "Debug Mode" and added debug mode features to make life easier for me. </li> <li> Added the "God Mode" option (and on/off buttons). </li> <li> Removed Inverted Productions logo from the title screen because of problems with the animation. </li> <li> Added the Inverted Productions logo to the title screen. </li> <li> (Dev) Added the "1-Player, Inverted" game mode button. Game mode does not exist and button does not do anything. </li> <li> (Dev) Added "In-Game Speed Control" on/off buttons to title screen. </li> <li> Randomizing of cube placement improved. </li> <li> Added buttons to title screen to control speed of cubes and game type (number of players, for now) </li> <li> (Dev) Added buttons to title screen to control music. </li> <li> (Dev) Added background music. </li> <li> Added support for ASDW. </li> <li> Fixed death graphic. </li> </ul> ''' }, { 'id': 'icrplus', 'title': 'Inverse Cube Runner Plus', 'description': '', 'embedCode': '<iframe src=\"/public/game_files/icrplus/icr.html\" style=\"width:640px;height:480px;\">Please switch to a browser that supports iframes.</iframe>', 'releaseDate': 'Not yet', 'version': '0.6 beta', 'status': 'Work-in-progress', 'credits': 'Created and programmed by <a href=\"/people#zyaro\">Zachary Yaro</a>' }, { 'id': 'imd', 'title': 'Inverse Missile Defense', 'description': '<i>Inverse Missile Defense</i> is like classic missile defense games, but now you must destroy the cities you used to defend.', 'embedCode': '<embed src=\"/public/game_files/imd/inv_missile_def.swf\" height=\"540\" width=\"960\" wmode=\"tranparent\" />', 'releaseDate': 'January 31<sup>th</sup>, 2011', 'version': '1.1 beta', 'status': 'Work-in-progress', 'credits': 'Created by Josh Nyden<br />Programmed by <a href=\"/people#zyaro\">Zachary Yaro</a><br />Graphics by Josh Nyden and <a href=\"/people#zyaro\">Zachary Yaro</a>', 'changelog': ''' 1.1 - more realistic missile physics - instructions built into game - tweaked missile accelerations and initial velocities - fixed missile spawn positions - fixed infinite star glitch 1.0 - first release ''' }, { 'id': 'lagrange', 'title': 'Lagrange', 'description': '', 'embedCode': '<applet code=\"/public/game_files/lagrange/Lagrange.class\" width=\"550\" height=\"500\">You must have the latest version of Java installed to play this game.</applet>', 'releaseDate': 'TBD', 'version': '1.2 alpha', 'status': 'Work-in-progress', 'credits': 'Created and programmed by <a href=\"/people#jfoxcanning\">Jamie Fox-Canning</a><br />Graphics by <a href=\"/people#jfoxcanning\">Jamie Fox-Canning</a>', }, { 'id': 'ltd', 'title': 'Legitimate Tower Defense', 'description': 'Our only “complete” game, Legitimate Tower Defense, a monument to everything but legitimate code, stands as a sellout game with outrageous amounts of advertising, lag, and fun!', 'embedCode': '<embed src=\"/public/game_files/ltd/ltd.swf\" height=\"660px\" width=\"480px\" wmode=\"tranparent\" />', 'releaseDate': 'April 16<sup>th</sup>, 2009', 'version': '2.3', 'status': '“Complete”', 'credits': 'Created by <a href=\"/people#jfranzen\">Jack Franzen</a><br />Programmed by James Bradbury and <a href=\"/people#jfranzen\">Jack Franzen</a><br />Graphics by <a href=\"/people#jfranzen\">Jack Franzen</a> and <a href=\"/people#zyaro\">Zachary Yaro</a> (with a few sprites from <a href=\"/people#deliasen\">Derek Eliasen</a> and <a href=\"/people#jrenner\">John Renner</a>)' }, { 'id': 'smtr', 'title': 'StickMan: The Reckoning', 'description': '<i>StickMan: The Reckining</i> is a nice little game that is similar to <i>Stick Arena</i> and <i>Stick RPG</i>. Eventually there will be online battles and a story mode. For now, just have fun shooting!', 'embedCode': '<embed src=\"/public/game_files/smtr/smtr.swf\" height=\"600px\" width=\"600px\" />', 'releaseDate': 'TBD', 'version': 'Pre-alpha', 'status': 'Shelved', 'credits': 'Created by <a href=\"/people#jfranzen\">Jack Franzen</a><br />Programmed by James Bradbury and <a href=\"/people#jfranzen\">Jack Franzen</a><br />Graphics by <a href=\"/people#deliasen\">Derek Eliasen</a>, <a href=\"/people#jfranzen\">Jack Franzen</a>, and <a href=\"/people#zyaro\">Zachary Yaro</a>', }, { 'id': 'tpg', 'title': 'The Two-Player Game', 'description': '<i>The Two-Player Game</i> is a set of minigames designed for two players. You can choose from categories like survival, player-vs.-player, and point games. You and another player then compete in several games until a winner is decided. Games will be added/updated over time.', 'embedCode': '<embed src=\"/public/game_files/tpg/tpg.swf\" width=\"550px\" height=\"400px\" />', 'releaseDate': 'TBD', 'version': 'Low effort demo', 'status': 'Shelved', 'credits': 'Created by <a href=\"/people#jfranzen\">Jack Franzen</a><br />Minigame design by <!--<a href=\"/people#deliasen\">Derek Eliasen</a>, --><a href=\"/people#jfranzen\">Jack Franzen</a><!--, John Renner, and Zachary Yaro -->', }] for game in gameData: gameEntry = games.Game.gql('WHERE id = :1', game['id']).get() if not gameEntry: gameEntry = games.Game() gameEntry.id = game['id'] for var in game: setattr(gameEntry, var, game[var]) gameEntry.put() template = JINJA_ENVIRONMENT.get_template('head.html') self.response.write(template.render({'title': 'Admin'})) self.response.write( '</head><body><div id=\"main\">Game data re-loaded.</div></body></html>' ) #template = JINJA_ENVIRONMENT.get_template('footer.html') #self.response.write(template.render(path, {})) else: self.redirect('/') else: self.redirect(users.create_login_url(self.request.uri))
def v007_to_v008(gdb_inp, ldb_inp): """ Converts """ gamelist = games.Games() gamelist.translate_json(json.dumps(gdb_inp)) out_games = {} out_local = {"game_data": {}, "emulators": {}} out_games["multipack"] = gdb_inp["multipack"] out_games["actions"] = gdb_inp["actions"] out_games["games"] = {} print("starting:", len(gdb_inp["games"])) ran = 0 collisions = 0 changed_keys = {} for key in gdb_inp["games"]: ran += 1 game = gdb_inp["games"][key] if not game["name"]: print("ERROR", key) continue new = copy.deepcopy(game) game = games.Game(**game) orig = game.dict() oldid = game.gameid game.generate_gameid() new["gameid"] = game.gameid changed_keys[oldid] = new["gameid"] cur_local = ldb_inp["game_data"].get(oldid, None) if game.gameid in out_games["games"]: collisions += 1 print("COLLISION:") print(new) print(out_games["games"][game.gameid]) out_games["games"][game.gameid] = new if cur_local: out_local["game_data"][game.gameid] = cur_local for key in out_games["games"]: game = out_games["games"][key] if not game["package_data"]: continue if game["package_data"]["type"] == "bundle": for child in game["package_data"]["contents"]: child["gameid"] = changed_keys[child["gameid"]] elif game["package_data"]["type"] == "content": parent = game["package_data"]["parent"] if parent["gameid"] in changed_keys: parent["gameid"] = changed_keys[parent["gameid"]] print("looped", ran, "times") print(len(out_games["games"]), len(gdb_inp["games"])) print(collisions, len(gdb_inp["games"]) - collisions) return out_games, out_local
def v006_to_v007(inp): """ Converts install_path to external local exe information "mother_1.0": { "gameid": "mother_1.0", "install_path": "C:\\emu\\gb\\mother12.gba", "lastplayed": "13:32:54 2015-01-19", "name": "Mother 1", "website": "", "sources": [ { "source": "gba" } ], }, >>> local_db = { "game_data":{ "mother_1.0":{ "files": [ {"type":"rom","primary":True,"path":"C:\\emu\\gb\\mother12.gba","source":"gba"} ] } }, "emulators":{ "gba":{ "path":"C:\\emu\\retroarch\\retroarch.exe", "cmd":"$program -c C:\\emu\\retroarch\\retroarch-gba.cfg $path" } } } """ gamelist = games.Games() gamelist.translate_json(json.dumps(inp)) out_games = {} out_local = {"game_data": {}, "emulators": {}} out_games["multipack"] = inp["multipack"] out_games["actions"] = inp["actions"] out_games["games"] = {} print("starting:", len(inp["games"])) ran = 0 for key in inp["games"]: ran += 1 game = inp["games"][key] if not game["name"]: print("ERROR", key) continue new = copy.deepcopy(game) game = games.Game(**game) if game.install_path: li = [] out_local["game_data"][game.gameid] = {"files": li} for s in game.sources: file = {"source": s, "primary": True} if s["source"] in ["gba", "snes", "n64", "nds"]: file.update({"type": "rom", "path": game.install_path}) else: file.update({"type": "exe", "path": game.install_path}) li.append(file) del new["install_path"] out_games["games"][game.gameid] = new print("looped", ran, "times") print(len(out_games["games"]), len(inp["games"])) return out_games, out_local
def v005_to_v006(inp): """ Games that are a package (is_package==True) will have: package_data: {"type":"bundle","contents":[(gameid,name) for all games in package]} Games that are in a package (is_package==False, but have package info elsewhere) package_data: {"type":"content","parent":[(gameid,name) for package],"source_info":{"gog_id","humble_package"}} source_info is just for auditing Games that are not a package, nor are they in a package (is_package==False, no other packaging keys), package_data: {} delete is_package identifyer (gotten with package_data) """ gamelist = games.Games() gamelist.translate_json(json.dumps(inp)) out = {} out["multipack"] = inp["multipack"] out["actions"] = [] out["games"] = {} print("starting:", len(inp["games"])) ran = 0 for key in inp["games"]: ran += 1 game = inp["games"][key] if not game["name"]: print("ERROR", key) continue new = copy.deepcopy(game) game = games.Game(**game) package = gamelist.get_package_for_game_converter(game) def get_source_info(source): if source["source"] == "gog": return { "package_source": "gog", "package_id": source["id"], "id_within_package": game.packageid } elif source["source"] == "humble": return { "package_source": "humble", "package_id": source["package"], "id_within_package": source["id"] } assert len(game.sources) == 1 if game.is_package: print("Converting package:", game.gameid) inside = game.games_for_pack_converter(gamelist) new["package_data"] = { "type": "bundle", "contents": [{ "gameid": g.gameid, "name": g.name } for g in inside], "source_info": get_source_info(game.sources[0]) } else: if package: print("Converting content item:", game.gameid) source_info = get_source_info(game.sources[0]) new["package_data"] = { "type": "content", "parent": { "gameid": package.gameid, "name": package.name }, "source_info": source_info } else: new["package_data"] = {} del new["is_package"] del new["packageid"] out["games"][game.gameid] = new print("looped", ran, "times") print(len(out["games"]), len(inp["games"])) return out
raw_data_file_path = 'raw_data.csv' if __name__ == '__main__': #give the file path of the text file containing the list of espn game ids. id_file_path = espn_id_finder.id_file_path #read the game ids from the text file. with open(id_file_path, 'r') as id_file: id_list = id_file.readlines() #initialize the pandas dataframe that will hold all the raw game data df = pd.DataFrame() #add raw game data row by row into the dataframe df for game_id in id_list: #a few game pages have variations in the standard html structure that #will not be parsed correctly by the BeautifulSoup code in the Game class. #A simple try catch handles these exceptions. try: game = g.Game(game_id) new_row = pd.DataFrame(game.to_dict(), index=[game_id]) df = df.append(new_row) except: print('missing data at game id ' + game_id) #export the dataframe containing raw game data to a csv file df.to_csv(raw_data_file_path)
''' raw_data_file_path = dataframe_builder.raw_data_file_path raw_data = pd.read_csv(raw_data_file_path, index_col = 0) id_list = raw_data.index ''' create the lists X and y for the feature vectors and labels respectively of the training set ''' X = [] y = [] for game_id in id_list: game = g.Game(game_id,df_path = raw_data_file_path) X.append(f.assemble_feature_vector(game)) y.append([game.headline, game_id]) ''' train the KNN model with K = 1 and a weighted Minkowski metric ''' #instatiate the transforms and estimator we will use vectorizer = DictVectorizer() standardizer = preprocessing.StandardScaler() knn = KNeighborsClassifier() '''