def main(): display = pygame.display.set_mode( (Config['game']['width'], Config['game']['height'])) pygame.display.set_caption(Config['game']['caption']) game = Game(display) game.loop()
class MyPrompt(Cmd): def __init__(self): self.n_player = 0 self.game = Game() scneration01(self.game) self.display_game() super(MyPrompt, self).__init__() self.do_pow('') def display_game(self): print(display_grid(self.game.grid)) def do_pow(self, args): player = None self.n_player = (self.n_player % 2) + 1 player = self.game.getplayer(int(self.n_player)) pos = input("Player %s> X Y: " % player.id) posXY = pos.split(' ') posX = posXY[0] posY = posXY[1] self.game.player_play_pow(player.id, posX, posY) self.display_game() self.do_pow('') def do_quit(self, args): """Quits the program.""" print("Quitting.") raise SystemExit
def __init__(self): self.n_player = 0 self.game = Game() scneration01(self.game) self.display_game() super(MyPrompt, self).__init__() self.do_pow('')
def __init__(self, categoriesSelected, parent): super(GameWindow, self).__init__(parent) self.categories = self.getCategories(categoriesSelected) self.setupUi(self, self.categories) self.game = Game(self.categories) self.spin = "" self.updateUI() self.spinner.clicked.connect(self.spinWheel) self.back.clicked.connect(self.close) self.back.clicked.connect(parent.show)
def __init__(self): self.apps_path = "" self.working_dir = "" self.hack_dir = "" self.decrypt_dir = "" self.backup_dir = "" self.user = User() self.game = Game()
def test_model(self, model): steps_arr = [] scores_arr = [] for _ in range(self.test_games): steps = 0 game_memory = [] game = Game() _, score, snake, apple = game.start() prev_observation = self.generate_observation(snake, apple) for _ in range(self.goal_steps): predictions = [] for action in range(-1, 2): predictions.append( model.predict( self.add_action_to_observation( prev_observation, action).reshape(-1, 5, 1))) action = np.argmax(np.array(predictions)) game_action = self.get_game_action(snake, action - 1) done, score, snake, apple = game.step(game_action) game_memory.append([prev_observation, action]) if done: print('-----') print(steps) print(snake) print(apple) print(prev_observation) print(predictions) break else: prev_observation = self.generate_observation(snake, apple) steps += 1 steps_arr.append(steps) scores_arr.append(score) print('Average steps:', mean(steps_arr)) print(Counter(steps_arr)) print('Average score:', mean(scores_arr)) print(Counter(scores_arr))
def initial_population(self): training_data = [] for _ in range(self.initial_games): display = pygame.display.set_mode( (Config['game']['width'], Config['game']['height'])) pygame.display.set_caption(Config['game']['caption']) game = Game(display) _, prev_score, snake, apple = game.start() prev_observation = self.generate_observation(snake, apple) prev_apple_distance = self.get_apple_distance(snake, apple) for _ in range(self.goal_steps): action, game_action = self.generate_action(snake) done, score, snake, apple = game.step(game_action) if done: training_data.append([ self.add_action_to_observation(prev_observation, action), -1 ]) break else: apple_distance = self.get_apple_distance(snake, apple) if score > prev_score or apple_distance < prev_apple_distance: training_data.append([ self.add_action_to_observation( prev_observation, action), 1 ]) else: training_data.append([ self.add_action_to_observation( prev_observation, action), 0 ]) prev_observation = self.generate_observation(snake, apple) prev_apple_distance = apple_distance return training_data
def calculateDistanceMap(macarte: numpy.array, murs) -> int: ## <DONTCOPY> ## from classes.Point import Point from classes.Game import Game from classes.Debug import Debug import time ## </DONTCOPY> ## #Pathfinding.distanceMap = {{None} * len(macarte[0])} * len(macarte) #Pathfinding.distanceMap = numpy.empty((len(macarte), len(macarte[0]), len(macarte), len(macarte[0])), dtype=object) Pathfinding.distanceMap = {} nbCalcMap = 0 totalCalcExpected = 0 casesOk = [] for x in range(len(macarte)): Pathfinding.distanceMap[x] = {} for y in range(len(macarte[0])): if macarte[x][y] not in murs: Pathfinding.distanceMap[x][y] = None casesOk.append((x, y)) totalCalcExpected += 1 else: Pathfinding.distanceMap[x][y] = None for x, y in casesOk: if not Game.check_timeout(): tmp = Pathfinding.buildDistanceMap(macarte, Point(x, y), [False], 15) assert tmp[x][y] == 0 Pathfinding.distanceMap[x][y] = tmp nbCalcMap += 1 else: Debug.msg( f"checkDistanceMap stopped at {x},{y} ({round(nbCalcMap*100/totalCalcExpected)} %) with {time.time() - Game.startTime}" ) return nbCalcMap return nbCalcMap
def get_games(self): a = [ s for s in os.listdir(self.path) if os.path.isdir(os.path.join(self.path, s)) ] if len(a) == 0: print( f"{self.path} contains no games. Please ensure you have run QCMA and backed up your game." ) sys.exit("No Game In User Path") a.sort(reverse=True, key=lambda s: os.path.getmtime(os.path.join(self.path, s))) for folder in a: game_id = findall(r"([A-Z]{4}[0-9]{5})$", folder) if game_id: game = Game() game.set_id(game_id[0]) game.set_path(self.path) self.games.append(game)
from flask import Flask, request, render_template, redirect, send_from_directory from classes.Game import Game app = Flask(__name__, static_url_path='/js', static_folder='templates/js/', template_folder='templates/') class Init(object): def __init__(self): self.player_id = 0 game = Game() init = Init() def initgame(): if init.player_id != 0: return True init.player_id = 1 # INIT ## INIT player 1 y = 0 while y < 24: for x in range(25, 27): game.player_play_pow(1, x, y)
from classes.Game import Game game = Game() game.game_loop()
#!/usr/bin/python # -*- encoding: utf-8 -*- __author__ = 'Oliver Banse' # IDEA # Import and Initialization import pygame from classes.Game import Game from classes.Screen import Screen pygame.init() # Display configuration screen = Screen('Hit the Mole!', 800, 600) # Entities game = Game(screen) # Run Game game.start() # if __name__ == '__main__': # game.start()
from classes.Game import Game if __name__ == '__main__': game = Game() game.run()
class GameWindow(QtWidgets.QMainWindow, Ui_game): def __init__(self, categoriesSelected, parent): super(GameWindow, self).__init__(parent) self.categories = self.getCategories(categoriesSelected) self.setupUi(self, self.categories) self.game = Game(self.categories) self.spin = "" self.updateUI() self.spinner.clicked.connect(self.spinWheel) self.back.clicked.connect(self.close) self.back.clicked.connect(parent.show) def getCategories(self, categoriesSelected): categories = [] for cat in categoriesSelected: category = self.__getCategory(cat) categories.append(category) return categories def __getCategory(self, cat): filename = os.path.join('db', cat + '.csv') try: with open(filename, "r") as csvfile: rowReader = csv.reader(csvfile, delimiter='|') for row in rowReader: return row except: message = QMessageBox.question(self, "Error", "File does not exist", QMessageBox.Ok) if (message == QMessageBox.Ok): self.close() else: pass def spinWheel(self): self.spin = self.game.spinWheel() # Opens the Game Choice but needs to get the selected category if self.spin == 7 or self.spin == 9: self.goToGameChoice = GameChoiceWindow(self.game, parent=self) self.goToGameChoice.exec_() self.spin = self.goToGameChoice.categoryChoice # Once it has a category or if the category is spun, brings up the Game Answer window. Should determine if # player answered correctly and adject accordingly. if self.spin == 0 or self.spin == 2 or self.spin == 4 or self.spin == 6 or self.spin == 8 or self.spin == 10: data = self.game.playCategory(self.spin) if not (data[0] == ""): self.goToGameAnswer = GameAnswerWindow(data, parent=self) self.goToGameAnswer.exec_() answerCorrect = self.goToGameAnswer.answerCorrect questionValue = data[1] if answerCorrect: self.game.playerAnswersCorrect(questionValue) else: self.game.playerAnswersIncorrect(questionValue) else: self.game.playTurn(self.spin) gameOver = self.game.isGameOver() if gameOver: self.updateUI() winner = self.game.getWinner() score = self.game.getPlayer(winner).getTotalScore() goToGaveOver = GameOverWindow(winner, score, parent=self) goToGaveOver.exec_() self.updateUI()
"item": hiPotion, "quantity": 5 }, { "item": superPotion, "quantity": 5 }, { "item": elixer, "quantity": 5 }, { "item": hiElixier, "quantity": 2 }, { "item": grenade, "quantity": 5 }] #Instantiate People player = Person("Mario", 3260, 200, 60, 34, playerSpells, playerItems) player2 = Person("Mario", 4160, 200, 60, 34, playerSpells, playerItems) player3 = Person("Robot", 3889, 200, 60, 34, [], playerItems) enemy = Person("Evil Mario", 18200, 701, 525, 25, [], []) enemy2 = Person("MXMXM", 1250, 130, 560, 325, [], []) enemy3 = Person("Imp", 1250, 130, 560, 325, [], []) players = [player, player2, player3] enemies = [enemy, enemy2, enemy3] game = Game(players, enemies) game.announcement() game.play()
def test_something_3(self): game = Game(1, 2, True) game.pc_play_first() self.assertEqual("humain", game.winner)
import colorama from classes.Game import Game colorama.init(autoreset=True) # Hide the cursor print("\x1b[?25l") game = Game() option_picked = game.start_game() if option_picked == -1: game.quit_game() else: # If the game has to be started game.play_game()
import pygame as pg pg.init() from classes.Game import Game g = Game() g.run() g.show_end_screen()
import pygame, sys from pygame.locals import * sys.path.append('/home/denis/Documentos/developer/python/snake-game/classes') from classes.Game import Game from classes.Snake import Snake from classes.Apple import Apple pygame.init() # GAME INITIALIZATION snake_game = Game() WINDOW_SIZE = (snake_game.WINDOW_WIDTH, snake_game.WINDOW_HEIGHT) PIXEL_SIZE = snake_game.PIXEL_SIZE COLORS = snake_game.COLORS FPS = snake_game.FPS # AUDIO pygame.mixer.init() pygame.mixer.music.load('./assets/audios/yamete-kudasai.wav') # SNAKE INITIALIZATION snake_head_image = pygame.image.load('./assets/images/snake-head.png') initial_snake_pos = [(200, 200), (190, 200), (180, 200)] snake = Snake(initial_snake_pos, snake_head_image) # APPLE INITIALIZATION initial_apple_pos = (100, 100)
import pygame from classes.config import Config from classes.Game import Game pygame.init() display = pygame.display.set_mode((Config['w_g'], Config['h_g'])) pygame.display.set_caption('Project 3 semester by Iliya Puzhaev') game = Game(display) game.start_screen()
def test_something(self): game = Game(200, 2, 1) while game.winner == "": self.assertTrue(game.jeu_ordinateur() > 0)
def test_something_5(self): game = Game(1, 2, False) game.pc_play_first() self.assertEqual(game.nb_restantes, 1)
from classes.Game import Game if __name__ == "__main__": game = Game() game.run()
def play_game(player_names): game = Game(player_names) print(get_game_intro_dialog(game)) while game.game_over == False: game.advance_game()
def test_something_2(self): game = Game(33, 2, 1) game.afficher_restant()
from classes.Game import Game Game().run()
def main(): g = Game() g.set_up() g.mainloop()
'killing_as_a_service': Service('killing_as_a_service', '20113', killing_as_a_service), 'ATM_machine': Service('ATM_machine', '20061', ATM_machine), 'gdps': Service('gdps', '20037',gdps), 'temperature': Service('temperature', '25096',temperature), 'spiderman': Service('spiderman', '30000',spiderman), 'tattletale': Service('tattletale', '13007',tattletale) } teamListStatus = { } for teamName, team in teamList.iteritems(): serviceListStatus = { } for serviceName, service in serviceList.iteritems(): serviceListStatus[serviceName] = "Down" teamListStatus[teamName] = serviceListStatus honeypotList = {'poemwriter','gdps'} game = Game(teamList, serviceList, honeypotList) newGame = 0 for arg in sys.argv: if arg == "-n": newGame = 1 if newGame: game.resetLog() else: game.restoreLog() threading.Timer(2, routine).start() app.run(host = "0.0.0.0")
def get_games_stats(config, upcoming_flg, begin_yr=None, begin_wk=None): if upcoming_flg: start_yr = datetime.datetime.now().year current_yr = datetime.datetime.now().year + 1 else: start_yr = config["start_yr"] if begin_yr is None else begin_yr current_yr = datetime.datetime.now().year root_dir = os.getcwd().replace("/src", "").replace("/data", "") data_dir = os.path.join(root_dir, "data", "external") games_by_team_path = os.path.join(data_dir, "game_summary_by_team.csv") for season in range(start_yr, current_yr): season = Season(season, config) games_table = season.get_schedule_table() weekly_dict = season.get_weekly_dict(games_table, upcoming_flg, begin_yr, begin_wk) for week_num, games in weekly_dict.items(): week = Week(season, week_num, weekly_dict[str(week_num)], upcoming_flg) print("\nYear: {} / Week: {}".format(season.season, week_num)) for game_idx, game_info in enumerate(week.games): if os.path.exists(games_by_team_path): games_by_team_df = pd.read_csv(games_by_team_path) else: games_by_team_df = pd.DataFrame() game = Game(week, week.games[game_idx], upcoming_flg) print(game.game_full_url) for team_idx, team_info in enumerate(game.teams_list): opp_info = game.teams_list[abs(team_idx - 1)] home_flg = team_info["home_flg"] team = Team(game, team_info["team"], opp_info["team"], home_flg) opponent = Team(game, opp_info["team"], team_info["team"], opp_info["home_flg"]) team_row_dict = team.get_team_game_summary(game) team_game_stats_dict = team.get_indiv_game_stats() rush_dir_dict = team.get_rush_dir_stats() drive_summary_dict = team.get_drive_summary_dict() team_row_dict.update(team_game_stats_dict) team_row_dict.update(rush_dir_dict) team_row_dict.update(drive_summary_dict) team_snap_rows = team.get_game_snap_rows(opp_flg=False) team_game_player_stats = get_player_stats_rows( team_snap_rows, team) opp_snap_rows = team.get_game_snap_rows(opp_flg=True) opp_game_player_stats = get_player_stats_rows( opp_snap_rows, opponent) team_game_player_df = pd.DataFrame(team_game_player_stats) team.drop_to_csv(team_game_player_df, "game_summary_by_player") opp_game_player_df = pd.DataFrame(opp_game_player_stats) if len(team_game_player_df) > 0 and len( opp_game_player_df) > 0: team_pos_dict = team.aggregate_game_stats_by_pos(\ team_game_player_df, opp_flg = False, \ off_snaps = team_row_dict["team_plays"], def_snaps = team_row_dict["opp_plays"]) opp_pos_dict = team.aggregate_game_stats_by_pos(\ opp_game_player_df, opp_flg = True, \ off_snaps = team_row_dict["opp_plays"], def_snaps = team_row_dict["team_plays"]) team_row_dict.update(team_pos_dict) team_row_dict.update(opp_pos_dict) team_idx_dict = team.get_idx_cols(games_by_team_df, team_row_dict) team_row_dict.update(team_idx_dict) team.add_row_to_csv(team_row_dict)
# Expecting player input to pick a language def language_picked(): language = input( "Welcome to the Hangman ! Wich language would you like to use ? \n(use the first two letter of your language, ex: 'fr' for French\n") while len(language) != 2 or not language.isalpha(): language = input("Use only two letters, ex: 'it' for Italian\n") print("You chose " + language.upper()) return language # Translate the random word generated based on language picked by the player def translated_word(): trans = Translator() return unidecode.unidecode(trans.translate(generated_word(), src='en', dest=language_picked()).text).lower() # Game initialization game = Game(translated_word()) # Write a welcome message def welcome(): print("Let's see if you will be able to save the man from hanging ... ;)") # Check if the player have used all his chances or if he won def is_game_over(): return game.get_try_number() == 0 or game.game_won() # Check if the letter has already been used # yes: send a message to warn the player that he already used that letter # no: add it to a list of letter been used # Then check if the letter is in the secret word # yes: change current secret word state # no: the player lose one chance
game.next_Round() # update gui self.update_Main_Window_Information() def load_cats_data(path,file_name): cats=[] file_path=path+file_name for i in range(1,DataBaseIO.len_Database(file_path,"CAT")+1): t_name=DataBaseIO.read_Database(file_path,"CAT",i,"NAME") t_is_alive=DataBaseIO.read_Database(file_path,"CAT",i,"IS_ALIVE") t_friendly_const=DataBaseIO.read_Database(file_path,"CAT",i,"FRIENDLY_CONST") t_consumption=DataBaseIO.read_Database(file_path,"CAT",i,"CONSUMPTION") t_appeared_yesterday=DataBaseIO.read_Database(file_path,"CAT",i,"APPEARED_YESTERDAY") cats.append(Cat(t_name,t_is_alive,t_friendly_const,t_consumption,appeared_yesterday=t_appeared_yesterday)) return cats if __name__ == "__main__": import sys path = "savings/" file_name="init.db" cats = load_cats_data(path,file_name) campus = Campus(cats) game = Game(campus, cats) app = QApplication(sys.argv) Main_Window = QtWidgets.QMainWindow() win = myWindow(Main_Window) Main_Window.show() sys.exit(app.exec_())