Beispiel #1
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)
Beispiel #2
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 #3
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()
def main():
    player_box = PlayerBox()
    generator = Generator()
    menu = Menu()
    lib = TextureLib()
    graphics = Graphics(lib)
    space = Space(graphics, menu, generator, player_box)
    space.start()
Beispiel #5
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 #6
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 #7
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 #8
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 #9
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 #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 __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
Beispiel #12
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 #13
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 #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
    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
    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 __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)
Beispiel #18
0
import queue
import random
import pygame
from Graphics import Graphics

WIDTH = 512
HEIGHT = 100

WHITE = (255, 255, 255)
GREEN = (0, 128, 0)
RED = (128, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
BLACK = (0, 0, 0)

graphics = Graphics()
graphics.init("Maze", (WIDTH, HEIGHT))

#########################################################################
#########################################################################
#########################################################################


# https://www.youtube.com/watch?v=6-0UaeJBumA
class Noide1D():

    width = 0
    output = []
    noiseSeed = []
    octaves = 9
    scalingBias = 20.0
Beispiel #19
0
from Graphics import Graphics

game_board = Graphics([800, 800])

game_board.game_loop()
Beispiel #20
0
def routine(gui, DATA_FILE, ANNOT_FILE):
    # gui_thread = threading.Thread(target=gui.write_to_output, args=(gui, "Reading the file...\n",))
    # gui_thread.start()
    # gui_thread.join()
    gui.write_to_output("Reading the file...\n")
    grph = Graphics()
    fromFile = readTheFile(DATA_FILE, gui)
    alternatives = findAlternatives(fromFile)
    gui.write_to_output("Total transcripts: " + str(len(fromFile)) +
                        " | APA: " + str(len(alternatives)) + "\n")
    if len(alternatives) > 0:
        gui.write_to_output("Found alternatives...\n")
    else:
        gui.write_to_output("No alternatives, check the arguments\n")
        raise SystemExit
    fracs = calculateFractions(alternatives)
    # data = fracs[0].getSamples()
    # symbols = [fracs[0].getName()]
    # for frac in fracs[1:]:
    #     data = np.vstack((data, frac.getSamples()))
    #     symbols.append(frac.getName())
    # pca = PCAVisual(data, symbols)
    # pca.show(DATA_FILE)
    gui.write_to_output("Read the annotations file...\n")
    annotations = readAnnotation(ANNOT_FILE, gui)
    gui.write_to_output("Checks the annotations...\n")
    findAnnotatedShifts(fracs, annotations, gui)
    shifts = findShifts(fracs)
    shifts = correct_fdr(shifts)
    temp = []
    for gene in shifts:
        if gene.getMaxShift() > 1.5:
            temp.append(gene)
    # grph.data_to_heat_map(temp, names, filename="str_above1d5.pdf")
    topdf2 = grph.scatter_pval_to_fold(shifts, shift=1.5, gui=gui)
    sorted(topdf2, key=lambda x: x.getName())
    fm = SimpleMotifsFinder.Family()
    sequences = open("utrs_all_alt.fa", 'w')
    threads = []
    alt_exon = check_cds(topdf2, annotations, gui)
    long_up, long_down = grph.length_by_regulation(
        [gene for gene in topdf2 if gene not in alt_exon], SAMPLES_PARTS)
    # print([gene.getName() for gene in long_up])
    # print([gene.getName() for gene in long_down])
    """
    The next lines can be executed using multiprocessing or multithreading.
    These are some times for each approach(run on set of 37 genes):
    Threading: 50 seconds
    Processing: 137.8 seconds
    Neither: 57.1 seconds
    """
    # for gene in fracs:
    #     seq = gene.getSequence()
    #     print(gene.getName())
    #     sequences.write(">" + gene.getName() + "\n")
    #     sequences.write(seq + "\n")
    #     thread = threading.Thread(target=fm.hash_sequence, args=(seq,))
    #     thread.start()
    #     threads.append(thread)
    #     # fm.hash_sequence(seq)
    #     # if gene.getName() == 'Camk2a':
    #     #     grph.show_change_in_box(gene, SAMPLES_PARTS)
    # for thread in threads:
    #     thread.join()
    # sequences.close()
    # fm.write_motifs()
    # check_cds(topdf2, annotations)
    grph.fold_change_and_pvalue(shifts)
    gui.write_to_output("Writing the output...\n")
    gui.write_to_output("Done, press 'Exit' to close the window.\n")
Beispiel #21
0
                else:
                    snakes[snake] = [i]
            i += 1

    for i in range(graph.V):
        for roll in dice:
            if i + roll <= graph.V:
                graph.addEdge(i, i + roll)

    for l in ladders:
        graph.graph[ ladders[l][0] ].neighbors = graph.graph[ ladders[l][1] ].neighbors
    for s in snakes:
        graph.graph[ snakes[s][1] ].neighbors = graph.graph[ snakes[s][0] ].neighbors
    return graph

ladders = {}
snakes = {}
board = initBoard()
graph = initGraph(ladders, snakes)

graph.BFS(0)
graph.printPath(graph.V)
print "Total Number of rolls is: " + str(len(graph.graph[graph.V].path))

graphics = Graphics(board.ROWS)
graphics.drawBoard(board)
graphics.drawSnakesAndLadders(ladders, snakes)
graphics.drawPath(graph.graph[graph.V].path, ladders, graph)
graphics.win.getMouse()
graphics.win.close()
Beispiel #22
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)
Beispiel #23
0
from matricesVacias import matricesVacias
from Graphics import Graphics
from Sunshine import Sunshine
import time as time
from DFS8 import DFS8
from Graphics import Graphics
import copy as copy

print('Script de implementacion de Sunshine 1.0')
columnas = int(raw_input('ingrese el numero de columnas: '))
filas = int(raw_input('ingrese el numero de filas: '))
matrisVacia = matricesVacias(filas,columnas)
a = matrisVacia.matrizForSunshine()
g = copy.deepcopy(a)
print(a)
sunshie = Sunshine(a)
b = sunshie.getWaveFrontFromObstacle()
c  = sunshie.getWaveFrontFromInitialPoint((0,3),(0,0))
d = sunshie.getMatrizSunshine(4)
dfs8 = DFS8(d,columnas,filas)
covertura = dfs8.getCoverRouteWitSeed()
print(covertura)

graphics = Graphics(g)
graphics.printCovertura(covertura)
graphics.numberOfTwist(covertura)
graphics.counter(covertura)



Beispiel #24
0
 def __init__(self):                #Generate new field
     self.gui=Graphics()
     self.gui.update()
Beispiel #25
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)
from random import shuffle
from Graphics import Graphics
import Util
from time import sleep
from Track import Track
from RF import RF
from queue import *
from D import D
from Upload import Upload
from random import shuffle

nThread = 2

# Demone grafico

t = Graphics()
t.daemon = True
t.start()
'''
sleep(2)
idt=Util.w.create_text(10,10,text="Percentuale completamento: 0%",anchor='nw',tags='casa')
idt=Util.w.create_text(10,30,text="Percentuale completamento: 10%",anchor='nw',tags='casa')
idt=Util.w.create_text(10,50,text="Percentuale completamento: 0%",anchor='nw',tags='coso')
idt=Util.w.create_text(10,70,text="Percentuale completamento: 0%",anchor='nw',tags='coso')
idt=Util.w.create_text(10,90,text="Percentuale completamento: 0%",anchor='nw',tags='cacca')
idt=Util.w.create_text(10,110,text="Percentuale completamento: 0%",anchor='nw',tags='cacca')



sleep(2)
Util.w.itemconfig(idt,text=str(Util.w.find_above('1')))
Beispiel #27
0
print("dimensiones de la matriz")

hm,gm = input()
mapa = np.zeros((hm,gm))
mv = matricesVacias(hm,gm)
a = mv.matrizForSunshine()
b = copy.deepcopy(a)


##mapa = np.array([[0,0,0,0,-1], \
##                 [0,0,0,0,-1], \
##                 [0,0,0,-1,-1], \
##                 [-1,-1,-1,-1,-1] ])

hm,gm = mapa.shape
print(hm,gm)
print(a)
print("posicion Inicial ")
pi_x = int(input())
pi_y = int(input())
espiral = Espiral()
covertura = espiral.getCoverturePath(a,pi_x,pi_y)
graphis = Graphics(b)
graphis.printCovertura(covertura)


##print("anterior")
##ps_x = int(input())
##ps_y = int(input())
Beispiel #28
0
def main():
    arguments = parser.parse_args()
    train_path = "train_recortadas"
    test_path = "test_reconocimiento"
    classifier = "LDA-BAYES"
    imgPath = None
    if (arguments.train):
        train_path = arguments.train
    if (arguments.classifier):
        print('Detectado parametro classifier: ' + arguments.classifier)
        classifier = arguments.classifier
    if (arguments.test):
        test_path = arguments.test
    if (arguments.img_path):
        imgPath = arguments.img_path
    print("The script has " + str(3) + ' arguments:')
    print("Train path: " + str(train_path) + '.')
    print("Test path: " + str(test_path) + '.')
    print("Clasificador: " + str(classifier))
    #imagenes = os.listdir(test_path)

    try:
        trainClassesPath = []
        for f in os.listdir(train_path):
            trainClassesPath.append(train_path + "/" + f)
        cl = Classifier(classifier)
        classifier_result, test_img_names, test_labels, test_accuracy, train_accuracy = cl.start(
            trainClassesPath, test_path)

        # Si hay una imagen real para analizar
        if (imgPath is not None):
            print(
                "Detectada imagen adicional para analizar. \nComenzando deteccion de señales..."
            )
            # Obtenemos las señales de la imagen y las guardamos en una carpeta para procesarlas
            imgs = getSignalsFromImg(imgPath)
            folder = './temporary_test'
            if not os.path.exists(folder):
                os.makedirs(folder)
            else:
                shutil.rmtree(folder)  # removes all the subdirectories!
                os.makedirs(folder)
            for i, img in enumerate(imgs):
                im = plt.image.imsave(folder + "/image" + str(i) + ".png",
                                      cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
            # Una vez guardadas las señales reconocidas de la imagen procedemos a clasificarlas --> ToDo

        # Graficos
        graphics = Graphics()
        graphics.accuracy_graphic(train_accuracy,
                                  "Entrenamiento " + classifier)
        graphics.accuracy_graphic(test_accuracy, "Test " + classifier)
        graphics.conf_matrix(classifier_result, test_labels)
        graphics.get_f1_score(classifier_result, test_labels)

        # Escribir resultados
        writeInFile("resultado.txt", test_img_names, classifier_result)

    except Exception as e:
        print(
            'Algo ha ido mal, por favor comprueba que tienes la version 3.6.x de Python y la version 3.x de OpenCV'
        )
        print(str(e))
    print('Reconocimiento finalizado. Resultados escritos en resultados.txt')
Beispiel #29
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 #30
0
    def __init__(self, ctrl):
        self.ctrl = ctrl

        def up():
            if self.graphics.array[self.x - 1][self.y] != WALL:
                self.graphics.array[self.x][self.y] = (Graphics.EMPTY,
                                                       Graphics.WHITE)
                self.x -= 1
                self.graphics.array[self.x][self.y] = (self.hero,
                                                       self.herocolor)
                self.refresh()

        def down():
            if self.graphics.array[self.x + 1][self.y] != WALL:
                self.graphics.array[self.x][self.y] = (Graphics.EMPTY,
                                                       Graphics.WHITE)
                self.x += 1
                self.graphics.array[self.x][self.y] = (self.hero,
                                                       self.herocolor)
                self.refresh()

        def left():
            if self.graphics.array[self.x][self.y - 1] != WALL:
                self.graphics.array[self.x][self.y] = (Graphics.EMPTY,
                                                       Graphics.WHITE)
                self.y -= 1
                self.graphics.array[self.x][self.y] = (self.hero,
                                                       self.herocolor)
                self.refresh()

        def right():
            if self.graphics.array[self.x][self.y + 1] != WALL:
                self.graphics.array[self.x][self.y] = (Graphics.EMPTY,
                                                       Graphics.WHITE)
                self.y += 1
                self.graphics.array[self.x][self.y] = (self.hero,
                                                       self.herocolor)
                self.refresh()

        arr = [
            list('##########################################'),
            list('#      #           #      #              #'),
            list('#      #   #########   #  #   #          #'),
            list('#                      #      #          #'),
            list('##########################################')
        ]
        WALL = '#'
        self.x = 1
        self.y = 1
        self.hero = 'H'
        self.herocolor = Graphics.RED
        arr[self.x][self.y] = self.hero
        arr = [[(e, {
            '#': Graphics.GREEN,
            self.hero: self.herocolor,
            Graphics.EMPTY: Graphics.WHITE
        }[e]) for e in row] for row in arr]
        self.graphics = Graphics(
            arr
        )  #, {'#':Graphics.GREEN, self.hero:self.herocolor} , startX, startY)
        self.key_funcs = {
            ord('w'): up,
            ord('s'): down,
            ord('a'): left,
            ord('d'): right
        }
        self.refresh()