def app(): shape = ( translate( rotate( layers([ rectangle(-1, -1, 2, 2, yellow), point(0, 6, red), point(6, 0, red), point(0, -6, red), point(-6, 0, red), line(-6, 0, 12, 0, 2, sky_blue), line(0, -6, 0, 12, 1, blue) ]), lambda st: st.rot ), 6, 6 ) ) scene = compose( rotate( follow( tile(shape, 12, 12), lambda st: st.drift_displacement ), lambda st: st.scene_rot ), background ) game.run(scene, update, init_state)
def runGames(layout, pacman, ghosts, display, numGames, record, limMoves, numTraining=0, catchExceptions=False, timeout=30): import __main__ __main__.__dict__['_display'] = display rules = ClassicGameRules(timeout) # Criado com um determinado timeout games = [] namePac = "Pac" + pacman.myName() nameGhost = "Fant" + ghosts[0].myName() for i in range(numGames): beQuiet = i < numTraining if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: gameDisplay = display rules.quiet = False game = rules.newGame(layout, pacman, ghosts, gameDisplay, beQuiet, limMoves, catchExceptions) #Novo jogo criado game.run(limMoves) if not beQuiet: games.append(game) # save the game please in a file, only the action I presume... if record: import time import pickle fname = ('./results/recorded-game-'+namePac+'-'+nameGhost+'-%d-' % (i + 1)) + \ '-'.join([str(t) for t in time.localtime()[1:6]]) ffname = ('./results/recorded-game-' + namePac + nameGhost + "-" + str(i + 1) + '-').join( [str(t) for t in time.localtime()[1:6]]) #print(fname) f = open(fname, 'bw') components = {'layout': layout, 'actions': game.moveHistory} pickle.dump(components, f) f.close() if (numGames - numTraining) > 0: scores = [game.state.getScore() for game in games] wins = [game.state.isWin() for game in games] winRate = wins.count(True) / float(len(wins)) print('Average Score:', sum(scores) / float(len(scores))) print('Scores: ', ', '.join([str(score) for score in scores])) print('Win Rate: %d/%d (%.2f)' % (wins.count(True), len(wins), winRate)) print('Record: ', ', '.join([['Loss', 'Win'][int(w)] for w in wins])) return games
def loadGame(): loadState1 = pygame.transform.scale2x( pygame.image.load( os.path.join('UI' + '\\' + 'main menu' + '\\' + 'loadState1.png')).convert_alpha()) loadState2 = pygame.transform.scale2x( pygame.image.load( os.path.join('UI' + '\\' + 'main menu' + '\\' + 'loadState2.png')).convert_alpha()) loadRect = pygame.rect.Rect(34 * 2, 74 * 2, 100 * 2, 36 * 2) if loadRect.collidepoint(mousePosition): screen.blit(loadState2, loadRect) pygame.display.update(loadRect) if mouseClick[0] == True: if os.path.exists(os.path.join('saves' + '\\' + 'savefile.txt')) == False: pass else: pygame.mixer.music.load( os.path.join('Music' '\\' 'FINAL_2.wav')) pygame.mixer.music.play(-1, 0.0) import game game.run() else: screen.blit(loadState1, loadRect) pygame.display.update(loadRect)
def main(self): self.Button1 = Buttons.Button() self.Button2 = Buttons.Button() self.Button3 = Buttons.Button() self.Button4 = Buttons.Button() self.Button5 = Buttons.Button() self.display() ############################################################### # Yifan Leng wrote the following part while True: self.update_display() for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: if self.Button1.pressed(pygame.mouse.get_pos()): import tp_staff tp_staff.run() elif self.Button2.pressed(pygame.mouse.get_pos()): import record record.run() elif self.Button3.pressed(pygame.mouse.get_pos()): import visualize_the_record visualize_the_record.run() elif self.Button4.pressed(pygame.mouse.get_pos()): import game import choose_music song = choose_music.run() game.run(song) elif self.Button5.pressed(pygame.mouse.get_pos()): import instruction_page instruction_page.run()
def main(): viewPort = viewport.ViewPort(WINWIDTH, WINHEIGHT, topLeft=Point(400, 80)) game = CandySeller(viewPort) while True: game.run() # Re-initialised the game state. game.reset()
def main(): viewPort = viewport.ViewPort(WINWIDTH, WINHEIGHT) game = SheriffQuest(viewPort) while True: game.run() # Re-initialised the game state. game.reset()
def main(): # initialise pygame here so all modules # have instant access to pygame functions pygame.init() render.init() import game game.init() game.run()
def main(): """ Main function, this is what runs the game. """ options.parseOptions() game.loadFiles() game.intro() game.run()
def main(display): running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.event.post(pygame.Event(pygame.QUIT)) running = not running elif event.type == pygame.KEYUP and event.key == pygame.K_RETURN: game.run(display)
def main(): print("Starting Jimmy Pixel...") viewPort = viewport.ViewPort(WINWIDTH, WINHEIGHT, topLeft=Point(400, 80)) game = JimmyPixel(viewPort) print("Created Jimmy Pixel game...") while True: game.run() # Re-initialised the game state. game.reset()
def runGames(layout, pacman, ghosts, display, numGames, record, numTraining=0, catchExceptions=False, timeout=30): import __main__ __main__.__dict__['_display'] = display rules = ClassicGameRules(timeout) games = [] for i in range(numGames): beQuiet = i < numTraining if beQuiet: # Suppress output and graphics import textDisplay gameDisplay = textDisplay.NullGraphics() rules.quiet = True else: gameDisplay = display rules.quiet = False game = rules.newGame(layout, pacman, ghosts, gameDisplay, beQuiet, catchExceptions) game.run() if not beQuiet: games.append(game) if record: import time import cPickle fname = ('recorded-game-%d' % (i + 1)) + \ '-'.join([str(t) for t in time.localtime()[1:6]]) f = file(fname, 'w') components = {'layout': layout, 'actions': game.moveHistory} cPickle.dump(components, f) f.close() if (numGames - numTraining) > 0: scores = [game.state.getScore() for game in games] wins = [game.state.isWin() for game in games] winRate = wins.count(True) / float(len(wins)) print 'Average Score:', sum(scores) / float(len(scores)) print 'Scores: ', ', '.join([str(score) for score in scores]) print 'Win Rate: %d/%d (%.2f)' % (wins.count(True), len(wins), winRate) print 'Record: ', ', '.join([['Loss', 'Win'][int(w)] for w in wins]) return games
def main(): # Ask variables global DEBUG global COMONLY #DEBUG = True #COMONLY = True if input("Start in debug mode? ") in ("n", "N", "no"): DEBUG = False if input("Let the computer play against itself? ") in ("n", "N", "no"): COMONLY = False if COMONLY: if input("Run some test games? ") in ("n", "N", "no"): tests = False else: tests = True else: tests = False # Set ui if tests: ui = UiMinimal(test=True) else: ui = GuiTurtle() #ui = GuiNN() # Run ui intro if not DEBUG: ui.intro() # Run tests/game if tests: test(ui) else: if COMONLY: players = [dict_ai["com"](i) for i in range(4)] else: players = ui.ask_players(dict_ai) #number_players = ui.ask_number_players() #players = [] #for n in range(number_players): #AIClass = ui.ask_player_type(n, dict_ai) #players.append(AIClass(n)) run(ui, players) # Exit input("Hesperus terminated successfully! (Press enter to exit)")
def main(window): renderer.initialize() curses.curs_set(0) dimens = window.getmaxyx() main_window = window.subwin(22, 20, dimens[0] // 2 - 11, dimens[1] // 2 - 10) main_window.nodelay(1) main_window.keypad(1) game.init() game.add_state_and_switch("main_menu", MainMenuState(main_window)) game.add_state("paused", PauseState(main_window)) game.add_state("game", GameState(main_window)) game.run()
def test(ui, players=None): # Initiate players if players is None: #players = [AICom(i) for i in range(4)] players = [AIIndie(i) for i in range(4)] # Number of games try: n = int(input("Number of tests? ")) except: n = 100 # Simulate games list_turns = [] list_time = [] for i in range(n): turn, total_time = run(ui, players) list_turns.append(turn) list_time.append(total_time) print(f"Total time of game {i}: {round(total_time,3)},", end=" ") print(f"Number of rounds: {turn/4}") #if i == 0: #list_times.pop() # Calculate stats time_mu, time_sigma, time_rel = round_list(mu_sigma_rel(list_time)) turns_mu, turns_sigma, turns_rel = round_list(mu_sigma_rel(list_turns)) #cov_time_turns = sum([(list_time[i]-time_mu) * (list_turns[i] - turns_mu) for i in range(n)])/n #corr_time_turns = cov_time_turns/ (time_sigma * turns_sigma) corr_time_turns = corr(list_time, time_mu, time_sigma, list_turns, turns_mu, turns_sigma) corr_time_turns = round(corr_time_turns, 3) # Print stats print_mu_sigma_rel("time per game", time_mu, time_sigma, time_rel) print_mu_sigma_rel("turns per game", turns_mu, turns_sigma, turns_rel) print(f"Correlation between time and number of turns: {corr_time_turns}.") #counter_times = Counter([bucket(time_) for time_ in list_times]) #plt.bar([x for x in growths.keys()], [g/size for g in growths.values()], bar_width) time_dict = {(i / 10): 0 for i in range(51)} for time_ in list_time: time_dict[bucket_time(time_)] += 1 plt.bar(list(time_dict.keys()), list(time_dict.values()), 0.08) plt.title("Verteilung der Spieldauer") plt.show() turns_dict = {(5 * i): 0 for i in range(12, 41)} for turns in list_turns: turns_dict[bucket_turns(turns)] += 1 plt.bar(list(turns_dict.keys()), list(turns_dict.values()), 4) plt.title("Verteilung der Zugzahl") plt.show() plt.scatter(list_time, list_turns) plt.title("Verhaeltnis von Zugzahl und Spieldauer") plt.show()
def run_app(): """Initialize and start the app.""" # Create shader for scene background = game.rectangle(0, 0, WIDTH, HEIGHT, sky_blue) scene = game.compose(bug, background) # Initial position of the bug init_state = { "x": WIDTH / 2, # note: these coordinates will not necessarily be whole numbers "y": HEIGHT / 2 } # Let's go! game.run(scene, update, init_state)
def newGame(): newState1 = pygame.transform.scale2x(pygame.image.load(os.path.join('UI' + '\\' + 'main menu' + '\\' + 'newState1.png')).convert_alpha()) newState2 = pygame.transform.scale2x(pygame.image.load(os.path.join('UI' + '\\' + 'main menu' + '\\' + 'newState2.png')).convert_alpha()) newRect = pygame.rect.Rect(34*2, 114*2, 100*2, 36*2) if newRect.collidepoint(mousePosition): screen.blit(newState2, newRect) pygame.display.update(newRect) if mouseClick[0] == True: pygame.mixer.music.load(os.path.join('Music' '\\' 'FINAL_2.wav')) pygame.mixer.music.play(-1, 0.0) import save save.newgame() import game game.run() else: screen.blit(newState1, newRect) pygame.display.update(newRect)
def run(): wrap_problems() output = {} for problem in get_problems(): output[problem.__name__] = {} try: output[problem.__name__]['result'] = problem() output[problem.__name__]['error'] = None output[problem.__name__]['locals'] = problem.locals except Exception as ex: output[problem.__name__]['result'] = None output[problem.__name__]['locals'] = None output[problem.__name__]['error'] = ex output[problem.__name__]['feedback'] = feedback.feedback(problem, output[problem.__name__]) show_problem(problem, output[problem.__name__]) import game game.run(output)
class Main(): """boucle principale du programme""" pygame.init() fenetre = pygame.display.set_mode((1920, 1080)) ##, pygame.FULLSCREEN) game = 0 r = "startmenu" while r != "stop": if r == "start": game = Game(fenetre, "tower") game.respawn() r = game.run() elif r == "startmenu": startmenu = StartMenu(fenetre) r = startmenu.run() elif r == "respawn": game.respawn() r = game.run() pygame.quit()
def loadGame(): loadState1 = pygame.transform.scale2x(pygame.image.load(os.path.join('UI' + '\\' + 'main menu' + '\\' + 'loadState1.png')).convert_alpha()) loadState2 = pygame.transform.scale2x(pygame.image.load(os.path.join('UI' + '\\' + 'main menu' + '\\' + 'loadState2.png')).convert_alpha()) loadRect = pygame.rect.Rect(34*2, 74*2, 100*2, 36*2) if loadRect.collidepoint(mousePosition): screen.blit(loadState2, loadRect) pygame.display.update(loadRect) if mouseClick[0] == True: if os.path.exists(os.path.join('saves' + '\\' + 'savefile.txt')) == False: pass else: pygame.mixer.music.load(os.path.join('Music' '\\' 'FINAL_2.wav')) pygame.mixer.music.play(-1, 0.0) import game game.run() else: screen.blit(loadState1, loadRect) pygame.display.update(loadRect)
def testQtrackWins(trainer, player2, reward): wins_overall = [] ties_overall = [] w, t = testQAgents(ComboLearner(reward_fun=reward, epsilon=0.25), trainer, 1) # play specified number of games, tracking wins for rnd in range(20): game_results = [] wins = [] # define player player1 = ComboLearner(reward_fun=reward, epsilon=0, loadfile='test_player1.csv', learning_mode=False) # run 100 test games for i in range(100): game = Game.setup([player1, player2], variable_cards) final_game, results = game.run() game_results.append(results) if isinstance(player1, ComboLearner): player1.terminal_val(final_game) if isinstance(player2, ComboLearner): player2.terminal_val(final_game) if results[0][0].name == player1.name: score1 = results[0][1] score2 = results[1][1] else: score1 = results[1][1] score2 = results[0][1] # 1 if player 1 wins, 0 if loss, None if tie if score1 > score2: wins.append(1.0) elif score2 > score1: wins.append(0.0) else: wins.append(None) # get winning percentage for this round wins_no_ties = filter(lambda x: x is not None, wins) win_rate = float(sum(wins_no_ties)) / len(wins) tie_rate = float(100 - len(wins_no_ties)) / len(wins) wins_overall.append(win_rate) ties_overall.append(tie_rate) # train one more iteration testQAgents(ComboLearner(reward_fun=reward, epsilon=0.25, loadfile='test_player1.csv'), trainer, 1) print(wins_overall) print(ties_overall) return wins_overall, ties_overall
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--algo", help= "the training algorithm, sarsa for SARSA and qlearning for Q-learning") args = parser.parse_args() if args.algo == "sarsa": algo = train.SARSA print "Training using SARSA algorithm" else: algo = train.QLearning print "Training using Q-learning algorithm" circle = tictactoe.ActionValueFunc(tictactoe.PlayerCircle) cross = tictactoe.ActionValueFunc(tictactoe.PlayerCross) train.run(algo, circle, cross) print "Training completed, game starting..." while True: user = raw_input("Please choose a player, O or X: ") if user == "X" or user == "x": user = tictactoe.PlayerCross opponent = circle print "You are player X" else: user = tictactoe.PlayerCircle opponent = cross print "You are player O" opponentFirst = True yn = raw_input( "Do you want to go first? Y for yes, N for no, others for either way: " ) if yn == "Y" or yn == "y": opponentFirst = False elif yn == "N" or yn == "n": opponentFirst = True else: if random.random() < 0.5: opponentFirst = False game.run(user, opponent, opponentFirst)
def askTrain(): loa.load_scores() training = input( co.b + 'What would you like to train on?\nAttack - 1\nDefense - 2\nDodge - 3\nSpeed - 4\nStamina - 5\nSee High Scores - 6\nReturn to the Training Center - 7\n >>> ' ) if training == '1': c() attackAsk() elif training == '2': c() defenseAsk() elif training == '3': c() dodgeAsk() elif training == '4': c() speedAsk() elif training == '5': c() staminaAsk() elif training == '6': print('Attack game high score - ' + str(cl.highScores.attack)) print('Defense game high score - ' + str(cl.highScores.defense)) print('Dodge game high score - ' + str(cl.highScores.dodge)) print('Speed game high score - ' + str(cl.highScores.speed)) print('Stamina game high score - ' + str(cl.highScores.stamina)) input('---Press Enter to Continue---') c() elif training == '7': print('Returning to the training center.') s(2) c() game.run() else: print(co.y + 'Please answer with a 1, 2, 3, 4, or a 5.') s(2) c() lvlSys.lvlCheck()
def main(): parser = argparse.ArgumentParser() parser.add_argument("--algo", help="the training algorithm, sarsa for SARSA and qlearning for Q-learning") args = parser.parse_args() if args.algo == "sarsa": algo = train.SARSA print "Training using SARSA algorithm" else: algo = train.QLearning print "Training using Q-learning algorithm" circle = tictactoe.ActionValueFunc(tictactoe.PlayerCircle) cross = tictactoe.ActionValueFunc(tictactoe.PlayerCross) train.run(algo, circle, cross) print "Training completed, game starting..." while True: user = raw_input("Please choose a player, O or X: ") if user == "X" or user == "x": user = tictactoe.PlayerCross opponent = circle print "You are player X" else: user = tictactoe.PlayerCircle opponent = cross print "You are player O" opponentFirst = True yn = raw_input("Do you want to go first? Y for yes, N for no, others for either way: ") if yn == "Y" or yn == "y": opponentFirst = False elif yn == "N" or yn == "n": opponentFirst = True else: if random.random() < 0.5: opponentFirst = False game.run(user, opponent, opponentFirst)
def newGame(): newState1 = pygame.transform.scale2x( pygame.image.load( os.path.join('UI' + '\\' + 'main menu' + '\\' + 'newState1.png')).convert_alpha()) newState2 = pygame.transform.scale2x( pygame.image.load( os.path.join('UI' + '\\' + 'main menu' + '\\' + 'newState2.png')).convert_alpha()) newRect = pygame.rect.Rect(34 * 2, 114 * 2, 100 * 2, 36 * 2) if newRect.collidepoint(mousePosition): screen.blit(newState2, newRect) pygame.display.update(newRect) if mouseClick[0] == True: pygame.mixer.music.load(os.path.join('Music' '\\' 'FINAL_2.wav')) pygame.mixer.music.play(-1, 0.0) import save save.newgame() import game game.run() else: screen.blit(newState1, newRect) pygame.display.update(newRect)
def app(): # Create the marker red_dot = game.point(0, 0, red) marker = game.follow(red_dot, "marker_position") # Create the cursor black_dot = game.follow(game.point(0, 0, black), "cursor_position") horiz_line = game.follow(game.line(0, 0, WIDTH, 0, 1, grey), "cursor_position", axis='y', force_tuple=True) vert_line = game.follow(game.line(0, 0, 0, HEIGHT, 1, grey), "cursor_position", axis='x', force_tuple=True) crosshair = game.compose(horiz_line, vert_line) cursor = game.compose(black_dot, crosshair) # Build the scene scene = game.compose(marker, cursor) # Run the app game.run(scene, update, init_state)
def handle_main_menu(): img = tcod.image_load(b"menu_background.png") while not tcod.console_is_window_closed(): # show the background image, at twice the regular console resolution tcod.image_blit_2x(img, 0, 0, 0) # show the game's title, and some credits! tcod.console_set_default_foreground(0, tcod.white) tcod.console_print_ex( 0, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 4, tcod.BKGND_NONE, tcod.CENTER, bytes(GAME_NAME, "utf-8") ) tcod.console_print_ex( 0, SCREEN_WIDTH // 2, SCREEN_HEIGHT - 2, tcod.BKGND_NONE, tcod.CENTER, b"By Matthew Pfeiffer ([email protected])", ) # show options and wait for the player's choice choice = menu("", ["Play a new game", "Continue last game", "Quit"], 24) if choice == 0: # new game game.new_game() game.run() elif choice == 1: # load last game try: save.load_game() except: msgbox("\n No saved game to load.\n", 24) continue game.run() elif choice == 2 or choice == "escape": # quit break
def play(self, grid): moves = game.possibleMoves(grid) i = 0 scores = [0] * 4 while i < self.max_iter: for move in moves: new_grid = game.copy_grid(grid) game.next(new_grid, move) scores[move] += game.run(new_grid, self.dummy) i += 1 max_score = 0 best_move = 0 for move, score in enumerate(scores): if score > max_score: max_score = score best_move = move return best_move
def testQAgents(player1, player2, iterations): game_results = [] wins = [] # play specified number of games for i in range(iterations): game = Game.setup([player1, player2], variable_cards) final_game, results = game.run() game_results.append(results) if isinstance(player1, ComboLearner): player1.terminal_val(final_game) player1.saveweights("test_player1.csv") if isinstance(player2, ComboLearner): player2.terminal_val(final_game) player2.saveweights("test_player2.csv") if results[0][0].name == player1.name: score1 = results[0][1] score2 = results[1][1] else: score1 = results[1][1] score2 = results[0][1] # 1 if player 1 wins, 0 if loss, None if tie if score1 > score2: wins.append(1.0) elif score2 > score1: wins.append(0.0) else: wins.append(None) # return winning percentage wins_no_ties = filter(lambda x: x is not None, wins) win_rate = float(sum(wins_no_ties)) / len(wins) tie_rate = float(iterations - len(wins_no_ties)) / len(wins) # print(game_results) print("WIN RATE: " + str(win_rate)) print("TIE RATE: " + str(tie_rate)) print("LOSE RATE: " + str(1.0-tie_rate-win_rate)) # print(wins) return win_rate, tie_rate
def run(window_size, old_window): scroll = 0 offset = [0, window_size[1]] init() screen = display.set_mode(window_size, RESIZABLE) test_font = font.SysFont('arial', 100) clock = time.Clock() def resize(window, window_size): new = gfunc.event_loop() if new: window = display.set_mode(new, RESIZABLE) scale = min(new) return window, new, scale else: return window, window_size, min(window_size) def level_button(number, window, window_size, window_scale, pos, valid, show=True): height = window_scale * 0.15 if valid: if gfunc.text_button(window, window_size, (0, 0), str(number), (255, 255, 255), (pos[0], pos[1], height, height), alignment='center'): return True else: gfunc.text_button(window, window_size, (0, 0), str(number), (150, 150, 150), (pos[0], pos[1], height, height), alignment='center') # file = open('levels.txt', 'r') # for line in file: # print(line) # example_dict = {1: "6", 2: "2", 3: "f"} # # pickle_out = open("dict.pickle", "wb") # pickle.dump(example_dict, pickle_out) # pickle_out.close() level_info = pickle.load(open('levels', 'rb')) level_info[3] = { 'background': (126, 200, 80), 'grid_size': (16, 7), 'start_money': 1120, 'enemies': [[('boss', 1, 2, 1, 1, 0.5), ('walker', 1, 4, 20, 0.5, 0.4), ('giant', 1, 2, 1, 1, 0.5)], [('sprinter', 1, 6, 30, 1, 0.2), ('sprinter', 1, 6, 20, 1, 0.2), ('giant', 1, 2, 2, 1, 0.5)], [('walker', 1, 4, 25, 0.5, 0.4), ('walker', 1, 4.5, 15, 0.5, 0.35), ('walker', 1, 5, 15, 0.5, 0.3), ('walker', 1, 5.5, 15, 0.5, 0.25), ('walker', 1, 6, 15, 0.5, 0.2), ('sprinter', 1, 6, 20, 1, 0.15), ('sprinter', 1, 10, 200, 1, 0.15), ('giant', 1, 2, 5, 1, 0.5)], [('boss', 1, 2, 1, 1, 0.5)]] } levels = len(level_info) outfile = open('levels', 'wb') pickle.dump(level_info, outfile) outfile.close() # print(level_info) max_columns = 5 # User data user_data = pickle.load(open('user_data', 'rb')) while True: screen, window_size, window_scale = resize(screen, window_size) window = Surface(window_size) window.fill((130, 130, 130)) dt = clock.tick() / 1000 x_dist = window_size[0] / (min(max_columns, levels) + 1) rows = math.ceil(levels / max_columns) if rows > 0: y_dist = window_size[1] / (rows + 1) else: y_dist = 0 y_dist = max(y_dist, window_scale * 0.2) # Scroll mouse_pos = mouse.get_pos() s = 200 if mouse_pos[1] >= window_size[1] * 0.8: scroll += s * dt if mouse_pos[1] <= window_size[1] * 0.2: scroll -= s * dt max_s = 0.15 * window_scale + y_dist * (rows - 5) scroll = max(0, scroll) scroll = min(max_s, scroll) if rows < 5: scroll = 0 offset[1] -= dt * offset[1] * 5 offset[1] = max(0, offset[1]) # So it does stop if offset[1] < 1: offset[1] = 0 mouse_extras.update_buttons() mouse_extras.update_states() screen.blit(transform.scale(old_window, window_size), (0, 0)) # draw.rect(screen, (120, 120, 120), (0, offset[1] - 10, window_size[0], window_size[1])) k = key.get_pressed() button_pressed = None ret = None for level_num in range(levels): y = int(level_num / max_columns) x = level_num - y * max_columns x += 1 y += 1 x *= x_dist if y_dist == 0: y += window_size[1] / 2 else: y *= y_dist y -= scroll level_num += 1 valid = user_data['level'] + 1 >= level_num if level_button(level_num, window, window_size, window_scale, (x, y), valid): button_pressed = level_num if button_pressed: val, surf = game.run(button_pressed, levels, window_size, window) user_data = pickle.load(open('user_data', 'rb')) rect = surf.get_rect() window_size = rect.width, rect.height screen = display.set_mode(window_size, RESIZABLE) if type(val) == int: game.run(val, levels, window_size, surf) user_data = pickle.load(open('user_data', 'rb')) continue while True: if type(ret) == int: ret, new_window = game.run(button_pressed + 1, levels, window_size, new_window) user_data = pickle.load(open('user_data', 'rb')) rect = new_window.get_rect() window_size = rect.width, rect.height else: break if k[K_ESCAPE]: return screen if k[K_F2]: gfunc.show_fps(window) screen.blit(window, offset) display.update()
def get_pos(self): return self.game_object.pos def set_pos(self, pos): self.game_object.pos = pos def get_size(self): return self.game_object.size def set_size(self, size): self.game_object.size = size pos = property(get_pos, set_pos) size = property(get_size, set_size) def update(self): pass def pre_update(self): pass def post_update(self): pass def render(self): pass if __name__ == "__main__": game.run()
def main(): #Parsing level from parameters and parsing main config: level_name = None world_index = 0 world = World(WORLDS[world_index]) user_supplied_level = False parse_config() getlevel = False Variables.vdict["devmode"] = False if len(sys.argv) > 1: for arg in sys.argv: if getlevel: try: level_name = arg user_supplied_level = True end_trigger = END_NEXT_LEVEL menu_choice = MENU_QUIT except: error_message("Incorrect command line parameters") level_name = None elif arg == "-l": getlevel = True elif arg == "-dev": Variables.vdict["devmode"] = True Variables.vdict["verbose"] = True elif arg == "-v": Variables.vdict["verbose"] = True #Initializing pygame and screen pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) caption = "Which way is up?" if (Variables.vdict["devmode"]): caption = caption + " - developer mode" pygame.display.set_caption(caption) apply_fullscreen_setting(screen) if (pygame.joystick.get_count() > 0): joystick = pygame.joystick.Joystick(0) joystick.init() else: joystick = None score = Score(0) done = False if not user_supplied_level: if (Variables.vdict["unlocked" + WORLDS[0]] == 0): # Nothing unlocked, go straight to the game end_trigger = END_NEXT_LEVEL menu_choice = MENU_QUIT level_name = world.get_level() else: # Go to the menu first end_trigger = END_MENU menu_choice = 0 bgscreen = None #Menu and level changing loop, actual game code is in game.py: while not done: if end_trigger == END_NEXT_LEVEL: if user_supplied_level: end_trigger = game.run(screen, level_name, world.index, score, joystick) if end_trigger == END_NEXT_LEVEL: user_supplied_level = False end_trigger = END_WIN else: end_trigger = game.run(screen, level_name, world.index, score, joystick) if end_trigger == END_NEXT_LEVEL: if world.is_next_level(): level_name = world.get_level() else: end_trigger = END_WIN elif end_trigger == END_QUIT: display_bg("quit", screen) end_trigger = END_MENU bgscreen = screen.copy() if end_trigger == END_LOSE: display_bg("lose", screen) end_trigger = END_MENU menu_choice = world.index - 1 bgscreen = screen.copy() elif end_trigger == END_WIN: display_bg("victory", screen) end_trigger = END_MENU menu_choice = 0 bgscreen = screen.copy() elif end_trigger == END_QUIT or end_trigger == END_HARD_QUIT: done = True elif end_trigger == END_MENU: prev_score = score.score prev_time = score.time prev_levels = score.levels score = Score(0) if prev_score != 0: menu = Mainmenu(screen, prev_score, world, bgscreen, prev_time, prev_levels) else: menu = Mainmenu(screen, None, world, bgscreen) menu_choice = menu.run(menu_choice) if menu_choice == MENU_QUIT: end_trigger = END_QUIT elif menu_choice == MENU_SOUND: Variables.vdict["sound"] = not Variables.vdict["sound"] end_trigger = END_MENU elif menu_choice == MENU_DIALOGUE: Variables.vdict["dialogue"] = not Variables.vdict["dialogue"] end_trigger = END_MENU elif menu_choice == MENU_FULLSCREEN: Variables.vdict["fullscreen"] = not Variables.vdict["fullscreen"] end_trigger = END_MENU apply_fullscreen_setting(screen) elif menu_choice == MENU_WORLD: world_index += 1 if world_index >= len(WORLDS): world_index = 0 world = World(WORLDS[world_index]) end_trigger = END_MENU else: level_name = world.get_level(menu_choice) end_trigger = END_NEXT_LEVEL write_config() write_log() return
def main(): game.run(1,1000,5)
if __name__ == '__main__': import sys total_processes = int(sys.argv[1]) num_of_workers = total_processes - 1 # minus the master max_depth = int(sys.argv[2]) comm = MPI.COMM_WORLD rank = comm.Get_rank() common.VERBOSE = False common.PPRINT = False ctl = controller.ComputerController( None, max_depth, precompute_depth=2 ) # pre-compute depth for controller is 2 (max 49 tasks) if rank == 0: # code for master common.log('initializing master') board = board.Board() master = parallel.MasterController(comm, num_of_workers, board, ctl) # initialize master game = game.Game(board, controller.UserController(board), master) game.run(verbose=True) # run game loop master.done() # indicate MPI ending else: # code for worker common.log(f'initializing worker {rank}') worker = parallel.Worker(rank, comm, ctl) # initialize worker worker.run() common.log(f'worker {rank} exited')
points.append(0) quickTiming = timeMultiplier # changes the name to avoid confusion - but probably makes it more confusing... if quickTiming != 1.0: # this loop speeds up the timing for the trading rounds gameLength = round(gameLength / timeMultiplier, 2) # adjusts for time drift if trading: for i in range(len(buyStage)): buyStage[i] = buyStage[i] / quickTiming # runs a game for gameNumber in range(1, numberOfRounds + 1): details = game.run(numberOfPlayers, startPosition, gameLength, gameNumber, printStatements, playerTypes, trading, quickTiming, randomTime, buyStage, tradeStage, points, player1Chest, player2Chest, player3Chest, player4Chest, player1Chance, player2Chance, player3Chance, player4Chance) df = pandas.read_csv( 'output.csv', index_col='ID' ) # creates a dataframe by reading the output from the previous game frames.append(df) # this is per game and is over written each time # the variables "details" is a 2d array of all the data for each player like this: # details[player number][data from the list below] # both zero indexed # so if you wanted the total money from the 2nd player youd do --> "details[1][3]" # this is the what I'll use for all the analysis before its put into the csv ''' list of indices for data in 'details'
import game import environment if __name__ == '__main__': game = game.Game(60) game.run(environment.level_obj_list[0])
import game as g if __name__ == "__main__": g.run()
class ResourceState(): def update(self, delta): self.leafy = pygame.image.load("data\\Environment\\Sky.png") self.flower = pygame.image.load("data\\Environment\\flower.png") self.wasp_body = pygame.image.load("data\\Characters\\Enemies\\Jalapeno\\Body.png") self.wasp_wing = pygame.image.load("data\\Characters\\Enemies\\Jalapeno\\Wing Front.png") self.broccoli_body = pygame.image.load("data\\Characters\\Enemies\\Onion\\Onion.png") self.player_body = pygame.image.load("data\\Characters\\Main Character\\Body.png") self.player_leg = pygame.image.load("data\\Characters\\Main Character\\Leg Front.png") self.player_wing = pygame.image.load("data\\Characters\\Main Character\\Wing Front.png") self.player_jaw_upper = pygame.image.load("data\\Characters\\Main Character\\Jaw Upper.png") self.player_jaw_lower = pygame.image.load("data\\Characters\\Main Character\\Jaw Lower.png") self.player_dead = pygame.image.load("data\\Characters\\Main Character\\Dead.png") self.bullet = pygame.image.load("data\\Characters\\Main Character\\Bullet.png") self.splash = pygame.image.load("data\\Menu\\SplashScreen.png") self.help = pygame.image.load("data\\Menu\\help.png") self.attack_icon = pygame.image.load("data\\Menu\\Attack.png") self.utility_icon = pygame.image.load("data\\Menu\\Utility.png") self.movement_icon = pygame.image.load("data\\Menu\\Movement.png") for i in range(len(GroundShapes)): GroundShapes[i] = (pygame.image.load(GroundShapes[i][0]), GroundShapes[i][1]) game.set_state(MenuState()) resources = ResourceState() game.run(resources) # import profile, pstats # profile.run('game.run(resources)', "stats") # stats = pstats.Stats('stats') # stats.sort_stats('cumulative') # stats.print_stats()
done = True elif event.type == pygame.KEYDOWN: world.player['Player'].key_down(event.key) elif event.type == pygame.KEYUP: world.player['Player'].key_up(event.key) update() render() pygame.display.flip() post_update() print 'pg.quit' pygame.quit() def update(): world.update() for obj in objects: obj.update() def pre_update(): world.pre_update() for obj in objects: obj.pre_update() def post_update(): world.post_update() for obj in objects: obj.post_update() def render(): for obj in objects: obj.render() edge.manager.render() if __name__ == '__main__': game.run()
def main(): #Parsing level from parameters: level = 0 user_supplied_level = False parse_config() if len(sys.argv) > 1: for arg in sys.argv: if level == -1: try: level = int(arg) user_supplied_level = True except: print "Error: incorrect level number" level = 0 elif arg == "-l": level = -1 #Initializing pygame and screen pygame.init() print "Which way is up starting up." screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) pygame.display.set_caption("Which way is up?") if (pygame.joystick.get_count() > 0): joystick = pygame.joystick.Joystick(0) joystick.init() else: joystick = None score = Score(0) done = False if (Variables.vdict["unlocked"] == 0) or user_supplied_level: # Go straight to the game end_trigger = END_NEXT_LEVEL menu_choice = -2 else: # Go to the menu first end_trigger = END_MENU menu_choice = 0 #Menu and level changing loop, actual game code is in game.py: while not done: if end_trigger == END_NEXT_LEVEL: if level < TOTAL_LEVELS or user_supplied_level: end_trigger = game.run(screen, level, score, joystick) level += 1 if end_trigger == END_QUIT: end_trigger = END_MENU else: end_trigger = END_WIN if end_trigger == END_LOSE: display_bg("lose", screen) end_trigger = END_MENU elif end_trigger == END_WIN: display_bg("victory", screen) end_trigger = END_MENU elif end_trigger == END_QUIT or end_trigger == END_HARD_QUIT: done = True elif end_trigger == END_MENU: prev_score = score.score score = Score(0) if prev_score != 0: menu = Menu(screen, prev_score) else: menu = Menu(screen) menu_choice = menu.run(menu_choice) if menu_choice == MENU_QUIT: end_trigger = END_QUIT elif menu_choice == MENU_SOUND: Variables.vdict["sound"] = not Variables.vdict["sound"] end_trigger = END_MENU elif menu_choice == MENU_DIALOGUE: Variables.vdict["dialogue"] = not Variables.vdict["dialogue"] end_trigger = END_MENU else: level = menu_choice end_trigger = END_NEXT_LEVEL else: if user_supplied_level: user_supplied_level = False end_trigger = END_WIN else: if Variables.vdict["unlocked"] < level: Variables.vdict["unlocked"] = level print "Unlocked level " + str(Variables.vdict["unlocked"]) write_config() return
def main(): run()
def update_clock(): global code now = time.strftime("%H:%M:%S") clock.configure(text=now) code = gen(s) #code = "QQ" #print code update_canvas(canvas, image_list, code) root.after(100, update_clock) update_clock() root.mainloop() stop = False ############################## # main loop # ############################## s.write(chr(0)) while not stop: #generate() here game = reload(game) stop = game.run(code , s )
#!/usr/bin/env python """Entry point for the dodge game.""" import logging import sys import game LOG = logging.getLogger(__name__) if __name__ == '__main__': try: logging.basicConfig(level=logging.INFO) game.run() LOG.info("Exiting normally") sys.exit() except (SystemExit, KeyboardInterrupt) as exc: LOG.info("Caught %s; exiting", type(exc).__name__) sys.exit() except: # pylint: disable=bare-except LOG.critical("Unexpected error", exc_info=sys.exc_info()[0]) sys.exit(1)
def run(): return game.run()
return if game.g.matrix[y + 2][x].type != 'path': game.g.matrix[y + 2][x].update(tt='path') game.g.matrix[y + 1][x].update(tt='path') [ game.dir_stack.append(l) for l in game.g.gen_dt_list(x, y + 2) ] else: if (x - 2 <= 0): return if game.g.matrix[y][x - 2].type != 'path': game.g.matrix[y][x - 2].update(tt='path') game.g.matrix[y][x - 1].update(tt='path') [ game.dir_stack.append(l) for l in game.g.gen_dt_list(x - 2, y) ] else: pass game.g.draw(s) if __name__ == "__main__": # add options here game.add_option('tw', False, DEFAULT_WIDTH, 'The number of tiles in each row of the grid') game.add_option('th', False, DEFAULT_HEIGHT, 'The number of tiles in each column of the grid') game.run(maze_view_setup, maze_view_LOOP)
def runGame(): print("runGame") import states import game print("Starting game") game.run("Crawler Online", (800, 600), states.MainMenuState(), 0, True)
def run(choose_screen, boolean): if (boolean): man = male.male() man.draw(choose_screen) next1 = img.img((50,50),(420,70),"next.png") next1.draw(choose_screen) pre1 = img.img((50,50),(40,70),"pre.png") pre1.draw(choose_screen) next2 = img.img((50,50),(420,160),"next.png") next2.draw(choose_screen) pre2 = img.img((50,50),(40,160),"pre.png") pre2.draw(choose_screen) next3 = img.img((50,50),(420,220),"next.png") next3.draw(choose_screen) pre3 = img.img((50,50),(40,220),"pre.png") pre3.draw(choose_screen) next4 = img.img((50,50),(420,320),"next.png") next4.draw(choose_screen) pre4 = img.img((50,50),(40,320),"pre.png") pre4.draw(choose_screen) f = buttons.button((170,65),(325,435),(255,151,153)) f.draw(choose_screen) g = label.Label((333,440),(70,70),(232,23,61), "None" , 45, "Play Again") g.draw(choose_screen) f2 = buttons.button((170,65),(0,435),(255,151,153)) f2.draw(choose_screen) g2 = label.Label((10,440),(70,70),(232,23,61), "None" , 45, "Play game") g2.draw(choose_screen) pygame.display.flip() else: man = female.female() man.draw(choose_screen) next1 = img.img((50,50),(420,70),"next.png") next1.draw(choose_screen) pre1 = img.img((50,50),(40,70),"pre.png") pre1.draw(choose_screen) next2 = img.img((50,50),(420,160),"next.png") next2.draw(choose_screen) pre2 = img.img((50,50),(40,160),"pre.png") pre2.draw(choose_screen) next3 = img.img((50,50),(420,220),"next.png") next3.draw(choose_screen) pre3 = img.img((50,50),(40,220),"pre.png") pre3.draw(choose_screen) next4 = img.img((50,50),(420,320),"next.png") next4.draw(choose_screen) pre4 = img.img((50,50),(40,320),"pre.png") pre4.draw(choose_screen) f = buttons.button((170,65),(325,435),(255,151,153)) f.draw(choose_screen) g = label.Label((333,440),(70,70),(232,23,61), "None" , 45, "Play Again") g.draw(choose_screen) f2 = buttons.button((170,65),(0,435),(255,151,153)) f2.draw(choose_screen) g2 = label.Label((10,440),(70,70),(232,23,61), "None" , 45, "Play game") g2.draw(choose_screen) pygame.display.flip() while True: ev = pygame.event.poll() #CODE... pygame.display.flip() if ev.type == pygame.MOUSEBUTTONDOWN: x, y = ev.pos if f.rec.collidepoint(x,y): clear((255,255,255), choose_screen) main_game.run(choose_screen) if f2.rec.collidepoint(x,y): clear((255,255,255), choose_screen) game.run(choose_screen, man) if next1.pic.collidepoint(x,y): man.change_hair(1) man.draw(choose_screen) if pre1.pic.collidepoint(x,y): man.change_hair(-1) man.draw(choose_screen) if next2.pic.collidepoint(x,y): man.change_eye(1) man.draw(choose_screen) if pre2.pic.collidepoint(x,y): man.change_eye(-1) man.draw(choose_screen) if next3.pic.collidepoint(x,y): man.change_nose(1) man.draw(choose_screen) if pre3.pic.collidepoint(x,y): man.change_nose(-1) man.draw(choose_screen) if next4.pic.collidepoint(x,y): man.change_mouth(1) man.draw(choose_screen) if pre4.pic.collidepoint(x,y): man.change_mouth(-1) man.draw(choose_screen)
def main(): game = Game() game.init() game.run()