コード例 #1
0
def play_game(game_idx):
    was_closed = False
    step = 0
    if not os.path.isdir(str(game_idx)):
        os.mkdir(str(game_idx))
    while not was_closed:
        game = gamestate.GameState()
        button_pressed = config.play_game_button  #graphics.draw_main_menu(game)

        if button_pressed == config.play_game_button:
            game.start_pool()
            events = event.events()
            while not (events["closed"] or game.is_game_over
                       or events["quit_to_main_menu"] or step == 10):
                print(step)
                events = event.events()
                collisions.resolve_all_collisions(game.balls, game.holes,
                                                  game.table_sides)
                game.redraw_all()

                table = np.zeros((config.resolution[0], config.resolution[1]))
                for i in range(len(list(game.balls))):
                    pos = list(game.balls)[i].ball.pos
                    table[[
                        int(pos[0] + cos(i * 2 * pi / 360) * 12.5)
                        for i in range(360)
                    ], [
                        int(pos[1] + sin(i * 2 * pi / 360) * 12.5)
                        for i in range(360)
                    ]] = 1

                plt.imshow(table, cmap='gray')
                plt.savefig(str(game_idx) + '/' + str(step) + '.png')
                step += 1

                if game.all_not_moving():
                    game.check_pool_rules()
                    game.cue.make_visible(game.current_player)
                    while not (
                        (events["closed"] or events["quit_to_main_menu"])
                            or game.is_game_over) and game.all_not_moving():
                        game.redraw_all()
                        events = event.events()
                        if True:  #game.cue.is_clicked(events):
                            game.cue.cue_is_active(game, events)
                        elif game.can_move_white_ball and game.white_ball.is_clicked(
                                events):
                            game.white_ball.is_active(
                                game, game.is_behind_line_break())
            was_closed = True  #events["closed"]

        if button_pressed == config.exit_button:
            was_closed = True

    print('closing')
    pygame.quit()
    print('done')
コード例 #2
0
def iterate_until_button_press(buttons, game_state, text_ending_place,
                               text_starting_place):
    # while a button was not clicked this method checks if mouse is in the button and if it is
    # changes its colour
    button_clicked = 0
    while button_clicked == 0:
        pygame.display.update()
        user_events = event.events()
        # the first button is the title which is unclickable, thus iterating from 1 to len(buttons)
        for num in range(1, len(buttons)):
            if np.all((np.less(text_starting_place[num] - config.menu_spacing,
                               user_events["mouse_pos"]),
                       np.greater(text_ending_place[num] + config.menu_spacing,
                                  user_events["mouse_pos"]))):
                if user_events["clicked"]:
                    button_clicked = num
                else:
                    game_state.canvas.surface.blit(buttons[num][1],
                                                   text_starting_place[num])
            else:
                game_state.canvas.surface.blit(buttons[num][0],
                                               text_starting_place[num])
        if user_events["closed"] or user_events["quit_to_main_menu"]:
            button_clicked = len(buttons) - 1
    return button_clicked
コード例 #3
0
    def play(self,x,y):
        self.was_closed = False
        while not self.was_closed:
            game = gamestate.GameState()
            button_pressed = config.play_game_button
            if button_pressed == config.play_game_button:
                game.start_pool()
                events = event.events()
                self.reward=0
                while not (events["closed"] or game.is_game_over or events["quit_to_main_menu"]):
                    events = event.events()
                    self.reward=collisions.resolve_all_collisions(game.balls, game.holes, game.table_sides,self.reward)
                    
                    game.redraw_all()
                    store_ball_list=dict()
                    if game.all_not_moving():
                        
                        print("\n*****************************")
                        
                        for ball in game.balls:
                            store_ball_list[ball.number]=ball.ball.pos
                            #print("ball {} not moving : {}".format(ball.number,ball.ball.pos))
                        
                        game.check_pool_rules()
                        
                        game.cue.make_visible(game.current_player)

                        if 0 not in store_ball_list:
                            store_ball_list[0]=game.give_value()
                        #print("如果陣列中沒有白球位置請看這裡 : {}".format(game.give_value()))

                        print("all balls : ",store_ball_list)
                        print("reward : {}".format(self.reward))

                        
                        while not (
                            (events["closed"] or events["quit_to_main_menu"]) or game.is_game_over) and game.all_not_moving():
                            game.redraw_all()
                            events = event.events()
                            if 1:
                                # x=int(input("x : "))
                                # y=int(input("y : "))
                                game.cue.cue_is_active(game, events,(x,y))
                            elif game.can_move_white_ball and game.white_ball.is_clicked(events):
                                game.white_ball.is_active(game, game.is_behind_line_break())
                        self.return_command=str(self.reward)+"*"+str(self.was_closed)
                self.was_closed = True
コード例 #4
0
ファイル: ball.py プロジェクト: SavelyBerdnik/PyGame_Project
    def is_active(self, game_state, behind_separation_line=False):
        game_state.cue.make_invisible()
        events = event.events()

        while events["clicked"]:
            events = event.events()
            if np.all(np.less(config.table_margin + config.ball_radius + config.hole_radius, events["mouse_pos"])) and \
                    np.all(np.greater(config.resolution - config.table_margin - config.ball_radius - config.hole_radius,
                                      events["mouse_pos"])) and \
                    not collisions.check_if_ball_touches_balls(events["mouse_pos"], self.number, game_state.balls):
                if behind_separation_line:
                    if events["mouse_pos"][0] <= config.white_ball_initial_pos[0]:
                        self.move_to(events["mouse_pos"])
                else:
                    self.move_to(events["mouse_pos"])
            game_state.redraw_all()
        game_state.cue.make_visible(game_state.current_player)
コード例 #5
0
ファイル: cue.py プロジェクト: annaosousa/Sinuca
    def cue_is_active(self, game_state, events):
        initial_mouse_pos = events["mouse_pos"]
        initial_mouse_dist = physics.point_distance(initialinitial_mouse_pos, self.target_ball.ball.pos)
        while events["clicked"]:
            events = event.events()
            self.update_cue(game_state,initial_mouse_dist, events)
        self.draw_lines(game_state, self.target_ball, self.angle+math.pi, config.table_color)

        if self.displacement > config.ball_radius + config.cue_safe_displacement:
            self.ball_hit()
コード例 #6
0
ファイル: testengine.py プロジェクト: eirvandelden/Bomb3D
    def __init__(self, graphics, level, players, inputqueue, options):

        self.graphics = graphics
        self.inputqueue = inputqueue
        graphics.load(level.objectsUsed)
        # initialize events
        events = event.events()
        events.token = event.event("token")  # arguments: none
        events.timeout = event.event("timeout")  # arguments: gamestate, object that timed out
        events.collision = event.event("collision")  # arguments: gamestate, object1, object2
        events.playerkilled = event.event("playerkilled")  # arguments: gamestate, bomberman, explosion
        events.playerspawned = event.event("playerspawned")  # arguments: bomberman
        events.bombexplode = event.event("bombexplode")  # arguments: bombcoordinate, bombrange
        events.poweruppickup = event.event("poweruppickup")  # arguments: bombcoordinate, bombrange

        events.eMouseEvent = event.event("eMouseEvent")

        # emits as data: the message as a string, player_id as an integer.
        events.eChtMessage = event.event("eChtMessage")

        # these all emit as data: player_id as an integer.
        events.eAcceForwOn = event.event("eAcceForwOn")
        events.eAcceBackOn = event.event("eAcceBackOn")
        events.eStepLeftOn = event.event("eStepLeftOn")
        events.eStepRghtOn = event.event("eStepRghtOn")
        events.eDropBombOn = event.event("eDropBombOn")
        events.ePowerup1On = event.event("ePowerup1On")
        events.ePowerup2On = event.event("ePowerup2On")
        events.ePowerup3On = event.event("ePowerup3On")
        events.eMinimapTOn = event.event("eMinimapTOn")

        events.eAcceForwOff = event.event("eAcceForwOff")
        events.eAcceBackOff = event.event("eAcceBackOff")
        events.eStepLeftOff = event.event("eStepLeftOff")
        events.eStepRghtOff = event.event("eStepRghtOff")
        events.eDropBombOff = event.event("eDropBombOff")
        events.ePowerup1Off = event.event("ePowerup1Off")
        events.ePowerup2Off = event.event("ePowerup2Off")
        events.ePowerup3Off = event.event("ePowerup3Off")
        events.eMinimapTOff = event.event("eMinimapTOff")

        events.eNeatQuit = event.event("eNeatQuit")

        events.token.register(engine.play)

        time = options.get("time", 120)  # TODO: tijd (timeleft in dit geval dacht ik) goed regelen

        level.createLevel(self, players)
        level.loadScripts(events)
        self.graphics.initEvents(events)

        self.gamestate = gamestate.gamestate(self, level, players, events, 10, time)  # TODO: framerate fixen
        graphics.buildLists(self.gamestate)

        self.inputqueuehandler = testqhandlers.QReaderEventWriter(inputqueue, self.gamestate)
コード例 #7
0
 def is_active(self, game_state, behind_separation_line=False):
     game_state.cue.make_invisible()
     events = event.events()
     
     while events["clicked"]:
         events = event.events()
         #print("自行移動白球知道最大(x,y):",self.ball.pos)
         self.white_ball_now=self.ball.pos
         # checks if the user isn't trying to place the ball out of the table or inside another ball
         if np.all(np.less(config.table_margin + config.ball_radius + config.hole_radius, events["mouse_pos"])) and \
                 np.all(np.greater(config.resolution - config.table_margin - config.ball_radius - config.hole_radius,
                                   events["mouse_pos"])) and \
                 not collisions.check_if_ball_touches_balls(events["mouse_pos"], self.number, game_state.balls):
             if behind_separation_line:
                 if events["mouse_pos"][0] <= config.white_ball_initial_pos[0]:
                     self.move_to(events["mouse_pos"])
             else:
                 self.move_to(events["mouse_pos"])
         game_state.redraw_all()
     game_state.cue.make_visible(game_state.current_player)
コード例 #8
0
ファイル: cue.py プロジェクト: Lin1225/pool_env
    def cue_is_active(self, game_state, events, pos):
        initial_mouse_pos = events["mouse_pos"]
        initial_mouse_dist = physics.point_distance(initial_mouse_pos,
                                                    self.target_ball.ball.pos)

        while events["clicked"]:
            events = event.events()
            self.update_cue(game_state, initial_mouse_dist, events)
        # undraw leftover aiming lines
        self.draw_lines(game_state, self.target_ball, self.angle + math.pi,
                        config.table_color)

        # if self.displacement > config.ball_radius+config.cue_safe_displacement:
        k = np.array([pos[0], pos[1]])
        self.ball_hit(k)
コード例 #9
0
    def __init__(self, iterations=1000, distance=1.0, layout=LAYOUT_SPRING):
        
        self.nodes = []
        self.edges = []
        self.root  = None
        
        # Calculates positions for nodes.
        self.layout = layout_.__dict__[layout+"_layout"](self, iterations)
        self.d = node(None).r * 2.5 * distance
        
        # Hover, click and drag event handler.
        self.events = event.events(self, _ctx)
        
        # Enhanced dictionary of all styles.
        self.styles = style.styles(self)
        self.styles.append(style.style(style.DEFAULT, _ctx))
        self.alpha = 0

        # Try to specialize intensive math operations.
        try:
            import psyco
            psyco.bind(self.layout._bounds)
            psyco.bind(self.layout.iterate)
            psyco.bind(self.__or__)
            psyco.bind(cluster.flatten)
            psyco.bind(cluster.subgraph)
            psyco.bind(cluster.clique)
            psyco.bind(cluster.partition)
            psyco.bind(proximity.dijkstra_shortest_path)
            psyco.bind(proximity.brandes_betweenness_centrality)
            psyco.bind(proximity.eigenvector_centrality)
            psyco.bind(style.edge_arrow)
            psyco.bind(style.edge_label)
            #print "using psyco"
        except:
            pass

        self.times = {}
        self.times['other'] = 0.
        self.times['edges'] = 0.
        self.times['nodes'] = 0.
        self.times['events'] = 0.
        self.times['path'] = 0.
        self.times['node_ids'] = 0.
        self.times['iter'] = 0
コード例 #10
0
ファイル: __init__.py プロジェクト: shenglixu/rcommander-core
    def __init__(self, iterations=1000, distance=1.0, layout=LAYOUT_SPRING):

        self.nodes = []
        self.edges = []
        self.root = None

        # Calculates positions for nodes.
        self.layout = layout_.__dict__[layout + "_layout"](self, iterations)
        self.d = node(None).r * 2.5 * distance

        # Hover, click and drag event handler.
        self.events = event.events(self, _ctx)

        # Enhanced dictionary of all styles.
        self.styles = style.styles(self)
        self.styles.append(style.style(style.DEFAULT, _ctx))
        self.alpha = 0

        # Try to specialize intensive math operations.
        try:
            import psyco
            psyco.bind(self.layout._bounds)
            psyco.bind(self.layout.iterate)
            psyco.bind(self.__or__)
            psyco.bind(cluster.flatten)
            psyco.bind(cluster.subgraph)
            psyco.bind(cluster.clique)
            psyco.bind(cluster.partition)
            psyco.bind(proximity.dijkstra_shortest_path)
            psyco.bind(proximity.brandes_betweenness_centrality)
            psyco.bind(proximity.eigenvector_centrality)
            psyco.bind(style.edge_arrow)
            psyco.bind(style.edge_label)
            #print "using psyco"
        except:
            pass

        self.times = {}
        self.times['other'] = 0.
        self.times['edges'] = 0.
        self.times['nodes'] = 0.
        self.times['events'] = 0.
        self.times['path'] = 0.
        self.times['node_ids'] = 0.
        self.times['iter'] = 0
コード例 #11
0
ファイル: graphics.py プロジェクト: annaosousa/Sinuca
def iterate_until_button_press(buttons, game_state, text_starting_place):
    button_clicked = 0
    while button_clicked == 0:
        pygame.display.update()
        user_events = event.events()
        for num in range(1, len(buttons)):
            if np.all(
                (np.less(text_starting_place[num] - config.menu_spacing,
                         user_events["mouse_pos"]),
                 np.generate(text_ending_place[num] + config.menu_spacing,
                             user_events["mouse_pos"]))):
                if user_events["clicked"]:
                    button_clicked = num
                else:
                    game_state.canvas.surface.blit(buttons[num][1],
                                                   text_starting_place[num])
            else:
                game_state.canvas.surface.blit(buttons[num][0],
                                               text_starting_place[num])
        if user_events["closed"] or user_events["quit_to_main_menu"]:
            button_clicked = len(buttons) - 1
    return button_clicked
コード例 #12
0
ファイル: Sinuca.py プロジェクト: annaosousa/Sinuca
import pygame
import collisions
import event
import gamestate
import graphics
import config

was_closed = False

while not was_closed:
    game = gamestate.GameState()
    button_pressed = graphics.draw_main_menu(game)

    if button_pressed == config.play_game_button:
        game.start_pool()
        events = event.events()
        while not (events["closed"] or game.is_game_over
                   or events["quit_to_main_menu"]):
            events = event.events()
            collisions.resolve_all_collisions(game.balls, game.holes,
                                              game.table_sides)
            game.redraw_all()

            if game.all_not_moving():
                game.check_pool_rules()
                game.cue.make_visible(game.current_player)
                while not ((events["closed"] or events["quit_to_main_menu"])
                           or game.is_game_over) and game.all_not_moving():
                    game.redraw_all()
                    events = event.events()
                    if game.cue.is_clicked(events):
コード例 #13
0
def play_game(game_idx):
    was_closed = False
    global_step = 0
    local_step = 0
    turn = 0
    tmp_list = [[]]
    """fig = plt.figure(figsize=(config.resolution[1]/mydpi, config.resolution[0]/mydpi), dpi=mydpi)
    ax = plt.Axes(fig, [0., 0., 1., 1.])"""

    if not os.path.isdir('dataset/' + str(game_idx)):
        os.mkdir('dataset/' + str(game_idx))
        #os.mkdir('dataset/'+ str(game_idx) + '/' + str(turn))
    while not was_closed:
        game = gamestate.GameState()
        button_pressed = config.play_game_button  #graphics.draw_main_menu(game)

        if button_pressed == config.play_game_button:
            game.start_pool()
            events = event.events()
            while not (events["closed"] or game.is_game_over
                       or events["quit_to_main_menu"] or global_step == 50000):
                events = event.events()
                collisions.resolve_all_collisions(game.balls, game.holes,
                                                  game.table_sides)
                game.redraw_all()
                #table = np.zeros((config.resolution[0], config.resolution[1]))
                for i in range(len(list(game.balls))):
                    pos = list(game.balls)[i].ball.pos
                    tmp_list[-1].append(pos.copy())
                    """table[
                        [int(pos[0] + cos(i*2*pi/360)*12.5) for i in range(360)],
                        [int(pos[1] + sin(i*2*pi/360)*12.5) for i in range(360)]
                    ] = 1"""

                tmp_list.append([])
                """ax.set_axis_off()
                fig.add_axes(ax)
                ax.imshow(table, cmap='gray')
                plt.savefig('dataset/'+ str(game_idx) + '/' + str(turn) + '/'+str(local_step)+'.png')
                plt.cla()
                plt.clf()"""
                global_step += 1
                local_step += 1

                if game.all_not_moving():
                    if global_step != 1:
                        with open(
                                'dataset/' + str(game_idx) + '/' + str(turn) +
                                '_' + str(local_step) + '.pickle', "wb") as f:
                            pickle.dump(tmp_list[:-1], f)
                            tmp_list = [[]]
                        turn += 1
                        #os.mkdir('dataset/'+ str(game_idx) + '/' + str(turn))
                    local_step = 0
                    game.check_pool_rules()
                    game.cue.make_visible(game.current_player)
                    while not (
                        (events["closed"] or events["quit_to_main_menu"])
                            or game.is_game_over) and game.all_not_moving():
                        game.redraw_all()
                        events = event.events()
                        if True:  #game.cue.is_clicked(events):
                            game.cue.cue_is_active(game, events,
                                                   global_step == 1)
                        elif game.can_move_white_ball and game.white_ball.is_clicked(
                                events):
                            game.white_ball.is_active(
                                game, game.is_behind_line_break())
            was_closed = True  #events["closed"]

        if button_pressed == config.exit_button:
            was_closed = True

    print('closing')
    pygame.quit()
    print('done')
コード例 #14
0
    def __init__(self, graphics, level, players, inputqueue, options):

        self.graphics = graphics
        self.inputqueue = inputqueue
        graphics.load(level.objectsUsed)
        # initialize events
        events = event.events()
        events.token = event.event("token")  #arguments: none
        events.timeout = event.event(
            "timeout")  # arguments: gamestate, object that timed out
        events.collision = event.event(
            "collision")  # arguments: gamestate, object1, object2
        events.playerkilled = event.event(
            "playerkilled")  # arguments: gamestate, bomberman, explosion
        events.playerspawned = event.event(
            "playerspawned")  # arguments: bomberman
        events.bombexplode = event.event(
            "bombexplode")  # arguments: bombcoordinate, bombrange
        events.poweruppickup = event.event(
            "poweruppickup")  # arguments: bombcoordinate, bombrange

        events.eMouseEvent = event.event("eMouseEvent")

        # emits as data: the message as a string, player_id as an integer.
        events.eChtMessage = event.event("eChtMessage")

        # these all emit as data: player_id as an integer.
        events.eAcceForwOn = event.event("eAcceForwOn")
        events.eAcceBackOn = event.event("eAcceBackOn")
        events.eStepLeftOn = event.event("eStepLeftOn")
        events.eStepRghtOn = event.event("eStepRghtOn")
        events.eDropBombOn = event.event("eDropBombOn")
        events.ePowerup1On = event.event("ePowerup1On")
        events.ePowerup2On = event.event("ePowerup2On")
        events.ePowerup3On = event.event("ePowerup3On")
        events.eMinimapTOn = event.event("eMinimapTOn")

        events.eAcceForwOff = event.event("eAcceForwOff")
        events.eAcceBackOff = event.event("eAcceBackOff")
        events.eStepLeftOff = event.event("eStepLeftOff")
        events.eStepRghtOff = event.event("eStepRghtOff")
        events.eDropBombOff = event.event("eDropBombOff")
        events.ePowerup1Off = event.event("ePowerup1Off")
        events.ePowerup2Off = event.event("ePowerup2Off")
        events.ePowerup3Off = event.event("ePowerup3Off")
        events.eMinimapTOff = event.event("eMinimapTOff")

        events.eNeatQuit = event.event("eNeatQuit")

        events.token.register(engine.play)

        time = options.get(
            "time",
            120)  #TODO: tijd (timeleft in dit geval dacht ik) goed regelen

        level.createLevel(self, players)
        level.loadScripts(events)
        self.graphics.initEvents(events)

        self.gamestate = gamestate.gamestate(self, level, players, events, 10,
                                             time)  #TODO: framerate fixen
        graphics.buildLists(self.gamestate)

        self.inputqueuehandler = testqhandlers.QReaderEventWriter(
            inputqueue, self.gamestate)