def season(season_num, dest, driver=None): close_driver_at_end = False if driver else False if driver == None: driver = driver_init() create_dirs = [dest, dest + '/games'] for d in create_dirs: if not os.path.exists(d): os.makedirs(d) base_url = 'http://www.j-archive.com/showseason.php?season=' season_soup = get_soup(driver, base_url + str(season_num)) game_tags = season_soup.tbody('tr', recursive=False) game_tags.reverse() games = [] summary_dict = dict() for g_tag in game_tags: link = g_tag.a['href'] game_id = int(link.split('=')[1]) exp = re.compile(r'#(\d+), aired ([\d-]+)') text = g_tag.a.text.replace(u'\xa0', u' ') match = exp.search(text) show_id = int(match.group(1)) date = match.group( 2) #datetime.datetime.strptime(match.group(2), '%Y-%m-%d').date() cs = g_tag.find_all('td', valign='top')[1].text.strip().split(' vs. ') summary_dict[str(game_id)] = { 'show_id': show_id, 'date': date, 'Contestant 1': cs[0], 'Contestant 2': cs[1], 'Contestant 3': cs[2] } try: comment = g_tag.find('td', class_='left_padded').text.strip() if comment != '': summary_dict[str(game_id)]['comment'] = comment except: pass with open(dest + '/summary.json', 'w') as summary_file: json.dump(summary_dict, summary_file) for game_id in summary_dict: print('Getting game ' + game_id) game(int(game_id), dest=dest + '/games/' + game_id + '.json', driver=driver) sleep(.5) if close_driver_at_end: driver.close()
def main(): pygame.init() flags = DOUBLEBUF | FULLSCREEN | HWSURFACE screen = pygame.display.set_mode((width, height), flags) pygame.display.set_caption("Adventure of Ghostly Square v0.1") background = Surface((width, height)) background = image.load("pics/background.png") frame = [] marker = 'play' button_size = (400, 200) play_image = image.load("pics/play1.png") quit_image = image.load("pics/quit.png") active_bg = Surface(button_size) active_bg.fill(Color("#656565")) play_button_pos = [200, 100] exit_button_pos = [200, 400] while 1: for command in pygame.event.get(): if command.type == QUIT: raise SystemExit if command.type == KEYUP: if marker == 'play': if command.key == K_DOWN or command.key == K_UP: play_image = image.load("pics/play.png") marker = 'quit' quit_image = image.load("pics/quit1.png") elif command.key == K_SPACE: try: game() except PlayerIsDead: print 'PlayerIsDead' except AllMobsAreDead: print 'Level cleared' elif marker == 'quit': if command.key == K_DOWN or command.key == K_UP: play_image = image.load("pics/play1.png") marker = 'play' quit_image = image.load("pics/quit.png") elif command.key == K_SPACE: raise SystemExit if command.type == KEYDOWN and command.key == K_t: if flags == DOUBLEBUF: flags = DOUBLEBUF | FULLSCREEN else: flags = DOUBLEBUF screen = pygame.display.set_mode(size_of_display, flags) background = screen.get_rect() screen.blit(background, (0, 0)) if marker == 'play': screen.blit(active_bg, (play_button_pos[0], play_button_pos[1])) elif marker == 'quit': screen.blit(active_bg, (exit_button_pos[0], exit_button_pos[1])) screen.blit(play_image, (play_button_pos[0], play_button_pos[1])) screen.blit(quit_image, (exit_button_pos[0], exit_button_pos[1])) for i in frame: screen.blit(i[0], i[1]) pygame.display.update()
def user_interface(): ''' The function that runs and prints the game.''' rows = ask_for_row_or_col_number(num_rows) cols = ask_for_row_or_col_number(num_cols) turn = ask_for_inputs(moves_first) left_color = ask_for_inputs(top_left) mode = ask_for_game_mode() game_board = new_game_board(cols, rows, left_color) state = game(game_board, turn, mode) while True: _print_display_info(game_board, cols, rows, state, turn) if state.color_no_legal_move(turn): print('\nNo valid move remains for this color, opposite turn\n') opposite = opposite_color(turn) turn = opposite state = game(game_board, turn, mode) #_print_display_info(game_board, cols, rows, state, turn) else: col_to_drop = ask_for_cell_to_drop(ask_col_num) row_to_drop = ask_for_cell_to_drop(ask_row_num) try: flip_list = CheckMove(game_board, col_to_drop, row_to_drop, turn).check_a_move() except InvalidMoveError: print('Invalid move, please try again\n') except OutOfBoardError: print('Specified cell out of board\n') except CellFilledError: print('Specified cell is not empty\n') except: print('Error\n') else: game_board = state.make_move(flip_list, col_to_drop, row_to_drop) if not game_not_over(game_board, turn, mode): turn = None _print_display_info(game_board, cols, rows, state, turn) break else: opposite = opposite_color(turn) turn = opposite state = game(game_board, turn, mode) game_not_over(game_board, turn, mode)
def main(): deposit.bank_deposit = 0 welcome() if (deposit.bank_deposit <= 2): deposit() while (deposit.bank_deposit > 2): choose_nb() money() game()
def go_to_game(): ans_human = menu('Введите кол-во игроков (людей)', ['1. 1-игрок', '2. 2-игрока', '0. Без людей'], ['1', '2', '0']) ans_computer = menu('Введите кол-во игроков (компьютеров)', ['1. 1-игрок', '2. 2-игрока', '0. Без компьютеров'], ['1', '2', '0']) if int(ans_human) + int(ans_computer) == 0: print('Нужен хотя-бы один игрок, хоть сам с собой') return game(int(ans_human), int(ans_computer))
def waiting_room(id, username): ''' Draws waiting room with *id* number. *Username* - username of user creating game with id number. ''' global start, finished finished = False header_font = pygame.font.SysFont('Arial', int(scale_x * 80)) button_font = pygame.font.SysFont('Arial', int(scale_x * 50)) text_font = pygame.font.SysFont('Arial', int(scale_x * 40)) back_button = button( int(100 * scale_x), int(100 * scale_x), 'Back', button_font) load_anim.play() screen = get_screen() raw_time = 0 time = 0 start = False while not finished: for event in pygame.event.get(): if event.type == pygame.QUIT: cl.execute_sql( "DELETE FROM Chess WHERE id='"+str(id)+"';", "askristal") pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if back_button.check(): cl.execute_sql( "DELETE FROM Chess WHERE id='"+str(id)+"';", "askristal" ) finished = True start = False raw_time += 1 / FPS if raw_time > time + 1: _thread.start_new_thread(check_start, (id, 0)) time = int(raw_time) write_text('Waiting for another player to join: ' + str(time), ( int(480 * scale_x), int(180 * scale_y)), screen, header_font) write_text('Your game id is ' + str(id), ( int(680 * scale_x), int(230 * scale_y)), screen, text_font) back_button.draw() load_anim.blit(screen, (int(700 * scale_x), int(350 * scale_y))) clock.tick(FPS) pygame.display.update() fill() load_anim.stop() if start: game(id, username) return start
def simulate_betting(): arch = const.MATCH_ARCHIVE bettors = [Bettor(0), Bettor(1), Bettor(2)] for i in range(len(const.TEAM_NAMES)): for j in range(i, len(const.TEAM_NAMES)): team_a, team_b = const.TEAM_NAMES[i], const.TEAM_NAMES[j] matches = arch[arch["Team A"] == team_a][arch["Team B"] == team_b].append( arch[arch["Team B"] == team_a][arch["Team A"] == team_b] ) if not matches.empty: for index, row in matches.iterrows(): result = row["Winner"] if result == 0 or result == 1: true_stats = game(team_a, team_b) for bettor in bettors: bettor.bet( [float(row["Team A Odds"]), float(row["Team B Odds"])], [true_stats[0], 100 - true_stats[0]], int(row["Winner"]), int(row["Match_No"]), ) for bettor in bettors: print bettor plt.plot(*zip(*sorted(bettor.history, key=lambda x: x[0])), label=const.STRATEGIES[bettor.strategy]) plt.legend() plt.show()
def main(): state = State() state.init_state state.screen_size = ScreenSize state.double_buffer = DoubleBuffer state.fullscreen = Fullscreen state.framerate = Framerate alive = True clock = pygame.time.Clock() app = game(screen,clock) while alive: # Events if pygame.event.peek(QUIT): alive = False events = pygame.event.get() # Pump events to game for event in events: app.handle_event(event) # Update state update = app.update() # Draw app.draw() # Are we done? alive = app.alive # Did we update anything? if update: # if so, redraw screen pygame.display.flip() # Regular framerate clock.tick(state.framerate)
def play_games(num_of_sims=10000): # data to collect total_history = [] for i in range(num_of_sims): history = [] # call game for data collection history = game(player1_name="Red", player2_name="Blue", method_1="random", method_2="random", model=None, display=False, training=True) total_history += history # store data in df and save to csv training_data = pd.DataFrame(total_history) training_data.columns = [x + 1 for x in range(126) ] + ["Player_1 Wins", "Player_2 Wins"] # clean data data = clean_data(training_data) check(data) # save training data to csv data.to_csv('big_data_c4.csv')
def main(): running = True # Pygame initialization pygame.init() pygame.display.set_caption("2.5D Pong") screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Initializing objects ball = Ball() scoreboard = Scoreboard(11) # Main loop, will run until you close the window or force stop the program while running: # Calls the main menu and gets paddles paddles = mainMenu(screen, ball) if paddles[0] != 0: # Creates Game object with paddles and runs it winner = game(screen, ball, scoreboard, paddles) if winner[2] == 0: running = False else: sleep(1) # Runs win menu when the game is over, loops back to main menu running = winMenu(screen, winner) else: running = False
class ai: game = game() def copy(self, board): #Makes a copy of main board. copyBoard = board return copyBoard #Checks if can win with next move. def checkIfCanWin(self, user, x, board, realBoard): for i in range(1, len(board)): if board[i] == " ": board[i] = user if checkIfWond(board): realBoard[i] = x return True board[i] = " " break else: board[i] = " " #Takes a random place in board and placeses it. def _randomMove(self, user, board): taken = False while taken == False: rnd = random.randrange(1, len(board)) if board[rnd] == " ": board[rnd] = user taken = True #Not in use. def _aiMove(self, move, board, user): board[move] = user
def runProg(iterations, players): if (iterations <= 0) or (players <= 0): print("invalid arguments") click.echo("running game for " + str(iterations) + "times", nl=False) count = 0 while iterations > 0: print("game" + str(count)) count = count + 1 deck = game.deck() shuffledDeck = game.shuffle(deck, players) game(shuffledDeck) iterations = iterations - 1
def gamewinner(board, boardstates): #this function will find all boardstates from the current game and show the proper winner. #board.actions will handle ending the game properly. #It will also need to call the game() function properly. boardstates.append(newobject(board)) winner=input("Who won? Enter \"1\" or \"2\" or something else to avoid choosing winner") for x in range(len(boardstates)): if boardstates[x].gamenum==board.gamenum: if winner=="1": boardstates[x].p1wins=1 if winner=="2": boardstates[x].p2wins=1 cmd=input("Play another? \"y\" or \"n\"?") if cmd=="y": game(deckp1,deckp1,boardstates,board,new=1) else: quit
def main(): #фывфывфывфы screen = pygame.display.set_mode(DISPLAY) play = True name = '' post = '' clr = False name, clr = inputName(screen, clr) print("clr = " + str(clr)) if clr: post = "b" print("clr = " + str(clr)) cl.SetName(name) while play: game(cl, post) if CurrentLevel() > 4: CurrentLevel.SetNum(1)
def main(): ## Vars # Communication clients = list() spectators = list() # Game gameInstance = game() # creation du socket d'ecoute ear = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ear.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ear.bind(('', 7777)) ear.listen(3) print("Serveur lance") # Boucle d'attente de connexion print("Attente de connexion...") while True: tmp = list(clients) tmp.append(ear) changes = select.select(tmp, list(), list())[0] for client in changes: # Traitement du socket d'ecoute if client == ear: data = client.accept() print("Nouvelle connexion de " + str(data[1])) # Ajout du client clients.append(data[0]) # Ajout du client a la partie gameInstance.addPlayer(data[0]) # Sinon reception des donnees else: data = client.recv(1500) # Traitement deconnexion if len(data) == 0: # Si la longueur recue est 0 c'est que l'user s'est deconnecte cmd_disconnect(gameInstance, clients, client) # Analyse du paquet # CMD : PLACE if data.startswith(b"PLACE "): if gameInstance.gameReady: gameInstance.place(client, formalizedata(data, "PLACE ")) else: sendError(client, "Game hasn't started yet.\n") # CMD : JOIN elif data.startswith(b"JOIN"): if not gameInstance.gameReady: gameInstance.joinGame(client) # CMD : DISCONNECT elif data.startswith(b"DISCONNECT"): cmd_disconnect(gameInstance, clients, client) pass
def test_nash_elimination(self): game1.set_utility_1(u1) game1.set_utility_2(u2) (z1, z2) = game1.reduced_game_nash() reduced_game = game((len(z1)), (len(z2)) ) reduced_game.set_utility_1(z1) reduced_game.set_utility_2(z2) self.assertEqual(nash_equilibria, set(reduced_game.nash()))
def new_game(gamename): if gamename in global_var.realgames: username = session['user'] game1 = game(username, global_var.gameid, gamename) global_var.opengamedict[global_var.gameid] = game1 global_var.gameid += 1 return (redirect('/')) else: return (redirect('/'))
def __init__(self): self.username = raw_input("请输入姓名:") global dict dict['name'] = self.username self.userage = raw_input("请输入您的年龄:") dict['age'] = self.userage if int(dict['age']) < 18: print "您未满18岁!" elif int(dict['age']) >= 18: self.two = game() self.two.fangfa()
def main(): game_g = game() print("Welcome to this text survival game! What is your name?") name = input() user = player(name) print("Good luck", user.name, "your adventure is about to begin...") time.sleep(2) os.system('clear') print( "You wake up in the middle of the woods... " "You have no clue how you got there.\nThe sun is beating down on you, " "you look around and all you see are trees... \n" "You check your phone, no service. You don't know if anyone else knows you are here\n" "Which direction would you like to go?\n") answer = input() answer = answer.lower() if answer == "help": handle_help() handle_turn(game_g, user, False) elif answer == 'north' or answer.startswith("n"): length = ask_amount("time", game_g, user) game_g.coordinates[1] += length if game_g.coordinates[1] > 100: print( "Sorry you've reached the bounds of the game, you only walked", length - (game_g.coordinates[1] - 100), "hours") elif answer == 'south' or answer.startswith("s"): length = ask_amount("time", game_g, user) game_g.coordinates[1] -= length if game_g.coordinates[1] < -100: print( "Sorry you've reached the bounds of the game, you only walked", length + (game_g.coordinates[1] + 100), "hours") elif answer == 'east' or answer.startswith("e"): length = ask_amount("time", game_g, user) game_g.coordinates[0] += length if game_g.coordinates[0] > 100: print( "Sorry you've reached the bounds of the game, you only walked", length - (game_g.coordinates[0] - 100), "hours") elif answer == 'west' or answer.startswith("w"): length = ask_amount("time", game_g, user) game_g.coordinates[0] -= length if game_g.coordinates[0] < -100: print( "Sorry you've reached the bounds of the game, you only walked", length + (game_g.coordinates[1] + 100), "hours") else: print("Sorry that is not a valid command\n") handle_help() time_up(game_g, length, user) handle_turn(game_g, user, True) sys.exit()
def statehandler(stdscr, screen, screen_panel, field_h, field_w, mine_num): done = False nextstate = 'menu' while not(done == True): if nextstate == 'game': nextstate = game(stdscr, screen, screen_panel, field_h, field_w, mine_num) if nextstate == 'quit': return if nextstate == 'menu': nextstate = mainmenu(stdscr, screen, screen_panel)
def main() : gameQuit = False """ testGame = game() testGame.nameUser() print("") testGame.printUserData() print("") testGame.nameOpponent() print("") testGame.printOpponentData() print("") testGame.draw() testGame.getMove() testGame.draw() testGame.resetGame() testGame.draw() """ Game = game() Game.nameUser() print("") Game.printUserData() print("") Game.nameOpponent() print("") Game.printOpponentData() print("") Game.draw() while not gameQuit : while Game.gameRunning() : Game.getMove() Game.draw() print() Game.printUserData() print("Continue playing (Yes or No)? : Y or N") choice = input (">>> ") while ( (choice != "Y") and (choice != "N") ) : print ("Y or N?") choice = input(">>> ") if choice == "Y" : gameQuit = False Game.resetGame() else : gameQuit = True
def menu(): while True: print("Welcome to the chatbot!") print("-----------------------") print() choice = int(input("""Please choose one of the options bellow :) Chatbot - 1 Cool Game - 2 Exit :( - 3 """)) if choice == 1: chatbot() elif choice == 2: game() elif choice == 3: print("BYEEE!") break else: print("You have to pick a number!")
def __init__(self): logger= logging.getLogger('start logging') logger.setLevel(logging.DEBUG) log= logging.FileHandler(filename='example.log', mode='w') format=logging.Formatter('%(message)s') log.setFormatter(format) log.setLevel(logging.INFO) logger.addHandler(log) noOfAgents= 2 noOfobjects= 3 maxObjects= 10 maxAgents= 100 timeSteps = 10 parameters={'WORD_LENGTH': 3, 'MIN_SCORE': 0.1, 'SUCCESS_DELTA':1.0, 'FAILURE_DELTA': 0.2, 'MAX_SCORE': 10.0, 'noOfobjects': noOfobjects, 'noOfAgents': noOfAgents, 'timeSteps': timeSteps} logger.info( "\nnoOfAgents:%i \nnoOfobjects:%i \ntimeSteps:%i \nwordlength:%i \nMIN_SCORE:%f \nSUCCESS_DELTA:%f \nFAILURE_DELTA:%f \nMAX_SCORE:%f \n" % (noOfAgents, noOfobjects, parameters['timeSteps'], parameters['WORD_LENGTH'], parameters['MIN_SCORE'], parameters['SUCCESS_DELTA'], parameters['FAILURE_DELTA'], parameters['MAX_SCORE'] )) #runs dialog until convergence # g=game(parameters) # a=g.dialogTillConverge(parameters) # print a #starts dialog for given timestep # b=g.dialogGivenTime(parameters) # print b #An example of plotting noOfobjects vs convergence time ct=[] #time of convergence for o in range(1, maxObjects+1): #noofobjects change parameters['noOfobjects']= o g = game(parameters) convergence_time, SuccessRate= g.dialogTillConverge(parameters) ct.append(convergence_time) print parameters['noOfobjects'] print ct plot(SuccessRate, label=('%iobjects' % o)) o= o+1 # plot(ct) # xlim(0, maxObjects) xlabel('Number of Rounds') ylabel('Success Rate') legend(loc=4) show()
def setUp (self) : """ setup for the tests to run""" self.game = game () self.game._user = user ("Bob", 'X', 0, 0, 0) self.game._ai = EAI ("Gary", 'O') self.point1 = Point (1,1) self.point2 = Point (1,2) self.point3 = Point (1,3) self.point4 = Point (2,1) self.point5 = Point (2,2) self.point6 = Point (2,3) self.point7 = Point (3,1) self.point8 = Point (3,2) self.point9 = Point (3,3)
def main(): in_game = True pos = 0 clock = pygame.time.Clock() while in_game: for event in pygame.event.get(): if event.type == QUIT: in_game = False if event.type == pygame.KEYDOWN: pos = event.key print() screen.fill(BLACK) game(pos) if FRUITS == []: in_game = False clock.tick(30) pygame.display.update() pygame.quit()
def main(): while 1: #define the initial status status = "Game Start" #Choose board size size_selection = question_screen(status) #run the game function and check the exit status status = game(size_selection) #two exit status:win/quit, ask if restart is needed or just exit confirm = question_screen(status) if confirm == 'QUIT': print('Game Quit') return else: print('Game Restart')
def __init__(self, game: Any, p1_strategy: Callable, p2_strategy: Callable[[Any], Any]) -> None: """ Initialize this GameInterface, setting its active game to game, and using the strategies p1_strategy for Player 1 and p2_strategy for Player 2. """ first_player = input("Type y if player 1 is to make the first move: ") is_p1_turn = False if first_player.lower() == 'y': is_p1_turn = True self.game = game(is_p1_turn) self.p1_strategy = p1_strategy self.p2_strategy = p2_strategy
def game_not_over(board, color, mode) -> bool: ''' Checks whether the current game state is over. If the game is over, prints the winning or tie message and the winning player if exists.''' try: state = game(board, color, mode) state._game_over() except GameOverError: if state._more_discs() == 'White' or 'Black': print('\nGame Over, the winner is: {}\n'.format( state._more_discs())) return False else: print('\nThe game is a tie\n') return False else: return True
def main(): ## Vars # Communication clients = list() spectators = list() # Game gameInstance = game() # Création d'un socket d'écoute - notre "oreille" ear = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) ear.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ear.bind(('', 7777)) ear.listen(3) print("Serveur lance") print("Attente de connexion...") ## Boucle principale while True: tmp = list(clients) tmp.append(ear) changes = select.select(tmp, list(), list())[0] ## Parcours des sockets en attente de lecture for client in changes: # Traitement du socket d'écoute if client == ear: data = client.accept() print("Nouvelle connexion de " + str(data[1])) # Ajout du client clients.append(data[0]) # Ajout du client à la partie gameInstance.addPlayer(data[0]) # Traitement else: data = client.recv(1500) # Traitement deconnexion if len(data) == 0: # Si la longueur recue est 0 c'est que l'user s'est deconnecte cmd_disconnect(gameInstance, clients, client) # CMD : DISCONNECT elif data.startswith(b"DISCONNECT"): cmd_disconnect(gameInstance, clients, client) # TODO : gestion de PLACE et JOIN pass
def creator(self): while self.life >0: gameon=game(self.score,self.life) num=gameon.main_loop() if num <=0: self.life-=1 self.score=-num self.score-=25 if self.score <0: self.score=0 elif num==3.14: print 1 break elif num>=0: self.score=num pygame.quit()
def main() : """"initiliaze a new game and set the name of user and opponent then draw the board and enter the loop for the game. For each game get a move then draw and continue until a win or draw. After a game is over print the user data and ask the user if they want to continue or stop playing """ gameQuit = False Game = game() Game.nameUser() print("") Game.printUserData() print("") Game.nameOpponent() print("")0 Game.printOpponentData() print("") Game.draw() while not gameQuit : while Game.gameRunning() : point = Game.getPlacement() Game.turn (point) Game.draw() print() Game.printUserData() print("Continue playing (Yes or No)? : Y or N") choice = input (">>> ") while ( (choice != "Y") and (choice != "N") ) : print ("Y or N?") choice = input(">>> ") if choice == "Y" : gameQuit = False Game.resetGame() else : gameQuit = True
def play(): global score score = game() if score > pickle.load(open("score.pickle", "rb")): pickle.dump(score, open("score.pickle", "wb")) else: pass entry.configure(state="normal") entry.delete(0, END) entry.insert(1, pickle.load(open("score.pickle", "rb"))) entry.configure(state="disabled") currentScore.configure(state="normal") currentScore.delete(0, END) currentScore.insert(1, score) currentScore.configure(state="disabled") time.sleep(3) destroy()
def checking(self): self.p = game() #self.p.show() for i in range(64): if self.p.t[i // 8][i % 8] == "P": self.pP = possibleP(i) self.ans = self.ans + self.pP.calcmove() elif self.p.t[i // 8][i % 8] == "K": self.pK = possibleK(i) self.ans = self.ans + self.pK.calcmove() elif self.p.t[i // 8][i % 8] == "R": self.pR = possibleR(i) self.ans = self.ans + self.pR.calcmove() elif self.p.t[i // 8][i % 8] == "B": self.pB = possibleB(i) self.ans = self.ans + self.pB.calcmove() elif self.p.t[i // 8][i % 8] == "Q": self.pQ = possibleQ(i) self.ans = self.ans + self.pQ.calcmove() elif self.p.t[i // 8][i % 8] == "A": self.pA = scratch(i) self.ans = self.ans + self.pA.calcmove() return self.ans
def main(): # Check if sound and font are supported if not pygame.font: print "Warning, fonts disabled" # Constants FPS = 35 SCREEN_WIDTH, SCREEN_HEIGHT = 480, 800 SCREENRECT = Rect(0, 0, 480, 800) SPEED = 5 BACKGROUND_COLOR = (0, 0, 0) # font = pygame.font.Font(None, 30) score = 0 levelNum = 0 # Initialize Pygame, the clock (for FPS), and a simple counter pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 0) pygame.display.set_caption('Sky High') clock = pygame.time.Clock() # Game loop while True: time_passed = clock.tick(FPS) if levelNum == 0: levelNum = title(screen) # Returns 99 if "Play Game" is clicked, 100 if "View Highscores" is clicked elif levelNum == 100: levelNum = scores(screen) # Returns 0 when player exits highscore screen levelNum = 0 else: # levelNum == 99: t = game(screen) score = score + int(t) if android: filename = "highscores.txt" else: filename = "highscores.txt" highscore = [("",0), ("",0), ("",0), ("",0), ("",0), ("",0), ("",0), ("",0)] try: # If there is already a highscores file, try opening it f = open(filename, "r+") except IOError: # If there is no highscores file, create one and add 0's to it f = open(filename, "w+") cPickle.dump(highscore, f) f.seek(0) try: highscore = cPickle.load(f) except EOFError: pass # Just don't load anything username = "******" if android: ## android.show_keyboard() ## ## #KEY MAPPING ## android.map_key(android.KEYCODE_BACK, pygame.K_BACKSPACE) ## android.map_key(android.KEYCODE_ENTER, pygame.K_RETURN) ## android.map_key(android.KEYCODE_SPACE, pygame.K_SPACE) ## android.map_key(android.KEYCODE_A, pygame.K_a) ## android.map_key(android.KEYCODE_B, pygame.K_b) ## android.map_key(android.KEYCODE_C, pygame.K_c) ## android.map_key(android.KEYCODE_D, pygame.K_d) ## android.map_key(android.KEYCODE_E, pygame.K_e) ## android.map_key(android.KEYCODE_F, pygame.K_f) ## android.map_key(android.KEYCODE_G, pygame.K_g) ## android.map_key(android.KEYCODE_H, pygame.K_h) ## android.map_key(android.KEYCODE_I, pygame.K_i) ## android.map_key(android.KEYCODE_J, pygame.K_j) ## android.map_key(android.KEYCODE_K, pygame.K_k) ## android.map_key(android.KEYCODE_L, pygame.K_l) ## android.map_key(android.KEYCODE_M, pygame.K_m) ## android.map_key(android.KEYCODE_N, pygame.K_n) ## android.map_key(android.KEYCODE_O, pygame.K_o) ## android.map_key(android.KEYCODE_P, pygame.K_p) ## android.map_key(android.KEYCODE_Q, pygame.K_q) ## android.map_key(android.KEYCODE_R, pygame.K_r) ## android.map_key(android.KEYCODE_S, pygame.K_s) ## android.map_key(android.KEYCODE_T, pygame.K_t) ## android.map_key(android.KEYCODE_U, pygame.K_u) ## android.map_key(android.KEYCODE_V, pygame.K_v) ## android.map_key(android.KEYCODE_W, pygame.K_w) ## android.map_key(android.KEYCODE_X, pygame.K_x) ## android.map_key(android.KEYCODE_Y, pygame.K_y) ## android.map_key(android.KEYCODE_Z, pygame.K_z) ## android.map_key(android.KEYCODE_0, pygame.K_0) ## android.map_key(android.KEYCODE_1, pygame.K_1) ## android.map_key(android.KEYCODE_2, pygame.K_2) ## android.map_key(android.KEYCODE_3, pygame.K_3) ## android.map_key(android.KEYCODE_4, pygame.K_4) ## android.map_key(android.KEYCODE_5, pygame.K_5) ## android.map_key(android.KEYCODE_6, pygame.K_6) ## android.map_key(android.KEYCODE_7, pygame.K_7) ## android.map_key(android.KEYCODE_8, pygame.K_8) ## android.map_key(android.KEYCODE_9, pygame.K_9) ## # android.map_key(android.ACTION_DOWN, pygame.KEYDOWN) ## ## for event in pygame.event.get(): ## ## if event.type == pygame.KEYDOWN: ## username = "" ## if event.key == pygame.K_t: ## username += "t" ## ## #username = raw_input("Enter name: ") android.hide_keyboard() # Add the new highscore if it is high enough newscore = (username, score) highscore.append(newscore) highscore = sorted(highscore, key=itemgetter(1), reverse = True) del highscore[-1] # Clear file's contents f.close() f = open(filename, "w+") # Write the new high score table cPickle.dump(highscore, f) f.close() levelNum = 0 score2 = score score = 0 username = "******" endgame(screen, score2) # Flip the display pygame.display.flip()
def __init__(self, lent, depth): self.counter = 0 self.fb = flipboard() self.p = game() self.len = lent self.depth = depth self.pawnBoard = [[0, 0, 0, 0, 0, 0, 0, 0], [50, 50, 50, 50, 50, 50, 50, 50], [10, 10, 20, 30, 30, 20, 10, 10], [5, 5, 10, 25, 25, 10, 5, 5], [0, 0, 0, 20, 20, 0, 0, 0], [5, -5, -10, 0, 0, -10, -5, 5], [5, 10, 10, -20, -20, 10, 10, 5], [0, 0, 0, 0, 0, 0, 0, 0]] self.rookBoard = [[0, 0, 0, 0, 0, 0, 0, 0], [5, 10, 10, 10, 10, 10, 10, 5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [-5, 0, 0, 0, 0, 0, 0, -5], [0, 0, 0, 5, 5, 0, 0, 0]] self.knightBoard = [[-50, -40, -30, -30, -30, -30, -40, -50], [-40, -20, 0, 0, 0, 0, -20, -40], [-30, 0, 10, 15, 15, 10, 0, -30], [-30, 5, 15, 20, 20, 15, 5, -30], [-30, 0, 15, 20, 20, 15, 0, -30], [-30, 5, 10, 15, 15, 10, 5, -30], [-40, -20, 0, 5, 5, 0, -20, -40], [-50, -40, -30, -30, -30, -30, -40, -50]] self.bishopBoard = [[-20, -10, -10, -10, -10, -10, -10, -20], [-10, 0, 0, 0, 0, 0, 0, -10], [-10, 0, 5, 10, 10, 5, 0, -10], [-10, 5, 5, 10, 10, 5, 5, -10], [-10, 0, 10, 10, 10, 10, 0, -10], [-10, 10, 10, 10, 10, 10, 10, -10], [-10, 5, 0, 0, 0, 0, 5, -10], [-20, -10, -10, -10, -10, -10, -10, -20]] self.queenBoard = [[-20, -10, -10, -5, -5, -10, -10, -20], [-10, 0, 0, 0, 0, 0, 0, -10], [-10, 0, 5, 5, 5, 5, 0, -10], [-5, 0, 5, 5, 5, 5, 0, -5], [0, 0, 5, 5, 5, 5, 0, -5], [-10, 5, 5, 5, 5, 5, 0, -10], [-10, 0, 5, 0, 0, 0, 0, -10], [-20, -10, -10, -5, -5, -10, -10, -20]] self.kingMidBoard = [[-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-30, -40, -40, -50, -50, -40, -40, -30], [-20, -30, -30, -40, -40, -30, -30, -20], [-10, -20, -20, -20, -20, -20, -20, -10], [20, 20, 0, 0, 0, 0, 20, 20], [20, 30, 10, 0, 0, 10, 30, 20]] self.kingEndBoard = [[-50, -40, -30, -20, -20, -30, -40, -50], [-30, -20, -10, 0, 0, -10, -20, -30], [-30, -10, 20, 30, 30, 20, -10, -30], [-30, -10, 30, 40, 40, 30, -10, -30], [-30, -10, 30, 40, 40, 30, -10, -30], [-30, -10, 20, 30, 30, 20, -10, -30], [-30, -30, 0, 0, 0, 0, -30, -30], [-50, -30, -30, -30, -30, -30, -30, -50]]
from game import * import unittest game1 = game(2,2) u1 = [[-1,-1/2],[-1,-1]] u2 = [[-1,-1], [-1/2,-1]] nash_equilibria = set([(0,0), (0,1), (1,0)]) class TestNashEquilibria(unittest.TestCase): def test_nash_bruteForce(self): game1.set_utility_1(u1) game1.set_utility_2(u2) (z1, z2) = game1.reduced_game_nash() self.assertEqual(nash_equilibria, set(game1.nash())) def test_nash_elimination(self): game1.set_utility_1(u1) game1.set_utility_2(u2) (z1, z2) = game1.reduced_game_nash() reduced_game = game((len(z1)), (len(z2)) ) reduced_game.set_utility_1(z1) reduced_game.set_utility_2(z2) self.assertEqual(nash_equilibria, set(reduced_game.nash()))
#######################main game############################ # if player choose start game at start screen if StartGame == True: pygame.mixer.music.play(-1) #########Enter the game here########### print "Game Start" #restart from start screen StartScreen = True # Game module here # Level 1 ship_life, score = game(screen) if ship_life == 0: pygame.mixer.music.stop() overscreen(screen, "lose") continue cleaner(screen, "down-top") # Level 2 ship_life, score = game2(screen, ship_life, score) if ship_life > 0: pygame.mixer.music.stop() overscreen(screen, "win") else:
pygame.mixer.init() # Tamanho da tela. screen = pygame.display.set_mode((WIDTH, HEIGHT)) # Nome do jogo pygame.display.set_caption("Capture The Flegg") game_status = GameStatus(screen) # Comando para evitar travamentos. try: state = INIT while state != QUIT: if state == INIT: state = init_screen(game_status) elif state == GAME: state = game(game_status) elif state == WINV: state = win_screen_red(game_status) elif state == WINA: state = win_screen_blue(game_status) elif state == SETTINGS: state = settings(game_status) elif state == CREDITS: state = creditss(game_status) else: state = QUIT finally: pygame.quit()
#!/bin/python3 # -*-coding:Utf-8 -* from menu import * #on importe les modules de menu et jeu from game import * while True: choice = menu() #on affiche le menu et demande quoi faire if choice == 1: #option1 : on affiche les regles menuSeeRules() if choice == 2: #option2 : on lance le jeu game() if choice == 3: #option3 : on quitte le jeu MenuQuit() continue
#this is going to be the main loop. gonna experiment a bit first. from game import * vintput = raw_input("test") while vinput != "stop": vinput = raw_input("test") game()
game_name = "Prisoner's Dilemma" numberOfPlayers = 2 players_names = ['row','column'] players_strategies = {} players_strategies['row'] = ['C','D'] players_strategies['column'] = ['C','D'] payoff_matrix = {} payoff_matrix[(('row','C'),('column','C'))] = {'row':-1,'column':-1} payoff_matrix[(('row','C'),('column','D'))] = {'row':-4,'column':0} payoff_matrix[(('row','D'),('column','C'))] = {'row':0,'column':-4} payoff_matrix[(('row','D'),('column','D'))] = {'row':-3,'column':-3} # Define an instance of the game PD = game(game_name, players_names, players_strategies, payoff_matrix) # Define an instance of the NashEqFinder NashEqFinderInst = NashEqFinder(PD, stdout_msgs = 'off') [Nash_equilibria,exit_flag] = NashEqFinderInst.runPure() print 'exit_flag = ',exit_flag print 'Nash_equilibria = ',Nash_equilibria print "\n-- Game of pure coordination ---" # Pure strategy Nash eq: (Left,Left) and (Right,Right) game_name = "Pure coordination" numberOfPlayers = 2 players_names = ['row','column']
def main(): game().play()
id = v['venue']['id'] name = v['venue']['name'] city = v['venue']['city'] stadium = Venues(name, id, city) team_id = v['homeTeam']['id'] team_city = v['homeTeam']['city'] team_name = v['homeTeam']['name'] team_abbr = v['homeTeam']['abbreviation'] teams[team_abbr] = Team(team_abbr, team_id, stadium, team_city, team_name) if (team_abbr == "NYG"): teams["NYJ"] = Team("NYJ", 51, stadium, team_city, "Jets") game_list = [] for g in schedule['games']: id = g['schedule']['id'] s_week = g['schedule']['week'] away = g['schedule']['awayTeam']['abbreviation'] home = g['schedule']['homeTeam']['abbreviation'] completion = g['schedule']['playedStatus'] awayScore = g['score']['awayScoreTotal'] homeScore = g['score']['homeScoreTotal'] new_game = game(id, s_week, away, home, completion, awayScore, homeScore) game_list.append(new_game) teams[new_game.away].addAwayGame(new_game) teams[new_game.home].addHomeGame(new_game) #for p in players: print(schedule['games'][0]['schedule'])
def main(): gra=game(740,480,200,0,"Czolgi",1000) execfile(pa("sys/menuust.py")) gra.graj()
# start the game with run.py import pygame from pygame.locals import * pygame.init() from game import * screen = pygame.display.set_mode((800,600)) game(screen)
from game import * from gameMap import * thegame=game() themap=map()
def main(): game()
def add_game(self, map_id, id, accel, friction, gravity, MaxVelocity): self.games[id] = game(self.maps[map_id], self, accel, friction, gravity, MaxVelocity)