示例#1
0
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
示例#2
0
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
示例#3
0
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
示例#4
0
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)]
示例#5
0
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 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]
示例#7
0
    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)
示例#8
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
示例#9
0
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
示例#10
0
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
示例#11
0
 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
示例#12
0
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
示例#13
0
 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()
示例#14
0
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
示例#15
0
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
示例#16
0
def match(data):
    match_data = data
    match_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/game/' + str(
        match_data['match_id']) + '/'

    challenger_code_filename = 'challenger{0}'.format(
        extension[match_data['challenger_language']])
    oppositer_code_filename = 'oppositer{0}'.format(
        extension[match_data['opposite_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 = match_data['challenger_code']
    oppositer_code = match_data['opposite_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('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,
                               placement_rule=match_data['placement'],
                               action_rule=match_data['action'],
                               ending_rule=match_data['ending'],
                               board_size=match_data['board_size'],
                               board_info=match_data['board_info'],
                               obj_num=match_data['obj_num'],
                               problem=match_data['problem'])

    winner, board_record, placement_record, result, error_msg = game_manager.play_game(
    )
    # 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)
    data = {
        "winner": winner,
        "record": board_record,
        "placement_record": placement_record,
        "result": result,
        "error_msg": error_msg
    }
    data2 = {
        "winner": winner,
        "placement_record": placement_record,
        "result": result,
        "error_msg": error_msg
    }
    print(data2)
    r = requests.patch(update_url, data=data)
    print('request ok')
示例#17
0
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()
示例#18
0
def test_check_computer():
    t = Tiles(800, 100, 90)
    gm = GameManager(t)
    assert gm.check_computer() is True
示例#19
0
文件: pyrate.py 项目: smbalf/Pyrates
    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()
示例#20
0
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)
示例#21
0
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()
示例#22
0
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)
示例#23
0
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()
示例#24
0
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()
示例#25
0
"""
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
示例#26
0
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
示例#27
0
 def _createGameManager(self):
     """Given the game manager configuration, create the game manager"""
     state = self.createState()
     return GameManager(state)
示例#28
0
文件: main.py 项目: pabloufrn/PySnake
from gamemanager import GameManager

manager = GameManager()
示例#29
0
                        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)