def test_islegal(): t = Tiles(800, 100, 90) gm = GameManager(t) assert gm.islegal(gm.tiles.player_tiles, gm.tiles.computer_tiles, 0, 0) == [] assert gm.islegal(gm.tiles.player_tiles, gm.tiles.computer_tiles, 3, 2) == [(3, 3)]
def setUp(self): self.gm = GameManager() self.gm.add_player('krol_julian', MockHandler()) self.gm.add_player('martarzy', MockHandler()) self.gm.add_player('the_bad', MockHandler()) self.p0 = self.gm.players[0] self.p1 = self.gm.players[1] self.p2 = self.gm.players[2]
class TutorialApp(App): sm = ObjectProperty() history = ListProperty() prev = StringProperty() def build(self): self.sm = GameManager(transition=NoTransition()) self.sm.switch_to_solo_menu() #default the AddCard's deck selecter button to decks[1]'s name self.sm.ids.s3.ids.butd.text = self.sm.manager.implementation.decks[1].find_attribute("name").attribute_value_ self.history.append('main_menu') #bind all the screes on_enter to record_history for a in self.sm.screens: a.bind(on_enter=self.record_history) self.bind(on_start=self.post_build_init) #Window.softinput_mode = 'pan' return self.sm def post_build_init(self, ev): if platform == 'android': import android android.map_key(android.KEYCODE_BACK, 1000) android.map_key(android.KEYCODE_MENU, 1001) win = self._app_window win.bind(on_keyboard=self._key_handler) def _key_handler(self, *args): key = args[1] #check if the user presses esc or android's back button if key in (1000, 27): #first check if the keyboard is on since its the first thing we want to remove if Window.keyboard_height is 0: #check if there is any modalview opened if self.sm.modal_state is 1: #check if we are at the last screen so we can exit the app if len(self.history) == 1: self.stop() self.prev = self.history[len(self.history) - 2] #delete the current screen del self.history[-1] #switch to the previous screen self.sm.current = self.prev return True else: self.sm.modal_state.dismiss() self.sm.modal_state = 1 else: Window.release_all_keyboards() #once we eneter a screen we are adding it to the history list def record_history(self, *args, **kwargs): #make sure we dont loop between 2 screens if self.prev != self.sm.current: self.history.append(self.sm.current)
class TutorialApp(App): sm = ObjectProperty() history = ListProperty() prev = StringProperty() def build(self): self.sm = GameManager(transition=NoTransition()) self.sm.switch_to_solo_menu() #default the AddCard's deck selecter button to decks[1]'s name self.sm.ids.s3.ids.butd.text = self.sm.manager.implementation.decks[ 1].find_attribute("name").attribute_value_ self.history.append('main_menu') #bind all the screes on_enter to record_history for a in self.sm.screens: a.bind(on_enter=self.record_history) self.bind(on_start=self.post_build_init) #Window.softinput_mode = 'pan' return self.sm def post_build_init(self, ev): if platform == 'android': import android android.map_key(android.KEYCODE_BACK, 1000) android.map_key(android.KEYCODE_MENU, 1001) win = self._app_window win.bind(on_keyboard=self._key_handler) def _key_handler(self, *args): key = args[1] #check if the user presses esc or android's back button if key in (1000, 27): #first check if the keyboard is on since its the first thing we want to remove if Window.keyboard_height is 0: #check if there is any modalview opened if self.sm.modal_state is 1: #check if we are at the last screen so we can exit the app if len(self.history) == 1: self.stop() self.prev = self.history[len(self.history) - 2] #delete the current screen del self.history[-1] #switch to the previous screen self.sm.current = self.prev return True else: self.sm.modal_state.dismiss() self.sm.modal_state = 1 else: Window.release_all_keyboards() #once we eneter a screen we are adding it to the history list def record_history(self, *args, **kwargs): #make sure we dont loop between 2 screens if self.prev != self.sm.current: self.history.append(self.sm.current)
def build(self): self.sm = GameManager(transition=NoTransition()) self.sm.switch_to_solo_menu() #default the AddCard's deck selecter button to decks[1]'s name self.sm.ids.s3.ids.butd.text = self.sm.manager.implementation.decks[ 1].find_attribute("name").attribute_value_ self.history.append('main_menu') #bind all the screes on_enter to record_history for a in self.sm.screens: a.bind(on_enter=self.record_history) self.bind(on_start=self.post_build_init) #Window.softinput_mode = 'pan' return self.sm
def test_computer_make_move(): # test case that no legal move game = GameManager(2, 2, 80) game.turn = 1 game.computer_make_move() assert game.turn == 0 # test case that has legal move game = GameManager(6, 6, 80) game.turn = 1 game.computer_make_move() assert game.tiles_list[1][3].color == game.WHITE assert game.tiles_list[2][3].color == game.WHITE assert game.turn == 0
def test_forecast(): t = Tiles(800, 100, 90) gm = GameManager(t) gm.player_make_move(250, 350) gm.computer_make_move() gm.player_make_move(350, 250) mock_squares = copy.deepcopy(gm.tiles.squares) mock_player_tiles = copy.deepcopy(gm.tiles.player_tiles) mock_computer_tiles = copy.deepcopy(gm.tiles.computer_tiles) assert gm.forecast(mock_squares, mock_player_tiles, mock_computer_tiles, [(3, 2), (4, 3)], 4, 2) == 9
def __init__(self, master): self.root = master self.root.withdraw() self.root.iconbitmap(RAVEN_ICON) self.root.title('Raven ' + VERSION) self.root.protocol('WM_DELETE_WINDOW', self._on_close) self.thinkTime = IntVar(value=5) self.manager = GameManager(root=self.root, parent=self) self.menubar = tk.Menu(self.root) self.create_game_menu() self.create_options_menu() self.create_help_menu() self.root.config(menu=self.menubar) CenteredWindow.__init__(self, self.root) self.root.deiconify()
def test_constructor(): game = GameManager(6, 6, 80) assert game.TC == 6 assert game.TR == 6 assert game.CW == 80 assert game.turn == 0 assert game.end is False
def test_player_make_move(): game = GameManager(6, 6, 80) # test case that has legal move game.player_make_move(200, 100) assert game.tiles_list[2][1].color == game.BLACK assert game.tiles_list[2][2].color == game.BLACK assert game.turn == 1 # test case that no legal move game = GameManager(2, 2, 80) game.player_make_move(70, 70) assert game.turn == 1
def __init__(self, fitness_func): class ThinkTime: def get(self): return 0.01 self.thinkTime = ThinkTime() self.manager = GameManager(root=None, parent=self, training=True, fitness=fitness_func)
def test_constructor(): t = Tiles(800, 100, 90) gm = GameManager(t) assert gm.AROUND == [(0, -1), (0, 1), (1, 0), (-1, 0), (1, 1), (-1, -1), (1, -1), (-1, 1)] assert gm.player_turn is True assert gm.tiles.SQUARES_NUM == 8 assert gm.tiles.white_num == 2 assert gm.NUM_OF_TOTAL_SQUARES == 64 assert gm.CORNERS == [(0, 0), (0, 7), (7, 0), (7, 7)] assert gm.num_of_tiles == 4
def test_code(data): test_data = data test_dir = os.getcwd() # os.path.join(os.getcwd(), 'match') extension = { '': '', 'C': '.c', 'C++': '.cpp', 'PYTHON': '.py', 'JAVA': '.java' } update_url = 'http://203.246.112.32:8000/api/v1/code/' + str( test_data['challenger_code_id']) + '/' # code_filename = 'challenger{0}'.format(extension[test_data['challenger_language']]) code_filename = 'challenger.py' # code_path = os.path.join(test_dir, code_filename) # code = test_data['challenger_code'] # with open(code_path, 'w') as f: # f.write(code) challenger = UserProgram('challenger', test_data['challenger'], test_data['challenger_language'], test_dir, code_filename) game_manager = GameManager(challenger=challenger, oppositer=challenger, placement_rule=test_data['placement'], action_rule=test_data['action'], ending_rule=test_data['ending'], board_size=test_data['board_size'], board_info=test_data['board_info'], obj_num=test_data['obj_num'], problem=test_data['problem']) _, _, _, result, _ = game_manager.play_game() print('result :', result) available = False if result == 'finish': available = True
def build(self): self.sm = GameManager(transition=NoTransition()) self.sm.switch_to_solo_menu() #default the AddCard's deck selecter button to decks[1]'s name self.sm.ids.s3.ids.butd.text = self.sm.manager.implementation.decks[1].find_attribute("name").attribute_value_ self.history.append('main_menu') #bind all the screes on_enter to record_history for a in self.sm.screens: a.bind(on_enter=self.record_history) self.bind(on_start=self.post_build_init) #Window.softinput_mode = 'pan' return self.sm
def data_formatting(test_data, test_dir, code_filename): challenger = UserProgram('challenger', test_data['challenger'], test_data['challenger_language'], test_dir, code_filename) game_manager = GameManager(challenger=challenger, oppositer=challenger, rule=test_data['rule'], board_size=test_data['board_size'], board_info=test_data['board_info'], problem=json_data['problem']) return game_manager
def test_computer_make_move(): t = Tiles(800, 100, 90) gm = GameManager(t) gm.player_make_move(250, 350) gm.computer_make_move() assert gm.num_of_tiles == 6 assert gm.player_turn is True assert gm.tiles.white_num == 3
def __init__(self, master): self.root = master self.root.withdraw() # This useless thing breaks linux... comment it out.. # self.root.iconbitmap(RAVEN_ICON) self.root.title('Raven ' + VERSION) self.root.protocol('WM_DELETE_WINDOW', self._on_close) self.thinkTime = IntVar(value=1) self.manager = GameManager(root=self.root, parent=self, training=False) self.menubar = tk.Menu(self.root) self.create_game_menu() self.create_options_menu() self.create_help_menu() self.root.config(menu=self.menubar) CenteredWindow.__init__(self, self.root) self.root.deiconify()
def test_player_make_move(): t = Tiles(800, 100, 90) gm = GameManager(t) # when the player makes an illegal move gm.player_make_move(1, 1) assert gm.num_of_tiles == 4 assert gm.tiles.white_num == 2 # when the player makes a legal move gm.player_make_move(250, 350) assert gm.num_of_tiles == 5 assert gm.tiles.white_num == 1
def match_data_formatting(match_data, match_dir, challenger_code_filename, oppositer_code_filename): challenger = UserProgram('challenger', match_data['challenger'], match_data['challenger_language'], match_dir, challenger_code_filename) oppositer = UserProgram('opposite', match_data['opposite'], match_data['opposite_language'], match_dir, oppositer_code_filename) game_manager = GameManager(challenger=challenger, oppositer=oppositer, rule=match_data['rule'], board_size=match_data['board_size'], board_info=match_data['board_info'], problem=json_data['problem']) return game_manager
def welcome_message(): print(WELCOME_MESSAGE) def get_firm_name(): return input(GET_FIRM_NAME) def get_starting_options(): starting_options = input(GET_STARTING_OPTIONS) if starting_options == "1": return (1000000, 250000, 0) else: return (0, 0, 5) # Start Game welcome_message() firm_name = get_firm_name() cash, debt, cannons = get_starting_options() game = GameManager(firm_name=firm_name, cash=cash, cannons=cannons, debt=debt, shiphold=100) game.StartUp()
def test_check_computer(): t = Tiles(800, 100, 90) gm = GameManager(t) assert gm.check_computer() is True
vessel_name = input("What shall you name your vessel?:\nThe ") return vessel_name # SHOULD ADD "ARE YOU SURE?" HERE def get_starting_options(): starting_options = input( "How do you wish to start? [1] Cash & No Cannons [2] Cannons & No Cash.\n" ) if starting_options == "1": opts = (250, 0) else: opts = (0, 5) return opts ##### GAME OPTIONS ##### welcome_message() pirate_name = get_pirate_name() vessel_name = get_vessel_name() cash, cannons = get_starting_options() game = GameManager(name=pirate_name, vessel=vessel_name, cash=cash, cannons=cannons, shiphold=500, shiphealth=100) ##### START THE GAME! ##### game.start_up()
class ScenariosAfterStart(unittest.TestCase): def setUp(self): self.gm = GameManager() self.gm.add_player('krol_julian', MockHandler()) self.gm.add_player('martarzy', MockHandler()) self.gm.add_player('the_bad', MockHandler()) self.p0 = self.gm.players[0] self.p1 = self.gm.players[1] self.p2 = self.gm.players[2] def test_get_players_number(self): self.assertEqual(self.gm.get_players_number(), 3) def test_after_drawing_all_chance_cards_no_get_out(self): for _ in range(20): self.gm.chance_stack.get_card() cards = [self.gm.chance_stack.get_card() for _ in range(16)] get_out_cards = [card for card in cards if card['action'] == 'getOut'] self.assertEqual(len(get_out_cards), 0) def test_add_cash(self): self.gm.add_cash(self.p0, 200) self.assertEqual(self.p0.cash, 1700) def test_move_with_crossing_the_start(self): self.gm.move(self.p0, 20) # Free parking field self.gm.move(self.p0, 20) # Again on Start self.assertEqual(self.p0.cash, 1900) self.assertEqual(self.p0.field_no, 0) def test_remove_player(self): self.gm.remove_player('martarzy') self.assertEqual(len(self.gm.players), 2) self.assertEqual(self.p0.name, 'krol_julian') self.assertEqual(self.gm.players[1].name, 'the_bad') def test_start_when_players_ready(self): for i in range(3): self.gm.ready(self.gm.players[i]) self.assertEqual(self.gm.turn, 0) def test_game_over_when_two_players_bankrupted(self): self.gm.bankrupt(self.p0) self.gm.bankrupt(self.gm.players[2]) self.assertTrue(self.p0.bankrupt) self.assertFalse(self.gm.players[1].bankrupt) self.assertTrue(self.gm.players[2].bankrupt) def test_nobody_owns_bankrupts_fields(self): self.gm.move(self.gm.players[1], 1) self.gm.buy_field(self.gm.players[1]) self.gm.bankrupt(self.gm.players[1]) self.assertIsNone(self.gm.fields[1].owner) def test_get_out_of_jail_with_card(self): self.p0.get_out_cards_no = 1 self.p0.goto_jail() self.gm.get_out_of_jail(self.p0, 'useCard') self.assertEqual(self.p0.get_out_cards_no, 0) self.assertFalse(self.p0.in_jail) def test_go_to_jail_after_staying_on_field_30(self): self.gm.move(self.p0, 30) self.assertTrue(self.p0.in_jail) self.assertEqual(self.p0.field_no, 10) def test_get_out_of_jail_paying(self): self.p0.goto_jail() self.gm.get_out_of_jail(self.p0, 'pay') self.assertEqual(self.p0.cash, 1450) def test_not_existing_message(self): self.gm.next_turn() self.gm.on_message('krol_julian', {'message': 'notExistingType'}) self.assertRaises(KeyError) def test_stay_on_railroad(self): self.gm.move(self.p0, 5) self.gm.buy_field(self.p0) self.gm.move(self.p1, 5) self.assertEqual(self.p0.cash, 1325) self.assertEqual(self.p1.cash, 1475) def test_simple_trade_accepted(self): self.gm.move(self.p0, 5) self.gm.buy_field(self.p0) p0_cash_before = self.p0.cash p1_cash_before = self.p1.cash trade = Trade(self.p0, self.p1, [5], 0, [], 400) self.gm.trade_offer(trade) self.assertEqual(self.gm.trade, trade) self.gm.trade_acceptance(True) p0_cash_after = self.p0.cash p1_cash_after = self.p1.cash p0_cash_diff = p0_cash_after - p0_cash_before p1_cash_diff = p1_cash_after - p1_cash_before self.assertEqual(p0_cash_diff, 400) self.assertEqual(p1_cash_diff, -400) self.assertEqual(self.gm.fields[5].owner, self.p1) def test_mortgage(self): self.gm.move(self.p0, 5) self.gm.buy_field(self.p0) self.gm.mortgage(self.p0, 5) self.assertEqual(self.p0.cash, 1400) self.assertTrue(self.gm.fields[5].mortgaged) def test_unmortgage(self): self.gm.move(self.p0, 5) self.gm.buy_field(self.p0) cash_before = self.p0.cash self.gm.mortgage(self.p0, 5) self.gm.unmortgage(self.p0, 5) cash_after = self.p0.cash diff = cash_after - cash_before self.assertEqual(diff, -10) self.assertFalse(self.gm.fields[5].mortgaged)
""" main module """ import time import pygame from gamemanager import GameManager GAME = GameManager() FPS_TIME = 0.0 TIME_DELTA = 0.01 CURRENT_TIME = time.clock() ACCUMULATOR = 0.0 NEW_TIME = 0 while not GAME.quit(): NEW_TIME = time.clock() FRAME_TIME = NEW_TIME - CURRENT_TIME CURRENT_TIME = NEW_TIME ACCUMULATOR += FRAME_TIME while ACCUMULATOR >= TIME_DELTA: for event in pygame.event.get(): GAME.input(event) GAME.update(TIME_DELTA) ACCUMULATOR -= TIME_DELTA FPS_TIME += TIME_DELTA GAME.render() NEW_TIME += 1
class MainFrame(object, CenteredWindow): def __init__(self, master): self.root = master self.root.withdraw() # This useless thing breaks linux... comment it out.. # self.root.iconbitmap(RAVEN_ICON) self.root.title('Raven ' + VERSION) self.root.protocol('WM_DELETE_WINDOW', self._on_close) self.thinkTime = IntVar(value=1) self.manager = GameManager(root=self.root, parent=self, training=False) self.menubar = tk.Menu(self.root) self.create_game_menu() self.create_options_menu() self.create_help_menu() self.root.config(menu=self.menubar) CenteredWindow.__init__(self, self.root) self.root.deiconify() def _on_close(self): if self.manager.view.is_dirty(): msg = 'Do you want to save your changes before exiting?' result = askyesnocancel(TITLE, msg) if result == True: self.manager.save_game() elif result == None: return self.root.destroy() def set_title_bar_filename(self, filename=None): if not filename: self.root.title(TITLE) else: self.root.title(TITLE + ' - ' + os.path.basename(filename)) def undo_all_moves(self, *args): self.stop_processes() self.manager.model.undo_all_moves(None, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def redo_all_moves(self, *args): self.stop_processes() self.manager.model.redo_all_moves(None, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def undo_single_move(self, *args): self.stop_processes() self.manager.model.undo_move(None, None, True, True, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def redo_single_move(self, *args): self.stop_processes() annotation = self.manager.view.get_annotation() self.manager.model.redo_move(None, None, annotation) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def create_game_menu(self): game = Menu(self.menubar, tearoff=0) game.add_command(label='New game', underline=0, command=self.manager.new_game) game.add_command(label='Open game ...', underline=0, command=self.manager.open_game) game.add_separator() game.add_command(label='Save game', underline=0, command=self.manager.save_game) game.add_command(label='Save game As ...', underline=10, command=self.manager.save_game_as) game.add_separator() game.add_command(label='Set up Board ...', underline=7, command=self.show_setup_board_dialog) game.add_command(label='Flip board', underline=0, command=self.flip_board) game.add_separator() game.add_command(label='Exit', underline=0, command=self._on_close) self.menubar.add_cascade(label='Game', menu=game) def create_options_menu(self): options = Menu(self.menubar, tearoff=0) think = Menu(options, tearoff=0) think.add_radiobutton(label="1 second", underline=None, command=self.set_think_time, variable=self.thinkTime, value=1) think.add_radiobutton(label="2 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=2) think.add_radiobutton(label="5 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=5) think.add_radiobutton(label="10 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=10) think.add_radiobutton(label="30 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=30) think.add_radiobutton(label="1 minute", underline=None, command=self.set_think_time, variable=self.thinkTime, value=60) options.add_cascade(label='CPU think time', underline=0, menu=think) options.add_separator() options.add_command(label='Preferences ...', underline=0, command=self.show_preferences_dialog) self.menubar.add_cascade(label='Options', menu=options) def create_help_menu(self): helpmenu = Menu(self.menubar, tearoff=0) helpmenu.add_command(label='About Raven ...', underline=0, command=self.show_about_box) self.menubar.add_cascade(label='Help', menu=helpmenu) def stop_processes(self): # stop any controller processes from making moves self.manager.model.curr_state.ok_to_move = False self.manager._controller1.stop_process() self.manager._controller2.stop_process() def show_about_box(self): AboutBox(self.root, 'About Raven') def show_setup_board_dialog(self): self.stop_processes() dlg = SetupBoard(self.root, 'Set up board', self.manager) self.manager.set_controllers() self.root.focus_set() self.manager.turn_finished() def show_preferences_dialog(self): font, size = get_preferences_from_file() dlg = PreferencesDialog(self.root, 'Preferences', font, size) if dlg.result: self.manager.view.init_font_sizes(dlg.font, dlg.size) self.manager.view.init_tags() write_preferences_to_file(dlg.font, dlg.size) def set_think_time(self): self.manager._controller1.set_search_time(self.thinkTime.get()) self.manager._controller2.set_search_time(self.thinkTime.get()) def flip_board(self): if self.manager.model.to_move == BLACK: self.manager._controller1.remove_highlights() else: self.manager._controller2.remove_highlights() self.manager.view.flip_board(not self.manager.view.flip_view) if self.manager.model.to_move == BLACK: self.manager._controller1.add_highlights() else: self.manager._controller2.add_highlights()
def play_with_me(data): json_data = data pwm_dir = os.getcwd() extension = { '': '', 'C': '.c', 'C++': '.cpp', 'PYTHON': '.py', 'JAVA': '.java' } code_filename = 'challenger{0}'.format( extension[json_data['challenger_language']]) # code_filename = 'challenger.py' code_path = os.path.join(pwm_dir, code_filename) placement_path = os.path.join(pwm_dir, 'placement.txt') code = json_data['challenger_code'] placement = json_data['placement_info'] # placement = '0 4 > 0 5' with open(code_path, 'w') as f: f.write(code) with open(placement_path, 'w') as f: f.write(placement) challenger = UserProgram('challenger', json_data['challenger'], json_data['challenger_language'], pwm_dir, code_filename) game_manager = GameManager(challenger=challenger, oppositer=challenger, placement_rule=json_data['placement'], action_rule=json_data['action'], ending_rule=json_data['ending'], board_size=json_data['board_size'], board_info=json_data['board_info'], obj_num=json_data['obj_num'], problem=json_data['problem']) result, winner, board_record, placement_code = game_manager.play_with_me( placement) r = redis.StrictRedis(host="192.168.23.13", port=6379, db=0) dict_name = str(json_data['challenger']) + '_' + str( json_data['challenger_code_id']) while r.exists(dict_name) == 1: pass result_dict = { 'result': result, 'winner': winner, 'board_record': board_record, 'placement_code': placement_code, 'time': time.strftime('%m-%d-%H-%M-%S', time.localtime(time.time())) } print(result_dict) json_result_dict = json.dumps(result_dict, ensure_ascii=False).encode('utf-8') r.set(dict_name, json_result_dict)
def get_firm_name(): # firm_name = input("Please enter your name: ") return "Testing Firm" def get_starting_options(): starting_options = "1" if starting_options == "1": opts = (2500, 250, 0) else: opts = (0, 0, 5) return opts # Create Products # GEt Game Options welcome_message() firm_name = get_firm_name() cash, debt, cannons = get_starting_options() game = GameManager(shiphold=100, name=firm_name, cash=cash, debt=debt, cannons=cannons) # Start up Game game.StartUp()
class MainFrame(object, CenteredWindow): def __init__(self, master): self.root = master self.root.withdraw() self.root.iconbitmap(RAVEN_ICON) self.root.title('Raven ' + VERSION) self.root.protocol('WM_DELETE_WINDOW', self._on_close) self.thinkTime = IntVar(value=5) self.manager = GameManager(root=self.root, parent=self) self.menubar = tk.Menu(self.root) self.create_game_menu() self.create_options_menu() self.create_help_menu() self.root.config(menu=self.menubar) CenteredWindow.__init__(self, self.root) self.root.deiconify() def _on_close(self): if self.manager.view.is_dirty(): msg = 'Do you want to save your changes before exiting?' result = askyesnocancel(TITLE, msg) if result: self.manager.save_game() elif result is None: return self.root.destroy() def set_title_bar_filename(self, filename=None): if not filename: self.root.title(TITLE) else: self.root.title(TITLE + ' - ' + os.path.basename(filename)) def undo_all_moves(self, *args): self.stop_processes() self.manager.model.undo_all_moves(None, self.manager.view.get_annotation()) self.manager.controller1.remove_highlights() self.manager.controller2.remove_highlights() self.manager.view.update_statusbar() def redo_all_moves(self, *args): self.stop_processes() self.manager.model.redo_all_moves(None, self.manager.view.get_annotation()) self.manager.controller1.remove_highlights() self.manager.controller2.remove_highlights() self.manager.view.update_statusbar() def undo_single_move(self, *args): self.stop_processes() self.manager.model.undo_move(None, None, True, True, self.manager.view.get_annotation()) self.manager.controller1.remove_highlights() self.manager.controller2.remove_highlights() self.manager.view.update_statusbar() def redo_single_move(self, *args): self.stop_processes() annotation = self.manager.view.get_annotation() self.manager.model.redo_move(None, None, annotation) self.manager.controller1.remove_highlights() self.manager.controller2.remove_highlights() self.manager.view.update_statusbar() def create_game_menu(self): game = Menu(self.menubar, tearoff=0) game.add_command(label='New game', underline=0, command=self.manager.new_game) game.add_command(label='Open game ...', underline=0, command=self.manager.open_game) game.add_separator() game.add_command(label='Save game', underline=0, command=self.manager.save_game) game.add_command(label='Save game As ...', underline=10, command=self.manager.save_game_as) game.add_separator() game.add_command(label='Set up Board ...', underline=7, command=self.show_setup_board_dialog) game.add_command(label='Flip board', underline=0, command=self.flip_board) game.add_separator() game.add_command(label='Exit', underline=0, command=self._on_close) self.menubar.add_cascade(label='Game', menu=game) def create_options_menu(self): options = Menu(self.menubar, tearoff=0) think = Menu(options, tearoff=0) think.add_radiobutton(label="1 second", underline=None, command=self.set_think_time, variable=self.thinkTime, value=1) think.add_radiobutton(label="2 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=2) think.add_radiobutton(label="5 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=5) think.add_radiobutton(label="10 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=10) think.add_radiobutton(label="30 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=30) think.add_radiobutton(label="1 minute", underline=None, command=self.set_think_time, variable=self.thinkTime, value=60) options.add_cascade(label='CPU think time', underline=0, menu=think) options.add_separator() options.add_command(label='Preferences ...', underline=0, command=self.show_preferences_dialog) self.menubar.add_cascade(label='Options', menu=options) def create_help_menu(self): helpmenu = Menu(self.menubar, tearoff=0) helpmenu.add_command(label='About Raven ...', underline=0, command=self.show_about_box) self.menubar.add_cascade(label='Help', menu=helpmenu) def stop_processes(self): # stop any controller processes from making moves self.manager.model.curr_state.ok_to_move = False self.manager.controller1.stop_process() self.manager.controller2.stop_process() def show_about_box(self): AboutBox(self.root, 'About Raven') def show_setup_board_dialog(self): self.stop_processes() dlg = SetupBoard(self.root, 'Set up board', self.manager) self.manager.set_controllers() self.root.focus_set() self.manager.turn_finished() def show_preferences_dialog(self): font, size = get_preferences_from_file() dlg = PreferencesDialog(self.root, 'Preferences', font, size) if dlg.result: self.manager.view.init_font_sizes(dlg.font, dlg.size) self.manager.view.init_tags() write_preferences_to_file(dlg.font, dlg.size) def set_think_time(self): self.manager.controller1.search_time = self.thinkTime.get() self.manager.controller2.search_time = self.thinkTime.get() def flip_board(self): if self.manager.model.to_move == BLACK: self.manager.controller1.remove_highlights() else: self.manager.controller2.remove_highlights() self.manager.view.flip_board(not self.manager.view.flip_view) if self.manager.model.to_move == BLACK: self.manager.controller1.add_highlights() else: self.manager.controller2.add_highlights()
def _createGameManager(self): """Given the game manager configuration, create the game manager""" state = self.createState() return GameManager(state)
required=True, choices=list(games.keys()), help='the game file to be used') parser.add_argument('-sc', '--startclock', dest='startclock', type=int, default=DEFAULT_STARTCLOCK, help='seconds between start and play messages') parser.add_argument('-pc', '--playclock', dest='playclock', type=int, default=DEFAULT_PLAYCLOCK, help='seconds between play messages') parser.add_argument('-pl', '--players', dest='players', type=player, nargs='+', required=True, help='players that will play the game') args = parser.parse_args() """""" """""" """ RUN GAMEMANAGER """ """""" """""" manager = GameManager(args.port) matchID = manager.setup_match(games[args.game], args.players, args.startclock, args.playclock) manager.run_match(matchID)
def main(): pygame.init() pygame.font.init() manager = GameManager() manager.run_game()
def begin_game(): pygame.init() screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH) pygame.display.set_caption("Text Adventure!") manager = GameManager(screen) manager.run_game()
def test_iscorner(): t = Tiles(800, 100, 90) gm = GameManager(t) assert gm.iscorner(0, 0) is True assert gm.iscorner(1, 1) is False
from gamemanager import GameManager import pygame pygame.init() if __name__ == "__main__": print("Creating game object...") gm = GameManager() print("Done. Starting run method") gm.start_screen() gm.game()
def match(match_data): match_dir = os.getcwd() # os.path.join(os.getcwd(), 'match') extension = { '': '', 'C': '.c', 'C++': '.cpp', 'PYTHON': '.py', 'JAVA': '.java' } # update_url = 'http://127.0.0.1:8000/api/v1/game/' + match_data['match_id'] challenger_code_filename = 'challenger{0}'.format( extension[match_data['challenger_language']]) oppositer_code_filename = 'oppositer{0}'.format( extension[match_data['oppositer_language']]) challenger_code_path = os.path.join(match_dir, challenger_code_filename) oppositer_code_path = os.path.join(match_dir, oppositer_code_filename) # challenger_code = select_code(match_data['challenger'], match_data['problem']) # oppositer_code = select_code(match_data['oppositer'], match_data['problem']) challenger_code = match_data['challenger_code'] oppositer_code = match_data['oppositer_code'] with open(challenger_code_path, 'w') as f: f.write(challenger_code) with open(oppositer_code_path, 'w') as f: f.write(oppositer_code) challenger = UserProgram(match_data['challenger'], match_data['challenger_language'], match_dir, challenger_code_filename) oppositer = UserProgram(match_data['oppositer'], match_data['oppositer_language'], match_dir, oppositer_code_filename) game_manager = GameManager(challenger=challenger, oppositer=oppositer, placement_rule=match_data['placement'], action_rule=match_data['action'], ending_rule=match_data['ending'], turn=match_data['turn'], board_size=match_data['board_size'], board_info=match_data['board_info'], obj_num=match_data['obj_num']) match_result, board_record, placement_record = game_manager.play_game() req = requests.put(update_url, data={ 'match_result': match_result, 'board_record': board_record, 'placement_record': placement_record }) # with open('result.txt', 'w') as f: # f.write(match_result) # with open('result.txt', 'a') as f: # f.write(board_record) # with open('result.txt', 'a') as f: # f.write(placement_record) # update match data update_match_data(match_result, board_record, placement_record)
def Tetris(target): gameboard = np.array(target) game = GameManager(gameboard) # # # Viz Stuff # # wrong_list = checkshape(solution) # Ty_len = len(target) # Tx_len = len(target[0]) # Sy_len = len(target) # Sx_len = len(target[0]) # # fig, (ax1, ax2) = plt.subplots(1, 2) # Create figure and axes # im = Image.new('RGB', (Tx_len, Ty_len), (255, 255, 255)) # white background-image # dr = ImageDraw.Draw(im) # ax1.imshow(im) # Display the background-image # ax2.imshow(im) # # # -------------------- Target Display ---------------------- # for y in range(Ty_len): # row = target[y] # for x in range(Tx_len): # if row[x] == 1: # ax1.add_patch(patches.Rectangle((x, y), 0.88, 0.88, color='b')) # draw a block # ax1.set_title('The Display of Task') # ax1.set_xlim([-1, Tx_len + 1]) # ax1.set_ylim([-1, Ty_len + 1]) # ax1.invert_yaxis() # # ax2.set_title('The Display of Solutioin') # ax2.set_xlim([-1, Sx_len + 1]) # ax2.set_ylim([-1, Sy_len + 1]) # ax2.invert_yaxis() # # # plt.draw() # # plt.pause(5) # plt.draw() # plt.pause(10) while not game.done(): greedy_search(game) # # solution = game.getSolution() # # --------------- Solution Display ---------------------- # def get_color(num): # generate a random color # np.random.seed(num) # c = list(np.random.rand(3)) # c.append(1.0) # return tuple(c) # # wrong_label_count = {} # for y in range(Sy_len): # row = solution[y] # for x in range(Sx_len): # shape, num = row[x] # if shape != 0: # ax2.add_patch(patches.Rectangle((x, y), 0.88, 0.88, color=get_color(num))) # draw a block # # if num in wrong_list: # # if wrong_label_count.setdefault(num, 0) == 0: # # ax2.text(x, y + 0.8, '{}'.format(num)) # add label to blocks that have wrong shapes # # wrong_label_count[num] += 1 # plt.draw() # plt.pause(0.01) # # valid, missing, excess, error_pieces = check_solution(target, game.getSolution()) # # total_blocks = sum([sum(row) for row in target]) # total_blocks_solution = total_blocks - missing + excess # # s1 = "The number of blocks in the TARGET is {:.0f}.".format(total_blocks) # s2 = "The number of blocks in the SOLUTION is {:.0f}.".format(total_blocks_solution) # s3 = "There are {} MISSING blocks ({:.4f}%) and {} EXCESS blocks ({:.4f}%).\n".format \ # (missing, 100 * missing / total_blocks, excess, 100 * excess / total_blocks) # # ax2.annotate(s1, (0,0), (0, -20), xycoords='axes fraction', textcoords='offset points', va='top') # ax2.annotate(s2, (0,0), (0, -30), xycoords='axes fraction', textcoords='offset points', va='top') # ax2.annotate(s3, (0,0), (0, -40), xycoords='axes fraction', textcoords='offset points', va='top') # # plt.draw() # plt.pause(10) return game.getSolution()