Beispiel #1
0
 def __init__(self, withGrapics=True):
     self.bestbest = 0
     self.done = False
     self.pool = Pool(Config.WIDTH, Config.HEIGHT, self.callback)
     self.graphics = Graphics()
     if withGrapics:
         self.graphics.init("PoolGame", Config.SIZE)
Beispiel #2
0
    def play_game(self):
        game = Game('X', 'O')
        player = Player()

        sock = socket.socket()
        sock.bind(("", 1024))
        sock.listen(1)
        conn, addr = sock.accept()

        pygame.init()
        graphics = Graphics()
        pygame.display.set_caption("Reversi Game")

        done = False

        clock = pygame.time.Clock()

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                    conn.close()
                elif event.type == pygame.MOUSEBUTTONDOWN and game.move_first:
                    pos = pygame.mouse.get_pos()
                    column = pos[0] // (graphics.width + graphics.margin)
                    row = pos[1] // (graphics.height + graphics.margin)
                    if game.in_grid(row, column)\
                            and (game.grid[row][column] == ''):
                        if player.do_correct_move_player(game, row, column,
                                                         game.player,
                                                         game.rival)\
                                is not False:
                            game.move_first = False
                            x = '{0} {1}'.format(column, row)
                            conn.send(x.encode("utf-8"))
                elif not game.move_first:
                    data = conn.recv(16384)
                    udata = data.decode('utf-8')
                    arr = udata.split(' ')
                    column = int(arr[0])
                    row = int(arr[1])
                    if player.do_correct_move_player(game, row, column,
                                                     game.rival,
                                                     game.player) is not False:
                        game.move_first = True
                else:
                    pass
                scores = game.get_score_of_grid(game.grid)
                game.state['X'] = scores['X']
                game.state['O'] = scores['O']
                game.state['Empty'] = 64 - scores['X'] - scores['O']

            graphics.draw_grid(game)

            clock.tick(60)

            pygame.display.flip()

        pygame.quit()
Beispiel #3
0
    def __init__(self):
        self.solver = Solver(Config.SIZE, self.callback)
        self.done = False
        self.graphics = Graphics()
        self.graphics.init("Doku Solver", Config.WINDOWSIZE)

        if Config.SIZE == 4:
            self.solver.setGrid([
                "3002",
                "0410",
                "0320",
                "4001",
            ])

        if Config.SIZE == 9:
            self.solver.setGrid([
                "000000000",
                "000000000",
                "000000000",
                "384000000",
                "000000000",
                "000000000",
                "000000000",
                "000000000",
                "000000002",
            ])

            #self.solver.setGrid([
            #	"100904082",
            #	"052680300",
            #	"864200910",
            #	"010049806",
            #	"498300701",
            #	"607010093",
            #	"086035209",
            #	"509002130",
            #	"030497008"
            #]);

        if Config.SIZE == 16:

            self.solver.setGrid([
                " D0F  63C 7 1E  ", "  74    B 3 D   ", "E 4  97 0    3AF",
                " 2     E  516B9 ", "B A   E  8   F  ", "  F CA 6        ",
                "      4     5 E ", " 6C7  8  5B   2 ", " F B9   4 C  D 2",
                " 41D 6  5     C9", "2   7 1 D   B  8", "      A83   E   ",
                "C    B9 6  20   ", "  2  E30   C 546", " A 8 C   4     1",
                " 7   5       8D "
            ])

        if Config.SIZE == 25:
            for i in range(Config.SIZE):
                self.solver.setNumber(i, i, i + 1, True)
                self.solver.setNumber(0, i, Config.SIZE - (i + 1) + 1, True)
Beispiel #4
0
def main():
    game_board = GameBoard()
    graphics = Graphics((800, 800), game_board)

    while True:
        play_game(game_board, graphics)

        if players_are_bored(graphics):
            break

        game_board = GameBoard()
        graphics.game_board = game_board
Beispiel #5
0
    def __init__(self):
        # Must come before pygame.init()
        self.sounds = Sounds()

        self._clock = pygame.time.Clock()
        pygame.init()
        pygame.display.set_mode(
            (1, 1))  # temporarily initialise display so bitmaps can be loaded
        pygame.display.set_caption("Pacman")

        self.graphics = Graphics(self)

        self._img_Background = self.graphics.loadImage("backgrounds", "1.gif")

        # create the pacman
        self.player = Player(self)

        # create a path_finder object
        self.path = PathFinder()

        # create ghost objects
        self.ghosts = {}
        for i in range(0, 6, 1):
            # remember, ghost[4] is the blue, vulnerable ghost
            self.ghosts[i] = Ghost(self, i)

        # create piece of fruit
        self.fruit = Fruit(self)

        self.tileID = {}  # gives tile ID (when the name is known)
        self.tileIDImage = {}  # gives tile image (when the ID# is known)

        # create game and level objects and load first level
        self.game = Game(self)
        self.level = Level(self)
        self.level.loadLevel(self.game.getLevelNum())

        self.graphics.initDisplay()

        # initialise the joystick
        if pygame.joystick.get_count() > 0:
            if JS_DEVNUM < pygame.joystick.get_count():
                self._js = pygame.joystick.Joystick(JS_DEVNUM)
            else:
                self._js = pygame.joystick.Joystick(0)
            self._js.init()
        else:
            self._js = None
Beispiel #6
0
    def render(self, g: Graphics):
        for s in self.shape:
            # angle = self.rotation * (math.pi / 2) # degrees
            angle = self.rotation  # radians

            new_x1 = math.cos(angle) * (s[0]) - math.sin(angle) * (s[1])
            new_y1 = math.sin(angle) * (s[0]) + math.cos(angle) * (s[1])
            new_x1 = self.x + new_x1 * self.scale
            new_y1 = self.y + new_y1 * self.scale

            new_x2 = math.cos(angle) * (s[2]) - math.sin(angle) * (s[3])
            new_y2 = math.sin(angle) * (s[2]) + math.cos(angle) * (s[3])
            new_x2 = self.x + new_x2 * self.scale
            new_y2 = self.y + new_y2 * self.scale

            g.line(new_x1, new_y1, new_x2, new_y2, Graphics.WHITE)
Beispiel #7
0
 def __init__(self):
     """
     pygame.init() does initialize parts of the sound, but according to the
     documentation for the mixer module, safest way is to do mixer.pre_init,
     then pygame.init and then mixer.init. The controller also makes sure any
     resources needed in the game are preloaded.
     """
     self.__options = Options.load()
     self.__resources = Resources()
     pygame.mixer.pre_init(frequency = 44100, buffer = 2048) 
     pygame.init()
     pygame.mixer.init(frequency = 44100, buffer = 2048)
     self.__graphics = Graphics(self.__resources, self.__options)
     # Load all graphics and sound effects before the game is started
     self.__resources.preload_all()
     self.__logic = None
Beispiel #8
0
 def init(self):
   self.num = int(self.num)
   self.width = int(self.width)
   self.height = int(self.height)
   self.space = int(self.space)
   self.g = Graphics(self.num, self.height)
   self.separator = Separator(self.separator_width , self.height, self.separator_color)
Beispiel #9
0
    def options(self, active = 0):
        o = self.__options
        key_opts = [ ("Left:", o.left), ("Down:", o.down), ("Up:", o.up)
                   , ("Right:", o.right), ("Fire:", o.fire)
                   , ("Abort:", o.abort), ("Confirm:", o.confirm)
                   ]
        bool_opts = [ ("Fullscreen: ", o.fullscreen), ("Music: ", o.music)
                    , ("Sound effects: ", o.sfx)
                    ]
        self.__graphics.paint_options(key_opts, bool_opts, active, False)
        keys = [o.up, o.down, o.confirm, o.abort]
        kpress = wait_for_key(keys)
        while kpress in [o.up, o.down]:
            if kpress == o.up and active > 0:
                active -= 1
            elif kpress == o.down and active < 9:
                active += 1
            self.__graphics.paint_options(key_opts, bool_opts, active, False)
            kpress = wait_for_key(keys)

        if kpress == o.confirm:
            # Key options
            if active < len(key_opts):
                # Paint selection and wait for input
                self.__graphics.paint_options(key_opts, bool_opts, active, True)
                key = anykey()
                # Only keys that are not already assigned may be chosen
                if key not in self.__options.get_all_keys():
                    self.__options.set_index(active, key)
                    self.__options.save()
            
            # Boolean options, just reverse the value
            else:
                fs = self.__options.fullscreen
                val = self.__options.get_index(active)
                self.__options.set_index(active, not val)
                # If the fullscreen option was changed, reinitialize the
                # graphics
                if fs != self.__options.fullscreen:
                    pygame.display.quit()
                    self.__graphics = Graphics(self.__resources, self.__options)
            self.options(active)
        elif kpress == o.abort:
            self.main_menu()
        else: # event == QUIT
            self.quit()
Beispiel #10
0
    def play_game(self):
        game = Game('X', 'O')
        player = Player()
        robot = Robot()

        pygame.init()
        graphics = Graphics()
        pygame.display.set_caption("Reversi Game")

        done = False

        clock = pygame.time.Clock()

        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                elif event.type == pygame.MOUSEBUTTONDOWN and game.move_first:
                    pos = pygame.mouse.get_pos()
                    column = pos[0] // (graphics.width + graphics.margin)
                    row = pos[1] // (graphics.height + graphics.margin)
                    if game.in_grid(row, column)\
                            and (game.grid[row][column] == ''):
                        if player.do_correct_move_player(game, row, column,
                                                         game.player,
                                                         game.rival)\
                                is not False:
                            game.move_first = False
                elif not game.move_first:
                    x, y = robot.get_best_move_robot(game)
                    robot.do_move_robot(game, x, y)
                    game.move_first = True
                else:
                    pass
                scores = game.get_score_of_grid(game.grid)
                game.state['X'] = scores['X']
                game.state['O'] = scores['O']
                game.state['Empty'] = 64 - scores['X'] - scores['O']

            graphics.draw_grid(game)

            clock.tick(60)

            pygame.display.flip()

        pygame.quit()
Beispiel #11
0
def main():
    player_box = PlayerBox()
    generator = Generator()
    menu = Menu()
    lib = TextureLib()
    graphics = Graphics(lib)
    space = Space(graphics, menu, generator, player_box)
    space.start()
Beispiel #12
0
	def __init__(self, screen):
		"""
		Constructs an instance of Game and returns it.
		
		screen: a standard screen object from the curses library.
		"""
		# Create a Graphics class to handle drawing.
		self.graphics = Graphics(screen)
		
		# The last valid input by the user.
		self.last_valid_command = ""
		
		# Controls the game loop.
		self.running = True
		
		# Current scene.
		self.scene = None
    def __init__(self, graphicsBackend, difficultyLevel, playerName):

        self.board = Board()

        self.graphics = Graphics(graphicsBackend, self.board, playerName)
        self.aiPlayer = AI.AIPlayer(self.board, RED, difficultyLevel)
        # Cache parameters for when we need to restart the game
        self.graphicsBackend = graphicsBackend
        self.difficultyLevel = difficultyLevel
        self.playerName = playerName

        self.done = False

        self.mousePos = None

        self.hoverPiece = None
        self.hoverButton = 0
        self.selectedPiece = None
        self.profiler = cProfile.Profile()

        # Last timeDelta from last graphics update
        self.timeDelta = 0.

        self.turnNumber = 1

        # Player's turn switcher
        self.board.playerTurn = WHITE

        # Game state variables
        self.exitedGame = False
        self.gameEnded = None
        self.forceMove = None
        self.forcedMove = False
        self.states = {
            "playerTurn": self.playerTurnEventLoop,
            "AITurn": self.AITurnEventLoop,
            "pause": self.pauseEventLoop,
            "gameOver": self.gameOverEventLoop,
            "anim": self.waitForAnimationEventLoop
        }
        self.state = "playerTurn"
        self.stateBeforePause = None
        self.stateAfterAnimation = None
Beispiel #14
0
 def __init__(self, x_co, y_co, w_co, h_co, vx_co, vy_co, mass, level_co,
              c_co):
     """
     initialize everything
     x_co, y_co: the center coordinates.
     w_co, h_co: the width and height.
     vx_co, vy_co: speed to 2 coordinates.
     c_co: coefficient of restitution
     """
     self.w = w_co
     self.h = h_co
     self.vx = vx_co
     self.vy = vy_co
     self.mylevel = level_co
     self.graphics = Graphics(self)
     self.m = mass
     self.c = c_co
     self.update(x_co, y_co)
     self.af = 0.9
Beispiel #15
0
    def main():
        go_file = TraceTxt()
        sce = Scenery()
        gra = Graphics()
        config = Config()
        fac_aps = FactoryAp()
        fac_users = FactoryUser()
        data_generator = DataGenerator()
        arq = go_file.abreArquivo('result.txt')
        arq_supervisioned = go_file.abreArquivo('supervisioned.txt')

        aps = fac_aps.createAps(config)
        users = fac_users.createUsers(config)
        dados = []

        sp = SupervisedData()

        valuesClean = sp.get_values(config, aps)

        #chama o gerador de ddos apssando a lista de usuarios e aps(com os tributs de localizacao)
        for i in range(0, config.ciclo):
            dados, users = data_generator.createData(aps, config, users)
            #gera grafico
            sce.gerarGrafico(users, aps, i, config, valuesClean)
            #gera arquivo
            go_file.escreveArquivoScenery(i, arq, dados)

        go_file.escreveArquivoSupervisionado(arq_supervisioned, valuesClean)

        gra.plotagemPower(valuesClean, config)
        gra.heatMaps(aps, config)
        #gra.heatMapSinr(aps,config)

        go_file.fechaArquivo(arq)
    def gameLoop(self):
        sdl2.ext.init()
        self._window = sdl2.ext.Window("Game Window", size=(800, 600))
        self._graphics = Graphics(self._window)
        self._player = Player(self._graphics, 100, 100)
        self._window.show()

        LAST_UPDATE_TIME = 0

        while self._running:

            self._input.beginNewFrame()
            events = sdl2.ext.get_events()
            for event in events:
                if event.type == SDL_KEYDOWN:
                    if event.key.repeat == 0:
                        self._input.keyDownEvent(event)
                elif event.type == SDL_KEYUP:
                    self._input.keyUpEvent(event)
                
                elif event.type == sdl2.SDL_QUIT:
                    self._running = False
                    break

            if self._input.wasKeyPressed(SDL_SCANCODE_LEFT):
                self._player.moveLeft()
            elif self._input.wasKeyPressed(SDL_SCANCODE_RIGHT):
                self._player.moveRight()
            if not self._input.isKeyHeld(SDL_SCANCODE_LEFT) and not self._input.isKeyHeld(SDL_SCANCODE_RIGHT):
                self._player.stopMoving()

            CURRENT_TIME_MS = sdl2.SDL_GetTicks()
            ELAPSED_TIME_MS = CURRENT_TIME_MS - LAST_UPDATE_TIME
            self.update(min([ELAPSED_TIME_MS, MAX_FRAME_TIME]))
            LAST_UPDATE_TIME = CURRENT_TIME_MS

            self.draw()
            

        return 0
Beispiel #17
0
def main():
    # Setup
    pygame.init()
    clock = pygame.time.Clock()
    current_players_turn = True

    game_state = GameState()
    game_state.addPeices(4, 4, 2, True)
    game_state.addPeices(0, 5, -2, False)
    state = game_state.getState()
    enemy = Enemy()

    game_graphics = Graphics(state)

    selected_tile = None

    crashed = False
    while not crashed:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                crashed = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                x, y = event.pos
                tile_clicked_on = game_graphics.tileClickingOn(x, y)
                if selected_tile:
                    selected_tile.reset_tile_colour()
                if tile_clicked_on:
                    if current_players_turn:
                        if tile_clicked_on.isPlayer():
                            selected_tile = tile_clicked_on
                            tile_clicked_on.select()
                        elif selected_tile:
                            if tile_clicked_on.isEmpty():
                                game_state.move(selected_tile, tile_clicked_on,
                                                True)
                                current_players_turn = False
                                game_graphics.updateGraphics(state)
                                selected_tile = None
                                # game_state.printState()
                                game_state.processMove(
                                    enemy.makeMove(game_state))
                                # for e in game_state.getEnemyPeices():
                                #     print(e.i, e.j)
                                current_players_turn = True
                else:
                    selected_tile = None

        state = game_state.getState()
        game_graphics.updateGraphics(state)

        clock.tick(60)

    pygame.quit()
    quit()
Beispiel #18
0
def main():
    """
    Main starting point for the program

    :return: N/A
    """
    Graphics.init()
    FPS.init()

    drawer = Drawer()

    key_down_listeners = [drawer.on_key_down]

    mouse_down_listeners = [drawer.on_mouse_down]

    mouse_up_listeners = [drawer.on_mouse_up]

    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    sys.exit()
                if event.key == pygame.K_F10:
                    Graphics.toggle_fullscreen()

                for delegate in key_down_listeners:
                    delegate(event.key, event.mod)

            if event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEBUTTONUP:
                mouse_position = (event.pos[0] / Graphics.get_scale()[0],
                                  event.pos[1] / Graphics.get_scale()[1])

                if event.type == pygame.MOUSEBUTTONDOWN:
                    for delegate in mouse_down_listeners:
                        delegate(mouse_position, event.button)

                if event.type == pygame.MOUSEBUTTONUP:
                    for delegate in mouse_up_listeners:
                        delegate(mouse_position, event.button)

        drawer.update()

        drawer.draw()

        FPS.update()
        Graphics.flip()
Beispiel #19
0
class Screen(object):
  
  def __init__(self):
    self.num = -1
    self.width = 600
    self.height = 15
    self.space = 2
    self.separator_color = "#555555"
    self.separator_width = 1
    self.separator_active = True
    self.applets = []

  
  def init(self):
    self.num = int(self.num)
    self.width = int(self.width)
    self.height = int(self.height)
    self.space = int(self.space)
    self.g = Graphics(self.num, self.height)
    self.separator = Separator(self.separator_width , self.height, self.separator_color)

  def paint(self):
    self.g.x = self.width
    for applet in self.applets:
      self.g.x -= self.space
      if(self.separator_active):
        self.separator.paint(self.g)
        self.g.x -= self.space
      applet.paint(self.g)

    self.g.x -= self.space
    if(self.separator_active):
      self.separator.paint(self.g)
    self.g.send()


  def addApplet(self,applet):
    self.applets.append(applet)
Beispiel #20
0
    def __init__(self):
        self.is_running = False
        self.is_alive = False
        self.is_train = False
        self.is_human = True

        self.__hero = Hero()

        self.__score = 0
        self.__action_queue = []

        self.__width = WIDTH
        self.__height = HEIGHT

        self.__clock = None
        self.__environment = None

        self.screen = pg.display.set_mode((self.__width, self.__height))

        pg.init()

        self.__graphics = Graphics(self.screen)
        self.menu = GameMenu(self, self.screen)
	def __init__(self):
		self.g = Graphics(self)

		# load background image
		self.g.loadBackground(BACKGROUND_IMAGE)

		# Initialize our player and set its position to (50,50)
		self.player = self.g.loadPlayer(PLAYER_IMAGE)
		self.player.setPos(START_X, START_Y)

		# game clock
		self.clock = pygame.time.Clock()

		# Loop until exit
		self.gameLoop()
Beispiel #22
0
 def __init__(self, x_co, y_co, w_co, h_co, vx_co, vy_co, mass, level_co, c_co):
     """
     initialize everything
     x_co, y_co: the center coordinates.
     w_co, h_co: the width and height.
     vx_co, vy_co: speed to 2 coordinates.
     c_co: coefficient of restitution
     """
     self.w = w_co
     self.h = h_co
     self.vx = vx_co
     self.vy = vy_co
     self.mylevel = level_co
     self.graphics = Graphics(self)
     self.m = mass
     self.c = c_co
     self.update(x_co, y_co)
     self.af = 0.9
Beispiel #23
0
 def __init__(self):
     Controller.static_ctrl = self
     Controller.static_end = False
     self.graphics = Graphics()
     self.model = StartModel(self, self.graphics) # FIXME change to Start a different Model
     assert hasattr(self, 'timeout'), "Model does not call setTimeOut()"
     self.timestamp = now() # in seconds
     Input().start() # Thread 2
     while True: # Thread 1
         if (Controller.static_end): break
         time.sleep(REFRESH)
         if(now() - self.timestamp > self.timeout):
             if(self.model.timeout()):
                 self.model = self.model.next()
             if (self.model == None):
                 Controller.static_end = True
                 exit()
             self.timestamp = now();
Beispiel #24
0
g = copy.deepcopy(matrizFromImageForDfs)
matrizVacia = matricesVacias(0, 0)
matrizFin = matrizVacia.defineFin(fin, matrizFromImageForDfs)
print(matrizFin)
wf = WaveFront(matrizFin, filas, columnas)
matrizWithWaveFront = wf.aplyWaveFrontToMatrix()
matrizInicioFin = matrizVacia.definirOrigenFin(inicio, fin,
                                               matrizWithWaveFront)
print(matrizInicioFin)
df = DFS(matrizInicioFin, columnas, filas)
coverturaDFS = df.getCoverRouteWitSeed()
i = 0
dupe = False
i = 0
dupe = False

while i < len(coverturaDFS) - 1:
    if coverturaDFS[i] == coverturaDFS[i + 1]:
        del coverturaDFS[i]
        dupe = True
    else:
        i += 1

graphicsDFS = Graphics(g)
graphicsDFS.printCovertura(coverturaDFS)
coverturaPixelsDFS = openCvScript.getCentralPixel(coverturaDFS)
np.savetxt("coverturaDFS.txt", coverturaPixelsDFS, delimiter=',')
with open("coverturaDFS.txt", "wb") as f:
    writer = csv.writer(f)
    writer.writerows(coverturaPixelsDFS)
Beispiel #25
0
class Element(object):
    exist = True
    def __init__(self, x_co, y_co, w_co, h_co, vx_co, vy_co, mass, level_co, c_co):
        """
        initialize everything
        x_co, y_co: the center coordinates.
        w_co, h_co: the width and height.
        vx_co, vy_co: speed to 2 coordinates.
        c_co: coefficient of restitution
        """
        self.w = w_co
        self.h = h_co
        self.vx = vx_co
        self.vy = vy_co
        self.mylevel = level_co
        self.graphics = Graphics(self)
        self.m = mass
        self.c = c_co
        self.update(x_co, y_co)
        self.af = 0.9

    def set_exist(self, x):
        self.exist = x

    def update(self, x1, y1):
        """
        update the position of element
        """
        self.x = x1
        self.y = y1
        self.left = self.x - self.w/2.0
        self.right = self.x + self.w/2.0
        self.top = self.y - self.h/2.0
        self.bottom = self.y + self.h/2.0
        
        
    def in_inter(self, x, a, b):
        """
        return true when x is inside the interval [a, b]
        """
        assert a <= b, 'Invalid interval'
        if x >= a and x <= b:
            return True
        return False


    def touch(self, elem):
        """
        return true if the two elements are overlapped by the other
        """
        gapright =  self.right - elem.left
        gapleft =   elem.right - self.left
        gaptop =    -self.top + elem.bottom
        gapbottom = -elem.top + self.bottom
        if gapleft > 0 and gapright > 0 and gaptop > 0 and gapbottom > 0:
            if min(gapleft, gapright) < min(gaptop, gapbottom):
                #collision horizontal
                if gapleft < gapright:
                    return 3
                else:
                    return 1
            else:
                #collision vertical
                if gaptop < gapbottom:
                    return 2
                else:
                    return 4
        else:
            return 0
    
    def touch_ammount(self, elem):
        gapright =  self.right - elem.left
        gapleft =   elem.right - self.left
        gaptop =    -self.top + elem.bottom
        gapbottom = -elem.top + self.bottom
        direction =  self.touch(elem)
        if direction == 0:
            return 0
        elif direction == 1:
            return gapright
        elif direction == 2:
            return gaptop
        elif direction == 3:
            return gapleft
        elif direction == 4:
            return gapbottom
        else:
            assert False, "invalid direction"

    def move(self, elem):
        """
          move something out of another element under the presumption that those two elements are overlapped
          return nothing
        """
        direction = self.touch(elem)
        ammount = self.touch_ammount(elem)
        if direction == 0:
            return
        elif direction == 1:
            elem.x += ammount
        elif direction == 2:
            elem.y -= ammount
        elif direction == 3:
            elem.x -= ammount
        elif direction == 4:
            elem.y += ammount
        else:
            assert False, "invalid direction"

        elem.update(elem.x, elem.y)
            

    def phy_for(self, va, vb, ma, mb, coef):
        """
        take in objects a and b's speed and mass and return the speed for object b
        coef is the coefficient of restitution which is the average of the c of two elements
        """
        v = (coef * ma * (va - vb) + ma * va + mb * vb) / (ma + mb)
        return v
        


    def collide(self, elem):
        """
        modify the other element's speed; return nothing
        """
        direction = self.touch(elem)
        coef = (self.c + elem.c)/2
        if direction == 1 or direction == 3:
            if elem.vy > 0:
                elem.vy = max(0, elem.vy - self.af * abs(elem.vx))
            else:
                elem.vy = min(0, elem.vy + self.af * abs(elem.vx))
            elem.vx = self.phy_for(self.vx, elem.vx, self.m, elem.m, coef)
        elif direction == 2 or direction == 4:
            if elem.vx > 0:
                elem.vx = max(0, elem.vx - self.af * abs(elem.vy))
            else:
                elem.vx = min(0, elem.vx + self.af * abs(elem.vy))
            elem.vy = self.phy_for(self.vy, elem.vy, self.m, elem.m, coef)
        else:
            return
        """
        elem.vx = elem.vy = 0"""

    def sim(self, time):
        """
        simulate the element move in the certain direction for certain time.
        REMEMBER TO CHECK!
        """
        self.vy += self.mylevel.g * time
        x1 = self.x + time * self.vx
        y1 = self.y + time * self.vy
        self.update(x1, y1)
        
        

    def within_screen(self, scr_left, scr_right, scr_top, scr_bot):
        """
        return True if the element is in screen; False otherwise.
        scr_left: the left bound of the screen
        scr_right: the right bound of the screen
        """
#TODO:  Fixme
        return True
    

    def draw(self, screen, x, y, w, h):
        """
        convey the arguments x and y to graphics function to draw things.
        """
        self.graphics.draw(screen, x, y, w, h)
Beispiel #26
0
class Controller:
    
    #
    #
    def __init__(self):
        """
        pygame.init() does initialize parts of the sound, but according to the
        documentation for the mixer module, safest way is to do mixer.pre_init,
        then pygame.init and then mixer.init. The controller also makes sure any
        resources needed in the game are preloaded.
        """
        self.__options = Options.load()
        self.__resources = Resources()
        pygame.mixer.pre_init(frequency = 44100, buffer = 2048) 
        pygame.init()
        pygame.mixer.init(frequency = 44100, buffer = 2048)
        self.__graphics = Graphics(self.__resources, self.__options)
        # Load all graphics and sound effects before the game is started
        self.__resources.preload_all()
        self.__logic = None

    def main(self):
        self.main_menu()

    def play_game(self):
        """
        Initialize the game logic and handle whatever the game logic returns
        from a run of the game. 
        """
        self.__logic = GameLogic(self.__graphics, self.__resources, 
                                 self.__options)
        self.__logic.add_player()
        levels = level_convert()
        status = CLEARED
        #
        # Play the levels
        #
        for i in range(len(levels)):
            lev = levels[i]
            # Background music
            # TODO: Different music for different levels
            if self.__options.music:
                pygame.mixer.music.load(join(MP3_PATH,"cruising.mp3"))
                pygame.mixer.music.set_volume(0.8)
                pygame.mixer.music.play()

            # Prepare the level
            self.__logic.clear()
            self.__graphics.reset_distance()
            self.__graphics.set_scroll(5)
            self.__logic.set_level(lev)
            
            status = self.__logic.game_loop()
            if status != CLEARED:
                break
            # Last level cleared = game cleared!
            if i != len(levels)-1:
                self.level_cleared()

        # Turn off the music, since game is obviously over
        pygame.mixer.music.stop()

        #
        # Depending on how the game went, show some information, or not.
        #
        if status == CLEARED:
            self.game_cleared()
            self.main_menu()
        elif status == DIED:
            self.game_over()
        elif status == ABORTED:
            self.main_menu()
        else:
            self.quit()

#
# Menus below
#

    def main_menu(self):
        o = self.__options
        entries = ["Start game", "Instructions", "Options", "Quit"]
        funs = [lambda _: self.play_game(), lambda _: self.instructions()
               ,lambda _: self.options(), lambda _: self.quit()]
        active = 0
        self.__graphics.main_menu(entries, active)
        keys = [o.up, o.down, o.confirm]
        kpress = wait_for_key(keys)
        while kpress in [o.up, o.down]:
            if kpress == o.up and active > 0:
                active -= 1
            elif kpress == o.down and active < len(entries) - 1:
                active += 1
            self.__graphics.main_menu(entries, active)
            kpress = wait_for_key(keys)
        if kpress == o.confirm:
            f = funs[active]
            f(0)
        else:
            self.quit()

    # TODO: Collect and print stats from the level, too
    def level_cleared(self):
        self.__graphics.paint_level_cleared()
        anykey()

    # TODO: Highscores and stuff
    def game_cleared(self):
        self.__graphics.paint_game_cleared()
        anykey()

    # Shows an options menu and allows setting various game parameters
    def options(self, active = 0):
        o = self.__options
        key_opts = [ ("Left:", o.left), ("Down:", o.down), ("Up:", o.up)
                   , ("Right:", o.right), ("Fire:", o.fire)
                   , ("Abort:", o.abort), ("Confirm:", o.confirm)
                   ]
        bool_opts = [ ("Fullscreen: ", o.fullscreen), ("Music: ", o.music)
                    , ("Sound effects: ", o.sfx)
                    ]
        self.__graphics.paint_options(key_opts, bool_opts, active, False)
        keys = [o.up, o.down, o.confirm, o.abort]
        kpress = wait_for_key(keys)
        while kpress in [o.up, o.down]:
            if kpress == o.up and active > 0:
                active -= 1
            elif kpress == o.down and active < 9:
                active += 1
            self.__graphics.paint_options(key_opts, bool_opts, active, False)
            kpress = wait_for_key(keys)

        if kpress == o.confirm:
            # Key options
            if active < len(key_opts):
                # Paint selection and wait for input
                self.__graphics.paint_options(key_opts, bool_opts, active, True)
                key = anykey()
                # Only keys that are not already assigned may be chosen
                if key not in self.__options.get_all_keys():
                    self.__options.set_index(active, key)
                    self.__options.save()
            
            # Boolean options, just reverse the value
            else:
                fs = self.__options.fullscreen
                val = self.__options.get_index(active)
                self.__options.set_index(active, not val)
                # If the fullscreen option was changed, reinitialize the
                # graphics
                if fs != self.__options.fullscreen:
                    pygame.display.quit()
                    self.__graphics = Graphics(self.__resources, self.__options)
            self.options(active)
        elif kpress == o.abort:
            self.main_menu()
        else: # event == QUIT
            self.quit()

    # TODO: A describing text about the gameplay
    def instructions(self):
        opts = self.__options
        enemies = all_ships()
        funs = [lambda _: self.__graphics.paint_instructions_keys(),
                lambda _: self.__graphics.paint_instructions_ship(),
                lambda _: self.__graphics.paint_instructions_enemies(enemies) ]
        active = 0
        kpress = None 
        while active >= 0 and active <= 2 and kpress != QUIT:
            screen = funs[active]
            screen(0)
            kpress = wait_for_key([opts.left, opts.right])
            if kpress == opts.left: 
                active -= 1
            elif kpress == opts.right:
                active += 1
        if kpress == QUIT:
            self.quit()
        else:
            self.main_menu()

    def game_over(self):
        self.__graphics.game_over()
        # There is an option of restarting without going through the main menu
        if yn_key():
            self.play_game()
        else:
            self.main_menu()

    def quit(self):
        self.__options.save()
        pygame.mixer.quit()
        pygame.quit()
 def render(self, g: Graphics):
     g.filled_circle(self.sx, self.sy, self.r, self.color)
 def render(self, g: Graphics):
     g.line(self.x1, self.y1, self.x2, self.y2, Graphics.WHITE)
Beispiel #29
0
    def update():
        FPS._current_frames += 1

        FPS._previous_time = FPS._current_time
        FPS._current_time = time.time()

        FPS._delta_time = FPS._current_time - FPS._previous_time
        FPS._last_update += FPS._delta_time

        if FPS._last_update >= 1:
            FPS._current_fps = FPS._current_frames

            FPS._current_frames = 0
            FPS._last_update = 0

            FPS._surface = FPS._font.render("FPS: " + str(FPS._current_fps), 1, System.Color.WHITE)
            FPS._outline_surface = \
                FPS._font.render("FPS: " + str(FPS._current_fps), 1, System.Color.BLACK)

            FPS._surface_rect = FPS._surface.get_rect()
            FPS._surface_rect.move_ip(Graphics.get_resolution()[0] / 2, 15)

            FPS._outline_surface_rect = FPS._surface.get_rect()

        # Draws an outline for the FPS 
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x + 1, FPS._surface_rect.y,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x - 1, FPS._surface_rect.y,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x, FPS._surface_rect.y + 1,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x, FPS._surface_rect.y - 1,
                                  FPS._surface_rect.width, FPS._surface_rect.height))

        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x + 1, FPS._surface_rect.y + 1,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x - 1, FPS._surface_rect.y - 1,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x - 1, FPS._surface_rect.y + 1,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        Graphics.draw(FPS._outline_surface,
                      pygame.Rect(FPS._surface_rect.x + 1, FPS._surface_rect.y - 1,
                                  FPS._surface_rect.width, FPS._surface_rect.height))
        # End of Outline

        Graphics.draw(FPS._surface, FPS._surface_rect)

        FPS._clock.tick(System.Display.TARGET_FPS)
class Game():
	def __init__(self):
		self.g = Graphics(self)

		# load background image
		self.g.loadBackground(BACKGROUND_IMAGE)

		# Initialize our player and set its position to (50,50)
		self.player = self.g.loadPlayer(PLAYER_IMAGE)
		self.player.setPos(START_X, START_Y)

		# game clock
		self.clock = pygame.time.Clock()

		# Loop until exit
		self.gameLoop()
	
	def gameLoop(self):
		self.frameCountSub = 0

		while True:
			# ensure we're running at a stable FPS
			self.clock.tick(FRAME_RATE)

			# handle user input
			self.handle_input()

			# possibly create new enemy
			self.frameCountSub += 1
			if self.frameCountSub == ENEMY_SPAWN_INTERVAL:
				self.g.addSub()
				self.frameCountSub = 0

			# update positions, handle collisions, etc
			self.g.update()

			# draw
			self.g.drawScreen()

	def handle_input(self):
		'''
			Handle all input from user. This includes keypresses, mouse clicks,
			exiting, etc.
		'''
		# For each event that occurs this frame
		for event in pygame.event.get():
			# If user exits the window
			if event.type == QUIT:
				sys.exit(0)
			
			# monitor keyboard
			self.handle_keys(event)

	
	def handle_keys(self, event):
		'''
			Handle input from user keyboard
		'''
		if event.type == pygame.KEYDOWN:
			# move left
			if event.key == K_LEFT:
				self.player.setVel(Vector2(-1,0) * PLAYER_SPEED)
			# move right
			elif event.key == K_RIGHT:
				self.player.setVel(Vector2(1,0) * PLAYER_SPEED)

			# fire
			elif event.key == K_SPACE:
				self.fireTorpedo()

			# exit game
			elif event.key == K_ESCAPE:
				sys.exit(0)

		elif event.type == pygame.KEYUP:
			# if we released either the left or right arrow key, stop moving
			if event.key == K_LEFT or event.key == K_RIGHT:
				self.player.setVel(Vector2(0,0))
	
	def fireTorpedo(self):
		pos = self.player.getPos()
		self.g.addTorpedo(pos)
Beispiel #31
0
class Doku():
    def __init__(self):
        self.solver = Solver(Config.SIZE, self.callback)
        self.done = False
        self.graphics = Graphics()
        self.graphics.init("Doku Solver", Config.WINDOWSIZE)

        if Config.SIZE == 4:
            self.solver.setGrid([
                "3002",
                "0410",
                "0320",
                "4001",
            ])

        if Config.SIZE == 9:
            self.solver.setGrid([
                "000000000",
                "000000000",
                "000000000",
                "384000000",
                "000000000",
                "000000000",
                "000000000",
                "000000000",
                "000000002",
            ])

            #self.solver.setGrid([
            #	"100904082",
            #	"052680300",
            #	"864200910",
            #	"010049806",
            #	"498300701",
            #	"607010093",
            #	"086035209",
            #	"509002130",
            #	"030497008"
            #]);

        if Config.SIZE == 16:

            self.solver.setGrid([
                " D0F  63C 7 1E  ", "  74    B 3 D   ", "E 4  97 0    3AF",
                " 2     E  516B9 ", "B A   E  8   F  ", "  F CA 6        ",
                "      4     5 E ", " 6C7  8  5B   2 ", " F B9   4 C  D 2",
                " 41D 6  5     C9", "2   7 1 D   B  8", "      A83   E   ",
                "C    B9 6  20   ", "  2  E30   C 546", " A 8 C   4     1",
                " 7   5       8D "
            ])

        if Config.SIZE == 25:
            for i in range(Config.SIZE):
                self.solver.setNumber(i, i, i + 1, True)
                self.solver.setNumber(0, i, Config.SIZE - (i + 1) + 1, True)

    def callback(self):
        # self.done = True
        pass

    def run(self):
        # Loop until the user clicks the close button.
        while not self.done:

            self.done = self.graphics.queryQuit()

            # Set the screen background
            self.graphics.fill(Config.WHITE)
            # self.graphics.print("Clock: {}".format(self.graphics.fps()))

            if Config.SPEED == Config.FAST:
                # Draw everything
                self.solver.draw(self.graphics)
                # Update screen
                self.graphics.flip()

            # Do physics
            self.solver.tick()

            # Draw everything
            self.solver.draw(self.graphics)

            # Update screen
            self.graphics.flip()

        # Exit
        self.graphics.quit()
Beispiel #32
0
 def draw(self):
     Graphics.getInstance().drawPlayState(self.player)
Beispiel #33
0
 def render(self, g: Graphics):
     g.filled_circle(self.pos.x, self.pos.y, 3, Graphics.WHITE)
Beispiel #34
0
class Element(object):
    exist = True

    def __init__(self, x_co, y_co, w_co, h_co, vx_co, vy_co, mass, level_co,
                 c_co):
        """
        initialize everything
        x_co, y_co: the center coordinates.
        w_co, h_co: the width and height.
        vx_co, vy_co: speed to 2 coordinates.
        c_co: coefficient of restitution
        """
        self.w = w_co
        self.h = h_co
        self.vx = vx_co
        self.vy = vy_co
        self.mylevel = level_co
        self.graphics = Graphics(self)
        self.m = mass
        self.c = c_co
        self.update(x_co, y_co)
        self.af = 0.9

    def set_exist(self, x):
        self.exist = x

    def update(self, x1, y1):
        """
        update the position of element
        """
        self.x = x1
        self.y = y1
        self.left = self.x - self.w / 2.0
        self.right = self.x + self.w / 2.0
        self.top = self.y - self.h / 2.0
        self.bottom = self.y + self.h / 2.0

    def in_inter(self, x, a, b):
        """
        return true when x is inside the interval [a, b]
        """
        assert a <= b, 'Invalid interval'
        if x >= a and x <= b:
            return True
        return False

    def touch(self, elem):
        """
        return true if the two elements are overlapped by the other
        """
        gapright = self.right - elem.left
        gapleft = elem.right - self.left
        gaptop = -self.top + elem.bottom
        gapbottom = -elem.top + self.bottom
        if gapleft > 0 and gapright > 0 and gaptop > 0 and gapbottom > 0:
            if min(gapleft, gapright) < min(gaptop, gapbottom):
                #collision horizontal
                if gapleft < gapright:
                    return 3
                else:
                    return 1
            else:
                #collision vertical
                if gaptop < gapbottom:
                    return 2
                else:
                    return 4
        else:
            return 0

    def touch_ammount(self, elem):
        gapright = self.right - elem.left
        gapleft = elem.right - self.left
        gaptop = -self.top + elem.bottom
        gapbottom = -elem.top + self.bottom
        direction = self.touch(elem)
        if direction == 0:
            return 0
        elif direction == 1:
            return gapright
        elif direction == 2:
            return gaptop
        elif direction == 3:
            return gapleft
        elif direction == 4:
            return gapbottom
        else:
            assert False, "invalid direction"

    def move(self, elem):
        """
          move something out of another element under the presumption that those two elements are overlapped
          return nothing
        """
        direction = self.touch(elem)
        ammount = self.touch_ammount(elem)
        if direction == 0:
            return
        elif direction == 1:
            elem.x += ammount
        elif direction == 2:
            elem.y -= ammount
        elif direction == 3:
            elem.x -= ammount
        elif direction == 4:
            elem.y += ammount
        else:
            assert False, "invalid direction"

        elem.update(elem.x, elem.y)

    def phy_for(self, va, vb, ma, mb, coef):
        """
        take in objects a and b's speed and mass and return the speed for object b
        coef is the coefficient of restitution which is the average of the c of two elements
        """
        v = (coef * ma * (va - vb) + ma * va + mb * vb) / (ma + mb)
        return v

    def collide(self, elem):
        """
        modify the other element's speed; return nothing
        """
        direction = self.touch(elem)
        coef = (self.c + elem.c) / 2
        if direction == 1 or direction == 3:
            if elem.vy > 0:
                elem.vy = max(0, elem.vy - self.af * abs(elem.vx))
            else:
                elem.vy = min(0, elem.vy + self.af * abs(elem.vx))
            elem.vx = self.phy_for(self.vx, elem.vx, self.m, elem.m, coef)
        elif direction == 2 or direction == 4:
            if elem.vx > 0:
                elem.vx = max(0, elem.vx - self.af * abs(elem.vy))
            else:
                elem.vx = min(0, elem.vx + self.af * abs(elem.vy))
            elem.vy = self.phy_for(self.vy, elem.vy, self.m, elem.m, coef)
        else:
            return
        """
        elem.vx = elem.vy = 0"""

    def sim(self, time):
        """
        simulate the element move in the certain direction for certain time.
        REMEMBER TO CHECK!
        """
        self.vy += self.mylevel.g * time
        x1 = self.x + time * self.vx
        y1 = self.y + time * self.vy
        self.update(x1, y1)

    def within_screen(self, scr_left, scr_right, scr_top, scr_bot):
        """
        return True if the element is in screen; False otherwise.
        scr_left: the left bound of the screen
        scr_right: the right bound of the screen
        """
        #TODO:  Fixme
        return True

    def draw(self, screen, x, y, w, h):
        """
        convey the arguments x and y to graphics function to draw things.
        """
        self.graphics.draw(screen, x, y, w, h)
Beispiel #35
0
 def draw(self):
     Graphics.getInstance().drawPlayState(self.player)
Beispiel #36
0
print(inicio)
print(fin)

matrizInicio = matrizVacia.defineOrigin(inicio,matrizFromImage)
print(matrizInicio)
stc = STC(matrizInicio)
coverturaStc = stc.getSTCoverture()
i = 0
dupe = False
while i < len(coverturaStc)-1:
    if coverturaStc[i] == coverturaStc[i+1]:
        del coverturaStc[i]
    else:
        i += 1

gp = Graphics(b)
gp.printCovertura(coverturaStc)
(visit, revisit) = gp.counter()
twist = gp.numberOfTwist(coverturaStc)
with open("propiedadesSTC.txt","wb") as f:
        f.write("visitas: {visitas} re visitas : {revisitas} giros {giros}".format(visitas = visit,revisitas=revisit, giros = twist))


coverturaPixels = openCvScript.getCentralPixel(coverturaStc)
print(coverturaPixels)
np.savetxt("coverturaSTC.txt",coverturaPixels,delimiter=',')
with open("coverturaSTC.txt","wb") as f:
        writer = csv.writer(f)
        writer.writerows(coverturaPixels)

Beispiel #37
0
 def render(self, g: Graphics):
     g.rectangle(self.x, self.y, self.x + self.w, self.y + self.h, Graphics.GREEN, 0)
Beispiel #38
0
    def draw(self):
        if self._nodes_surface_dirty or self._font_surface_dirty or self._debug_surface_dirty:

            if self._nodes_surface_dirty:
                self._nodes_surface.fill(System.Color.TRANSPARENT)
            if self._font_surface_dirty:
                self._font_surface.fill(System.Color.TRANSPARENT)
            if self._debug_surface_dirty:
                self._debug_surface.fill(System.Color.TRANSPARENT)

            for x in range(0, len(self._search_space.nodes)):
                for y in range(0, len(self._search_space.nodes[x])):

                    if self._nodes_surface_dirty:
                        node_surface = pygame.Surface(
                            (System.Graph.NODE_WIDTH, System.Graph.NODE_HEIGHT))

                        self._search_space.nodes[x][y].update_surface_color(
                            self._search_space.open_list, self._search_space.closed_list,
                            self._search_space.start_node, self._search_space.end_node)
                        node_surface.fill(self._search_space.nodes[x][y].surface_color)

                        self._nodes_surface.blit(
                            node_surface, self._search_space.nodes[x][y].surface_rect)

                    if self._debug_surface_dirty \
                            and self._search_space.nodes[x][y].parent_node is not None:
                        pygame.draw.line(
                            self._debug_surface,
                            System.Color.BLACK,
                            (self._search_space.nodes[x][y].surface_rect.x +
                             (self._search_space.nodes[x][y].surface_rect.width / 2),
                             self._search_space.nodes[x][y].surface_rect.y +
                             (self._search_space.nodes[x][y].surface_rect.height / 2)),
                            (self._search_space.nodes[x][y].parent_node.surface_rect.x +
                             (self._search_space.nodes[x][y].parent_node.surface_rect.width / 2),
                             self._search_space.nodes[x][y].parent_node.surface_rect.y +
                             (self._search_space.nodes[x][y].parent_node.surface_rect.height / 2)
                            ))

                    if self._font_surface_dirty and self._search_space.nodes[x][y].traversable:
                        text_color = \
                            System.Color.BLACK \
                            if self._search_space.nodes[x][y] in self._search_space.open_list \
                            else System.Color.LIGHT_GREY

                        h_text_surface = self._font.render(
                            'H: ' + str(self._search_space.nodes[x][y].h_score), 1, text_color)

                        h_text_surface_rect = h_text_surface.get_rect()
                        h_text_surface_rect = (
                            self._search_space.nodes[x][y].surface_rect.x +
                            self._search_space.nodes[x][y].surface_rect.width -
                            h_text_surface_rect.width,
                            self._search_space.nodes[x][y].surface_rect.y +
                            self._search_space.nodes[x][y].surface_rect.height -
                            h_text_surface_rect.height)

                        g_text_surface = self._font.render(
                            'G: ' + str(self._search_space.nodes[x][y].g_score), 1, text_color)

                        g_text_surface_rect = h_text_surface.get_rect()
                        g_text_surface_rect = (
                            self._search_space.nodes[x][y].surface_rect.x,
                            self._search_space.nodes[x][y].surface_rect.y +
                            self._search_space.nodes[x][y].surface_rect.height -
                            g_text_surface_rect.height)

                        f_text_surface = self._font.render(
                            'F: ' + str(self._search_space.nodes[x][y].f_score), 1, text_color)

                        f_text_surface_rect = self._search_space.nodes[x][y].surface_rect

                        self._font_surface.blit(h_text_surface, h_text_surface_rect)
                        self._font_surface.blit(g_text_surface, g_text_surface_rect)
                        self._font_surface.blit(f_text_surface, f_text_surface_rect)

            if self._nodes_surface_dirty and not self._display_help:
                direction_list = [(1, 0), (0, 1), (-1, 0), (0, -1),
                                  (1, 1), (-1, -1), (1, -1), (-1, 1), (0, 0)]

                i = 0
                for direction in direction_list:
                    temp_text = self._help_font.render(
                        'F1 = Help', 1,
                        System.Color.WHITE if i == len(direction_list) - 1 else System.Color.BLACK)
                    temp_text_rect = temp_text.get_rect()

                    temp_text_rect.x += direction[0]
                    temp_text_rect.y += direction[1]
                    self._nodes_surface.blit(temp_text, temp_text_rect)

                    i += 1

            if self._debug_surface_dirty:
                current_path_node = self._search_space.end_node
                while current_path_node.parent_node is not None:
                    pygame.draw.line(
                        self._debug_surface,
                        System.Color.DARK_GREEN,
                        (
                            current_path_node.surface_rect.x +
                            (current_path_node.surface_rect.width / 2),
                            current_path_node.surface_rect.y +
                            (current_path_node.surface_rect.height / 2)),
                        (
                            current_path_node.parent_node.surface_rect.x +
                            (current_path_node.parent_node.surface_rect.width / 2),
                            current_path_node.parent_node.surface_rect.y +
                            (current_path_node.parent_node.surface_rect.height / 2)),
                        5)

                    current_path_node = current_path_node.parent_node

            self._nodes_surface_dirty = False
            self._font_surface_dirty = False
            self._debug_surface_dirty = False

        Graphics.draw(self._nodes_surface, self._nodes_surface_rect)

        if self._display_debug:
            Graphics.draw(self._debug_surface, self._debug_surface_rect)

        if self._display_text:
            Graphics.draw(self._font_surface, self._font_surface_rect)

        if self._display_help:
            Graphics.draw(self._help_surface, self._help_surface_rect)

        if self._paused:
            Graphics.draw(self._pause_surface, self._pause_surface_rect)
Beispiel #39
0
 def render(self, g: Graphics):
     if self.hidden:
         return
     g.line(self.p0.pos.x, self.p0.pos.y, self.p1.pos.x, self.p1.pos.y, Graphics.WHITE)
Beispiel #40
0
import numpy as np
from matricesVacias import matricesVacias
from STC import STC
from Graphics import Graphics
import copy


print("Script de implementacion de STC")
columnas = int(raw_input('ingrese numero de columnas: '))
filas = int(raw_input("ingerese filas: "))
matrisVacia = matricesVacias(filas,columnas)
a = matrisVacia.matrizForStc()
b = copy.deepcopy(a)
print(a)
inicio = raw_input("Defina la posicion de inicion, separando las posiciones con ',': ")
matrizInicio = matrisVacia.defineOrigin(inicio,a)
print(matrizInicio)
stc = STC(matrizInicio)
covertura = stc.getSTCoverture()
gp = Graphics(b)
gp.printCovertura(covertura)
gp.counter()
gp.numberOfTwist(covertura)