def new_game(cls, white_token, black_token, type_game, time_limit, white_user=None, black_user=None): game = cls(white_token, black_token) game.game = engine.Game() game.model = models.Game.create( white=white_token, black=black_token, player_white=white_user, player_black=black_user, state=str(game.game.board), type_game=type_game, time_limit=time_limit, ) delete_cache('wait_{}'.format(white_token)) delete_cache('wait_{}'.format(black_token)) game.send_ws(game.get_info(consts.WHITE), consts.WS_START, consts.WHITE) game.send_ws(game.get_info(consts.BLACK), consts.WS_START, consts.BLACK) return game
def load_game(cls, token): try: try: game_model = models.Game.get_game(token) except models.Game.DoesNotExist: data = get_cache('wait_{}'.format(token)) if data: raise errors.GameNotStartedError(*data) raise errors.GameNotFoundError game = cls(game_model.white, game_model.black) game.model = game_model game.game = engine.Game(game.model.state, game.model.next_color, game.model.cut) game._loaded_by = game_model._loaded_by if game.model.is_time_over(): winner = game.model.winner loser = invert_color(winner) game.send_ws(game.get_info(loser), consts.WS_LOSE, loser) game.send_ws(game.get_info(winner), consts.WS_WIN, winner) if not game.model.ended: game.check_draw() game.check_castles() except errors.GameNotStartedError: raise except: raise errors.GameNotFoundError return game
def main(resolution, fps): # initialse pygame pygame.init() # set up frame rate clock = pygame.time.Clock() dt = 1.0 / float(fps) timestep = 0 time = 0.0 # create the buffer and display buffer = pygame.display.set_mode(resolution) pygame.display.set_caption('Space Invaders - L4D') pygame.display.set_icon(pygame.image.load('data/enemy.png')) # enable smooth controls pygame.key.set_repeat(10,10) # initialse the game game = engine.Game() # main game loop while game.state is not engine.GameStates.QUIT: game.check_input() game.update(resolution, fps, dt, timestep, time) graphics.draw(game, buffer) pygame.display.flip() clock.tick(fps) timestep += 1 time += dt
def t_place(place, success): game = engine.Game(field=std_field) if success: game.place(place, T) assert type(game.field[place]) == T else: with pytest.raises(KeyError): game.place(place, T)
def t_notify(mocker): notificants = [mocker.Mock() for _ in range(3)] game = engine.Game() [game.add_notificant(n) for n in notificants] args = ('you', 'been', 'served') game.notify(*args) [n.assert_called_once_with(*args) for n in notificants]
def start_game_with_config(filename): config = configparser.ConfigParser() with open(filename, "r") as file: config.read_file(file) settings = {} for key in config["int"]: settings[key] = config["int"].getint(key) for key in config["float"]: settings[key] = config["float"].getfloat(key) for key in config["bool"]: settings[key] = config["bool"].getboolean(key) print("starting new game with configuration from '" + filename + "'") engine.game = engine.Game(settings)
def continue_program(self): ''' This function is called when the continue button is pressed. It renders a new screen and loads the previous game state. ''' self.button_list_loadingScreen = [] self.playScreen = False # creates the engine.Game variable of the class Game to initate play engine.Game = engine.Game( engine.loadProgress() ) # calls the function to check for and gather variables from the previous game state self.bootStart()
def play_program(self): ''' This function is called when the play button is pressed. It renders a new screen and starts a new game. ''' self.button_list_loadingScreen = [ ] # empties the list for laoding screen buttons to remove button display self.playScreen = False # boolean for displaying the loading screen is set to false # creates the engine.Game variable of the class Game to initate play engine.Game = engine.Game( []) # the "[]" indicates that there is no variable to load # initializes the game display on start up self.bootStart()
def t_move_units_accuracy(mocker): il = [I() for _ in range(4)] test_field = {(2, 2): il[0], (2, 3): il[1], (2, 5): il[2], (1, 7): il[3]} expected_field = { (2, 1): il[0], (2, 2): il[1], (2, 4): il[2], (1, 6): il[3] } game = engine.Game(field=test_field) game.move_units() assert expected_field == game.field
def setUp(self): self.p1 = engine.Player('Player One') self.p2 = engine.Player('Player Two') self.p2_grid = self.p2.battle_grid self.p2_submarine = engine.Ship.submarine() self.p2_destroyer = engine.Ship.destroyer() self.p2_grid.place_ship(self.p2_submarine, 'A1', engine.Orientation.LANDSCAPE) self.p2_grid.place_ship(self.p2_destroyer, 'C7', engine.Orientation.PORTRAIT) self.game = engine.Game(self.p1, self.p2)
def t_game_activate_units_kill(mocker): # set up to kill the defender defender = units.MeleeInvader() defender.health = 1 attacker = units.GunTower() field = {(1, 1): defender, (1, 2): attacker} m_roll_pct = mocker.patch('units.roll_pct') m_roll_pct.return_value = True game = engine.Game(field=field) game.activate_units() assert ({ (1, 2): attacker } == game.field # defender dead and attacker.health == 3) # defender didn't shoot back
def checkMiscButtons(self, x, y): # check start button button = self.startButton if button.leftBound <= x <= button.rightBound and button.lowerBound <= y <= button.upperBound: # start a new game game = engine.Game(self.players, self.activePlayers, self.boardSize) mainWindow = GameWindow(game) constants.clicksound.play() pyglet.clock.schedule_interval(mainWindow.update, 1 / 60) self.music.pause() self.close() # check exit button button = self.exitButton if button.leftBound <= x <= button.rightBound and button.lowerBound <= y <= button.upperBound: constants.clicksound.play() pyglet.app.exit()
def run_match(ind, bot1, bot2, count): cfg.PLAYER_1_PATH = topdir + '/robots/' + bot1 cfg.PLAYER_2_PATH = topdir + '/robots/' + bot2 os.mkdir(f'match{ind}') os.chdir(f'match{ind}') win_count1 = 0 win_count2 = 0 for k in range(count): winner = engine.Game().run() if winner == 'A': win_count1 += 1 else: win_count2 += 1 os.rename('A.txt', f'{k}_A.txt') os.rename('B.txt', f'{k}_B.txt') os.rename('gamelog.txt', f'{k}_gamelog.txt') os.rename('gamelog.pdf', f'{k}_gamelog.pdf') plt.gca().set_prop_cycle(None) os.chdir('..') return win_count1, win_count2
def play_function(): """ Main game function. :return: None """ global main_menu global clock global PLAYERS global SPEED print('Game starts for {0} players'.format(PLAYERS)) # Reset main menu and disable # You also can set another menu, like a 'pause menu', or just use the same # main_menu as the menu that will check all your input. main_menu.disable() main_menu.reset(1) engine.set_params(speed=SPEED, players=PLAYERS) game_engine = engine.Game(menu=main_menu) game_engine.game_loop( ) # doesn't return until game is over or close is requested main_menu.enable()
def play_function(): """ Main game function. :return: None """ global PLAYERS global SPEED print('Game starts for {0} players'.format(PLAYERS)) # Reset main menu and disable # You also can set another menu, like a 'pause menu', or just use the same # main_menu as the menu that will check all your input. GAME_ENV.main_menu.disable() GAME_ENV.main_menu.reset(1) PLAYER_CFG.NUM_PLAYERS = PLAYERS PLAYER_CFG.CONTROLS = player_controls GAME_CFG.DELAY_FACTOR = 10 - SPEED game_engine = engine.Game() game_engine.game_loop( ) # doesn't return until game is over or close is requested GAME_ENV.main_menu.enable()
def t_move_units_order(mocker): # assemble an ordering for move() calls il = [I() for _ in range(4)] test_field = {(2, 2): il[0], (2, 3): il[1], (2, 5): il[2], (1, 7): il[3]} move_calls = [] def closure(u): def inner(*args): move_calls.append(u) return inner for u in test_field.values(): u.move = mocker.Mock() u.move.side_effect = closure(u) game = engine.Game(field=test_field) game.move_units() assert il == move_calls
def t_game_activate_units(mocker): # mocking on this is crazy: Have to record the order in which the # effect calls happen on the various units, then assert it was done # correctly. Sheesh. effect_calls = [] def closure(u): def inner(*args): effect_calls.append(u) return None, None, None return inner for u in std_field.values(): u.effect = mocker.Mock() u.effect.side_effect = closure(u) game = engine.Game(field=std_field) game.activate_units() assert (isinstance(effect_calls[0], T) and isinstance(effect_calls[1], T) and isinstance(effect_calls[2], I) and isinstance(effect_calls[3], I))
def main(): pygame.init() screen = create_screen() game = engine.Game(BHEIGHT, BWIDTH) pygame.time.set_timer(INCREASE_SPEED, INCREASE_SPEED_INTERVAL) tickspeed = STARTING_TICK_MS pygame.time.set_timer(GAME_TICK, tickspeed) playing = True while playing: # If too many events are happening before the draw happens, I may need to convert this to a # pygame.event.poll(), handle one event, then redraw for event in pygame.event.get(): if event.type == pygame.QUIT: playing = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE: playing = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT: game.on_input(engine.User_action.LEFT) elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT: game.on_input(engine.User_action.RIGHT) elif event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN: game.on_input(engine.User_action.DOWN) elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE: game.on_input(engine.User_action.ROTATE) elif event.type == GAME_TICK: playing = game.on_tick() elif event.type == INCREASE_SPEED: pygame.time.set_timer(GAME_TICK, 0) tickspeed = tickspeed - TICK_SPAN_DECREASE pygame.time.set_timer(GAME_TICK, tickspeed) draw_game(screen, game.game_state()) pygame.quit()
#========= # Imports #========= import socket import json import engine #============ # Game stuff #============ board = engine.TicTacToe() game = engine.Game() #============== # Server stuff #============== TCP_IP = '' TCP_PORT = 3000 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept()
import pygame import engine import reader import sys State = "game" # a state variable MAXFPS = 60 # Maximum rate the loop will run at CLOCK = pygame.time.Clock() # Object used to restrict framerate of program if __name__ == '__main__': pygame.init() display = pygame.display.set_mode((1024, 768)) GameEngine = engine.Game() theMap = reader.Map() map_list, tile_list = theMap.read('test_map') looping = True while looping: # Main loop # Manage logic if State == "game": GameEngine.on_loop(map_list, display) pygame.display.flip() # Update the entire display CLOCK.tick(MAXFPS) # Cap Framerate
#!/usr/bin/python import sys, time import engine, botplayer import view import csv cfg_file = sys.argv[1] bots = sys.argv[2:] DEBUG = False ##se le pasa el mapa como fichero de configuracion config = engine.GameConfig(cfg_file) ##la configuracion y la cantidad de jugadores game = engine.Game(config, len(bots)) ##Bots que ejecutan la IA del jugador y se comunican actors = [ botplayer.BotPlayer(game, i, cmdline, debug=DEBUG) for i, cmdline in enumerate(bots) ] for actor in actors: actor.initialize() viewg = view.GameView(game) with open('pruebas.csv', mode='w') as pruebas: w_pruebas = csv.writer(pruebas, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
do_p = do_place do_q = do_quit do_l = do_look def notificant(event, *details): if event is None: return if event is 'end': message = 'YOU WIN!' if details[0] == units.Invader: message = 'YOU LOSE!' print("========================") print("GAME OVER,", message) print("========================") sys.exit(0) print(event, *details) if __name__ == '__main__': # tell people how to play, then start the command line interface. print(intro_text) cli = PyrgoiCLI() # have to instantiate the field scenario = scenarios.demo field = {k: v() for k, v in scenario['field'].items()} cli.game = engine.Game(field=field, win_cond=scenario['win-cond']) cli.game.add_notificant(notificant) print(map.render_game_state(cli.game)) cli.cmdloop() # GLHF
def main(): g = engine.Game(800, 600, framerate=20, title="simulator") g.run(Runner(g))
def on_key_press(self, symbol, modifiers): if symbol == key.RETURN: new_scene = FakeGameScene(self.window_state) self.window_state.game.push_scene(new_scene) class FakeGameScene(engine.TextScene): text = 'You Are Playing the Game' def on_key_press(self, symbol, modifiers): if symbol == key.RETURN: self.window_state.game.pop_scene() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-f', '--fullscreen', action='store_true', help='Run the game in fullscreen mode') args = parser.parse_args() g = engine.Game(MenuScene, 'Skeleton', (1024, 768), fullscreen=args.fullscreen) g.begin() pyglet.app.run() run_game()
from scipy.sparse.csgraph import connected_components from scipy.sparse import csr_matrix from json import load, dumps import numpy as np from constants import * import spritesheet import engine import pygame Game = engine.Game(BACKGROUND, fullscreen=False) GameSpritesheet = spritesheet.Spritesheet(GAME_SPRITESHEET) game_sprites = GameSpritesheet.images_datafile(SPRITES_DATAFILE) NameSpritesheet = spritesheet.Spritesheet(NAME_SPRITESHEET) name_sprites = NameSpritesheet.images_datafile(CITIES_DATAFILE) city_sprites = [] names = [] for city in load(open(CITY_POS_DATAFILE, "r")): names.append(city[SPRITE_ID]) sprite_id = city[SPRITE_ID] x, y = city[POSITION] cityspace_c = engine.Point(x + CITYTEXT_WIDTH // 2, y + CITYSPACE_SIZE // 2) cityspace_size = (CITYSPACE_SIZE, CITYSPACE_SIZE) citytext_size = (CITYTEXT_WIDTH, CITYTEXT_HEIGHT) a = pygame.transform.scale(game_sprites[city[SPRITE_ICON]], cityspace_size) b = pygame.transform.scale(name_sprites[city[SPRITE_ID]], citytext_size) s = (CITYTEXT_WIDTH, CITYSPACE_SIZE + CITYTEXT_HEIGHT - CITYTEXT_UPSHIFT) image = pygame.Surface(s, pygame.SRCALPHA)
def run_command(self, command, m, isgroup): """ Run commands :param command: Command to execute :param m: full dict message :param isgroup: whether the message is written in a group or a chat :return: """ self.logger.info("Executing command %s" % command) chat_id = m['chat']['id'] message_id = m['message_id'] comw = command.split() if comw[0] == "start": # start a new game if not isgroup: self.send_message( chat_id, "Esegui questo comando in una chat di gruppo.", message_id) elif self.groupchats[chat_id].game: self.send_message( chat_id, "C'è già una partita in corso in questo gruppo.", message_id) elif len(comw) < 2: self.send_message( chat_id, "Perfavore, dimmi anche i ruoli che desideri. Ad esempio:" "\n\n/start ccccccvll. Puoi vedere i ruoli disponibili usando /help.", message_id) else: try: self.groupchats[chat_id].game = engine.Game( comw[1].lower().strip()) self.send_message( chat_id, "Nuova partita creata. Cliccate qui 👉/in per entrare nella partita.", message_id) except engine.UnrecognizedRole: self.send_message( chat_id, "Mi spiace, non sono riuscito ad interpretare la stringa dei ruoli." " Usa /help per vedere quali sono i ruoli disponibili.", message_id) except engine.MoreThanOneWorP: self.send_message( chat_id, "Mi spiace, è possibile inserire solo un protettore e solo una " "veggente.", message_id) elif comw[0] == "in": # add a new player if not isgroup: pass else: if not self.groupchats[chat_id].game: self.send_message( chat_id, "Non c'è una partita in corso. Inizia una partita col comando /start", message_id) else: if self.groupchats[chat_id].game.state != PRE: self.send_message( chat_id, "La partita è già in corso, come minimo sei un po' in ritardo.", message_id) else: sender = m['from']['id'] for player in self.groupchats[chat_id].game.players: if player.chat_id == sender: self.send_message( chat_id, "Sei già inserito e confermato, " "attendi gli altri giocatori.", message_id) return if len(self.groupchats[chat_id].game.players) < len( self.groupchats[chat_id].game.rolelist): self.groupchats[chat_id].game.players.append( Player( sender, m['from'], len(self.groupchats[chat_id].game.players)) ) self.send_message( chat_id, "Inserito (%d/%d)." % (len(self.groupchats[chat_id].game.players), len(self.groupchats[chat_id].game.rolelist)), message_id) if len(self.groupchats[chat_id].game.players ) == len( self.groupchats[chat_id].game.rolelist): self.start_game(chat_id) else: self.send_message( chat_id, "Mi spiace, numero totale di giocatori già raggiunto.", message_id) elif comw[0] == "stop": # stop game self.send_message( chat_id, "Sei veramente sicuro di voler arrestare la partita?" " Se sì, dai il comando /stopstop", message_id) elif comw[0] == "stopstop": # stop game for real! if not isgroup: delete = False for gpc in self.groupchats: player = self.get_player(chat_id, gpc) delete = True if player is not None else False if self.groupchats[gpc].game.state != PRE: self.send_message(chat_id, "Ti sei suicidato.", message_id) self.groupchats[gpc].game.euthanise(player.index) self.send_message(gpc, "%s si è suicidato." % player.name) break else: self.send_message(chat_id, "Hai abbandonato la partita.", message_id) del self.groupchats[gpc].game.players[player.index] self.groupchats[gpc].game.recompute_player_index() self.send_message( gpc, "%s ha lasciato la partita." % player.name, message_id) break if not delete: self.send_message( chat_id, "Non mi risulta tu sia in nessuna partita.", message_id) else: if self.groupchats[chat_id].game is None: self.send_message( chat_id, "Nessun gioco attivo, niente da interrompere.", message_id) else: self.stop_game(chat_id) try: for p in self.groupchats[chat_id].game.players: self.send_message( p.chat_id, "La partita è stata interrotta.") except ValueError: pass self.send_message(chat_id, "Partita terminata.", message_id) elif comw[0] == "info": # info if isgroup: if self.groupchats[chat_id].game: if self.groupchats[chat_id].game.state == PRE: self.send_message( chat_id, "In attesa di conferma dei giocatori.", message_id) elif self.groupchats[chat_id].game.state == NIGHT: st = "" if not self.groupchats[chat_id].game.stato_lupi: st += "Aspettando la decisione dei lupi\n" if not self.groupchats[chat_id].game.stato_veggente: st += "Aspettando la decisione della veggente\n" if not self.groupchats[chat_id].game.stato_protettore: st += "Aspettando la decisione del protettore\n" self.send_message(chat_id, st, message_id) elif self.groupchats[chat_id].game.state == DAY: st = "Devono ancora votare: \n" st += "".join([ "- " + p.name + "\n" for p in self.groupchats[chat_id].game.alivePlayers() if p.choice is None ]) self.send_message(chat_id, st, message_id) else: st = engine.stateName( self.groupchats[chat_id].game.state) + "\n" st += "\nGiocatori vivi:\n\n" for p in self.groupchats[chat_id].game.alivePlayers(): st += p.name + "\n" self.send_message(chat_id, st, message_id) else: self.send_message( chat_id, "Nessuna partita attiva. Usa /start per iniziare una nuova partita, " "/help per maggiori informazioni, /rule per le regole.", message_id) else: self.send_message( chat_id, "Questo comando è veramente utile sono nella chat della partita. Prova " "/help.", message_id) elif comw[0] == "help": st = "Per iniziare una nuova partita, eseguire /start seguito da una stringa di ruoli:\n" st += "C - Contadino\n" st += "L - Lupo\n" st += "V - Veggente\n" st += "P - Protettore\n" st += "F - Figlio del Lupo\n" st += "\nPer fermare la partita, esegui /stop" self.send_message(chat_id, st, message_id) elif comw[0].isdigit(): n = int(comw[0]) - 1 if not isgroup: pl = None gpcp = None for gpc in self.groupchats: # controllo se è notte e il messaggio viene da uno dei giocatori in gioco if self.groupchats[gpc].game and self.groupchats[ gpc].game.state == NIGHT: pl = self.get_player(chat_id, gpc) gpcp = gpc if pl is not None: if pl.role == engine.lupo: try: if self.groupchats[gpcp].game.players[n].alive and \ not self.groupchats[gpcp].game.stato_lupi: pl.choice = n self.groupchats[gpcp].game.stato_lupi = True self.send_message(chat_id, "Selezionato.", message_id) else: self.send_message( chat_id, "Quel giocatore non è vivo.", message_id) except (IndexError, KeyError): self.send_message(chat_id, "Quel giocatore non esiste.", message_id) if pl.role == engine.veggente and not self.groupchats[ gpcp].game.stato_veggente: try: if self.groupchats[gpcp].game.players[n].alive: pl.choice = n self.groupchats[ gpcp].game.stato_veggente = True self.send_message(chat_id, "Selezionato.", message_id) else: self.send_message( chat_id, "Quel giocatore non è vivo.", message_id) except (IndexError, KeyError): self.send_message(chat_id, "Quel giocatore non esiste.", message_id) if pl.role == engine.protettore and not self.groupchats[ gpcp].game.stato_protettore: try: if self.groupchats[gpcp].game.players[n].alive: pl.choice = n self.groupchats[ gpcp].game.stato_protettore = True self.send_message(chat_id, "Selezionato.", message_id) else: self.send_message( chat_id, "Quel giocatore non è vivo.", message_id) except (IndexError, KeyError): self.send_message(chat_id, "Quel giocatore non esiste.", message_id) else: if self.groupchats[chat_id].game and self.groupchats[ chat_id].game.state == DAY: p = self.get_player(m['from']['id'], chat_id) if p is not None: try: if self.groupchats[chat_id].game.players[n].alive: p.choice = n self.repeat_votes(chat_id) else: self.send_message( chat_id, "Quel giocatore non è vivo.", message_id) except (IndexError, KeyError): self.send_message(chat_id, "Quel giocatore non esiste.", message_id) else: self.send_message( chat_id, "Non fai parte di questa partita, oppure sei stato ucciso.", message_id)
import engine import pygame Game = engine.Game("img/bg/bg.jpg", fullscreen=False) Game.load_cards("img/exploding_kittens/JPEG") Game.create_deck("Draw", lambda tag: tag not in ("explosion", )) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False Game.quit()