Example #1
0
	def update_board_render_bounds( self ):
		position_rect = [ -5, -5, 5, 5 ]
		left, top, right, bottom = 0, 1, 2, 3
		x, y = 0, 1

		for tile in self.tiles:
			position = tile.get_position().get()

			position_rect[ left ] = min( position[ x ], position_rect[ left ] )
			position_rect[ right ] = max( position[ x ], position_rect[ right ] )

			position_rect[ top ] = min( position[ y ], position_rect[ top ] )
			position_rect[ bottom ] = max( position[ y ], position_rect[ bottom ] )

		self.__render_bounds = [
			Draw.get_render_position( Position( [ position_rect[ left ], position_rect[ top ] ] ) ),
			Draw.get_render_position( Position( [ position_rect[ right ], position_rect[ bottom ] ] ) )
		]

		top_left, bottom_right = 0, 1
		self.__render_bounds[ top_left ][ x ] -= 1.5 * texture_manager.average_width()
		self.__render_bounds[ bottom_right ][ x ] += 2.5 * texture_manager.average_width()

		self.__render_bounds[ top_left ][ y ] -= 0.5 * texture_manager.average_height()
		self.__render_bounds[ bottom_right ][ y ] += 1.5 * texture_manager.average_height()

		Draw.set_render_bounds( self.__render_bounds )
Example #2
0
	def render( self, surface ):

		width = int( self.__render_bounds[ 1 ][ 0 ] - self.__render_bounds[ 0 ][ 0 ] )
		height = int( self.__render_bounds[ 1 ][ 1 ] - self.__render_bounds[ 0 ][ 1 ] )
		render_surface = pygame.Surface( ( width, height ) )

		# Make sure we render the tiles under beetles first
		rendered_tiles = []
		for tile in self.tiles:
			def render_tile( tile ):
				if tile.type == TileType.beetle and tile.tile_underneith is not None:
					render_tile( tile.tile_underneith )

				tile.render( render_surface )
				rendered_tiles.append( tile )

			if tile not in rendered_tiles:
				render_tile( tile )

		# Render the coordinates of all tiles and their adjacent pieces
		# We're rendering each coordinate multiple times here, but it shouldn't matter too much
		for tile in self.tiles:
			for position in tile.get_position().get_adjacent_positions():
				Draw.coordinate( render_surface, position )

		# Scale and blit our render surface to the screen surface
		scaled_render_surface = pygame.transform.scale( render_surface, [ width, height ] )
		surface.blit( scaled_render_surface, [ 0, 0 ] )
    def plot_clusters_all(self):
        """
        plot clusters for all regions of japan 
        you can select the number of clusters and the time period you want 
        """
        # auxiliar classes that we'll be needed 
        draw = Draw() 
        cat = Catalog()        

        # information relative to the regions
        BOUNDS = 0
        ZOOM_INDEX = 1
        ZOOM_VALUE = 9
        info = {}
        info["kanto"] =  [cat.get_kanto_bounds(), ZOOM_VALUE]
        #info["kansai"] = [cat.get_kansai_bounds(), ZOOM_VALUE]
        #info["tohoku"] = [cat.get_tohoku_bounds(), ZOOM_VALUE]
        #info["east_japan"] = [cat.get_east_japan_bounds(), ZOOM_VALUE]

        # list containing the number of clusters to plot and the time period to consider
        num_cluster = [10]
        time_period = [[0.0, 12 * 366 * 24.0 * 3600.0]] 

        # get all valid combinations
        combinations = list(itertools.product(info, num_cluster, time_period))
        REGION_IND = 0
        CLUSTER_IND = 1
        TIME_IND = 2

        # iterate through all combinations
        for comb in combinations: 
            
            # get region
            region = comb[REGION_IND]

            # folder we save the results into 
            folder = '../images/single_link/'

            # obtain array of quakes
            path = '../results/single_link/declustered_array_' + region
            quakes = pickle.load(open(path, 'rb'))

            # plot background for current region
            draw.plot_quakes_coast_slc(quakes, comb[TIME_IND], num_clusters = comb[CLUSTER_IND])
            call(["mv", "temp.png", folder + region + "_back_coast-1.png"])
            input("Edit the image and then press Enter")

            # plot cluster for the current data we have 
            self.plot_clusters(quakes, comb[CLUSTER_IND], comb[TIME_IND],  folder + region +"_back_coast-1.png")
            
            # save it in the correct format and do cleaning
            call(["mv", "temp.png", folder + region + "_clusters_coast.png"])
Example #4
0
    def restart(self):
        """Start or restart the plugin."""

        self.draw = Draw() # Utility for drawing 2D lines and shapes in 3-space
        path = Path([Vec2(40,40),Vec2(40,-40),Vec2(-40,40),Vec2(-40,-40)])
        for vehicle in self.vehicles[:3]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        c=(.6,.6,.6,.3)
        t=1
        z=1.5
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)
        path = Path([Vec2(-40,-40),Vec2(40,-40),Vec2(-40,40),Vec2(40,40)])
        for vehicle in self.vehicles[3:]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)        
        for vehicle in self.vehicles:
            vehicle.avoidObstacles = True
            vehicle.avoidVehicles = True
            vehicle.maxforce = 0.1
            vehicle.maxspeed = 0.5 + (random.random()/2)            
        node = self.draw.create()
        np = NodePath(node)   
        np.reparentTo(render)
Example #5
0
 def __submitSource(self):
     "listener for visual button"
     source = self.source_text.get("1.0", END)
     if "" != source:
         current_view = Draw(self)
         current_view.initDot()
         current_view.setSource(source, self.dict_with_label.get())
         current_view.show()
Example #6
0
def test_plot():
    stock = testdata()
    draw = Draw("N225", "日経平均株価")

    ti = TechnicalIndicators(stock)

    rsi = ti.calc_rsi(timeperiod=9)
    rsi = ti.calc_rsi(timeperiod=14)
    roc = ti.calc_roc()
    roc = ti.calc_roc(timeperiod=25)
    mfi = ti.calc_mfi()
    ultosc = ti.calc_ultosc()
    stoch = ti.calc_stoch()
    willr = ti.calc_willr()
    tr = ti.calc_tr()
    vr = ti.calc_volume_rate()

    ewma = ti.calc_ewma(span=5)
    ewma = ti.calc_ewma(span=25)
    ewma = ti.calc_ewma(span=50)
    ewma = ti.calc_ewma(span=75)
    bbands = ti.calc_bbands()
    sar = ti.calc_sar()

    draw.plot(stock, ewma, bbands, sar,
              rsi, roc, mfi, ultosc, willr,
              stoch, tr, vr,
              clf_result=0, reg_result=5000,
              ref=[])

    eq_(draw.code, 'N225')
    eq_(draw.name, '日経平均株価')

    filename = 'chart_N225.png'
    expected = True
    eq_(expected, os.path.exists(filename))

    if os.path.exists(filename):
        os.remove(filename)
Example #7
0
 def __init__(self):
     self.moving_balls = deque([])
     self.hitted_balls = deque([])
     self.potted = []
     pygame.display.set_caption('Cool Snooker')
     self.table = pygame.image.load('Snooker_table3.png')
     self.white_ball = balls.WhiteBall(coords=POS_WHITE)
     self.redball1 = balls.RedBall(coords=POS_RED1)
     self.redball2 = balls.RedBall(coords=POS_RED2)
     self.redball3 = balls.RedBall(coords=POS_RED3)
     self.redball4 = balls.RedBall(coords=POS_RED4)
     self.redball5 = balls.RedBall(coords=POS_RED5)
     self.redball6 = balls.RedBall(coords=POS_RED6)
     self.redball7 = balls.RedBall(coords=POS_RED7)
     self.redball8 = balls.RedBall(coords=POS_RED8)
     self.redball9 = balls.RedBall(coords=POS_RED9)
     self.redball10 = balls.RedBall(coords=POS_RED10)
     self.redball11 = balls.RedBall(coords=POS_RED11)
     self.redball12 = balls.RedBall(coords=POS_RED12)
     self.redball13 = balls.RedBall(coords=POS_RED13)
     self.redball14 = balls.RedBall(coords=POS_RED14)
     self.redball15 = balls.RedBall(coords=POS_RED15)
     self.black = balls.ColorBall(coords=POS_BLACK, COLOR=BLACK, points=7)
     self.pink = balls.ColorBall(coords=POS_PINK, COLOR=PINK, points=6)
     self.blue = balls.ColorBall(coords=POS_BLUE, COLOR=BLUE, points=5)
     self.brown = balls.ColorBall(coords=POS_BROWN, COLOR=BROWN, points=4)
     self.green = balls.ColorBall(coords=POS_GREEN, COLOR=GREEN, points=3)
     self.yellow = balls.ColorBall(coords=POS_YELLOW,
                                   COLOR=YELLOW, points=2)
     self.first_player = Player("Selby")
     self.second_player = Player("O'Sullivan")
     self.all_balls = deque([
                            self.redball1, self.redball2, self.redball3,
                            self.redball4, self.redball5, self.redball6,
                            self.redball7, self.redball8, self.redball9,
                            self.redball10, self.redball11, self.redball12,
                            self.redball13, self.redball14, self.redball15,
                            self.white_ball, self.black, self.pink,
                            self.blue, self.brown, self.green, self.yellow
                            ])
     self.cue = Cue()
     self.turn = self.first_player
     self.board_status = STATICK
     self.colol_order = iter([x for x in range(2, 8)])
     self.next_target_ball = next(self.colol_order)
     self.condition = STILL_RED
     self.score = Score()
     self.foul = False
     self.hit = False
     self.painter = Draw()
Example #8
0
class TestDraw(unittest.TestCase):

    def setUp(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.clock.tick(70)  # slow down
        self.drawer = Draw()
        self.constants = self.drawer.constants

    def test_show_menu(self):
        running = True
        while running:
            self.drawer.menu()
            pygame.display.flip()
            keys = pygame.key.get_pressed()
            for event in pygame.event.get():
                if event.type == pygame.QUIT or keys[pygame.K_q]:
                    running = False

    def test_show_instructions(self):
        running = True
        while running:
            self.drawer.instructions()
            pygame.display.flip()
            keys = pygame.key.get_pressed()
            for event in pygame.event.get():
                if event.type == pygame.QUIT or keys[pygame.K_q]:
                    running = False

    def test_show_bricks(self):
        running = True
        self.levels = Levels()
        self.levels.load_level(1)
        level = self.levels.return_loaded_level()
        y_ofs = 35
        # y_ofs = constants.V_OFFSET
        self.bricks = []
        for i in range(len(level)):
            # x_ofs = 35
            x_ofs = self.constants.MIN_BRICKS_X + 35
            for j in range(len(level[i])):
                if level[i][j] is 'x':
                    self.bricks.append(pygame.Rect(
                        x_ofs, y_ofs,
                        self.constants.BRICK_WIDTH,
                        self.constants.BRICK_HEIGHT
                    ))
                x_ofs += self.constants.BRICK_WIDTH + 10
            y_ofs += self.constants.BRICK_HEIGHT + 5
        while running:
            self.drawer.bricks(self.bricks)
            pygame.display.flip()
            keys = pygame.key.get_pressed()
            for event in pygame.event.get():
                if event.type == pygame.QUIT or keys[pygame.K_q]:
                    running = False
Example #9
0
    def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_color="viridis"):
        """
        Draws molecule through Molecule() and then puts the final figure together with
        Figure().
        """
        self.molecule = Molecule(self.topol_data)

        self.draw = Draw(self.topol_data,self.molecule,self.hbonds,self.pistacking,self.salt_bridges,self.lig_descr)
        self.draw.draw_molecule(data_for_color, data_for_size, data_for_clouds, rot_bonds, color_for_clouds, color_type_color)

        self.figure = Figure(self.molecule,self.topol_data,self.draw)
        self.figure.add_bigger_box()
        self.figure.manage_the_plots()
        self.figure.draw_white_circles()
        self.figure.put_everything_together()
        self.figure.write_final_draw_file(self.output_name)
Example #10
0
	def create_scaled_image( self ):
		scale_factor = 1
		tile_underneith = self.tile_underneith

		while tile_underneith is not None:
			scale_factor *= 0.75

			if tile_underneith.type == TileType.beetle:
				assert tile_underneith != tile_underneith.tile_underneith

				tile_underneith = tile_underneith.tile_underneith
			else:
				tile_underneith = None

		self.__scaled_image = pygame.transform.scale( self.image, 
			[ int( self.image.get_width() * scale_factor ), int( self.image.get_height() * scale_factor ) ] )

		self.__render_position = Draw.get_render_position( self.get_position() )
		self.__render_position[ 0 ] += ( self.image.get_width() - self.__scaled_image.get_width() ) / 2
		self.__render_position[ 1 ] += ( self.image.get_height() - self.__scaled_image.get_height() ) / 2
Example #11
0
class Engine():

    draw = None
    board = None

    def __init__(self):
        self.draw = Draw()
        self.board = Board()
        self.draw.set_board(self.board)

    def run(self):

        info = self.draw.get_board_info()

        self.board.set_cols(info['cols'])
        self.board.set_lines(info['lines'])

        self.draw.draw_board()

        while True:
            self.board.update()
            self.draw.draw_board()

            time.sleep(0.1)
Example #12
0
	def set_position( self, position, board ):
		self.__position.set( position )
		self.__render_position = Draw.get_render_position( self.__position )
Example #13
0
	def render( self, surface ):
		Draw.image_explicit( surface, self.__scaled_image, *self.__render_position )
Example #14
0
    def run(self):
        io = FileIO()
        will_update = self.update

        if self.csvfile:
            stock_tse = io.read_from_csv(self.code, self.csvfile)

            msg = "".join(["Read data from csv: ", self.code, " Records: ", str(len(stock_tse))])
            print(msg)

            if self.update and len(stock_tse) > 0:
                index = pd.date_range(start=stock_tse.index[-1], periods=2, freq="B")
                ts = pd.Series(None, index=index)
                next_day = ts.index[1]
                t = next_day.strftime("%Y-%m-%d")
                newdata = io.read_data(self.code, start=t, end=self.end)

                msg = "".join(["Read data from web: ", self.code, " New records: ", str(len(newdata))])
                print(msg)
                if len(newdata) < 1:
                    will_update = False
                else:
                    print(newdata.ix[-1, :])

                stock_tse = stock_tse.combine_first(newdata)
                io.save_data(stock_tse, self.code, "stock_")
        else:
            stock_tse = io.read_data(self.code, start=self.start, end=self.end)

            msg = "".join(["Read data from web: ", self.code, " Records: ", str(len(stock_tse))])
            print(msg)

        if stock_tse.empty:
            msg = "".join(["Data empty: ", self.code])
            print(msg)
            return None

        if not self.csvfile:
            io.save_data(stock_tse, self.code, "stock_")

        try:
            stock_d = stock_tse.asfreq("B").dropna()[self.days :]

            ti = TechnicalIndicators(stock_d)

            ti.calc_sma()
            ti.calc_sma(timeperiod=5)
            ti.calc_sma(timeperiod=25)
            ti.calc_sma(timeperiod=50)
            ti.calc_sma(timeperiod=75)
            ewma = ti.calc_ewma(span=5)
            ewma = ti.calc_ewma(span=25)
            ewma = ti.calc_ewma(span=50)
            ewma = ti.calc_ewma(span=75)
            bbands = ti.calc_bbands()
            sar = ti.calc_sar()
            draw = Draw(self.code, self.name)

            ret = ti.calc_ret_index()
            ti.calc_vol(ret["ret_index"])
            rsi = ti.calc_rsi(timeperiod=9)
            rsi = ti.calc_rsi(timeperiod=14)
            mfi = ti.calc_mfi()
            roc = ti.calc_roc(timeperiod=10)
            roc = ti.calc_roc(timeperiod=25)
            roc = ti.calc_roc(timeperiod=50)
            roc = ti.calc_roc(timeperiod=75)
            roc = ti.calc_roc(timeperiod=150)
            ti.calc_cci()
            ultosc = ti.calc_ultosc()
            stoch = ti.calc_stoch()
            ti.calc_stochf()
            ti.calc_macd()
            willr = ti.calc_willr()
            ti.calc_momentum(timeperiod=10)
            ti.calc_momentum(timeperiod=25)
            tr = ti.calc_tr()
            ti.calc_atr()
            ti.calc_natr()
            vr = ti.calc_volume_rate()

            ret_index = ti.stock["ret_index"]
            clf = Classifier(self.clffile)
            train_X, train_y = clf.train(ret_index, will_update)
            msg = "".join(["Train Records: ", str(len(train_y))])
            print(msg)
            clf_result = clf.classify(ret_index)[0]
            msg = "".join(["Classified: ", str(clf_result)])
            print(msg)
            ti.stock.ix[-1, "classified"] = clf_result

            reg = Regression(self.regfile, alpha=1, regression_type="Ridge")
            train_X, train_y = reg.train(ret_index, will_update)
            msg = "".join(["Train Records: ", str(len(train_y))])
            base = ti.stock_raw["Adj Close"][0]
            reg_result = int(reg.predict(ret_index, base)[0])
            msg = "".join(["Predicted: ", str(reg_result)])
            print(msg)
            ti.stock.ix[-1, "predicted"] = reg_result

            if len(self.reference) > 0:
                ti.calc_rolling_corr(self.reference)
                ref = ti.stock["rolling_corr"]
            else:
                ref = []

            io.save_data(io.merge_df(stock_d, ti.stock), self.code, "ti_")

            draw.plot(
                stock_d,
                ewma,
                bbands,
                sar,
                rsi,
                roc,
                mfi,
                ultosc,
                willr,
                stoch,
                tr,
                vr,
                clf_result,
                reg_result,
                ref,
                axis=self.axis,
                complexity=self.complexity,
            )

            return ti

        except (ValueError, KeyError):
            msg = "".join(["Error occured in ", self.code])
            print(msg)
            return None
Example #15
0
 def setUp(self):
     pygame.init()
     self.clock = pygame.time.Clock()
     self.clock.tick(70)  # slow down
     self.drawer = Draw()
     self.constants = self.drawer.constants
Example #16
0
    def run(self):
        io = FileIO()
        will_update = self.update

        if self.csvfile:
            stock_tse = io.read_from_csv(self.code,
                                         self.csvfile)

            msg = "".join(["Read data from csv: ", self.code,
                           " Records: ", str(len(stock_tse))])
            print(msg)

            if self.update and len(stock_tse) > 0:
                index = pd.date_range(start=stock_tse.index[-1],
                                      periods=2, freq='B')
                ts = pd.Series(None, index=index)
                next_day = ts.index[1]
                t = next_day.strftime('%Y-%m-%d')
                newdata = io.read_data(self.code,
                                       start=t,
                                       end=self.end)

                msg = "".join(["Read data from web: ", self.code,
                               " New records: ", str(len(newdata))])
                print(msg)
                if len(newdata) < 1:
                    will_update = False
                else:
                    print(newdata.ix[-1, :])

                stock_tse = stock_tse.combine_first(newdata)
                io.save_data(stock_tse, self.code, 'stock_')
        else:
            stock_tse = io.read_data(self.code,
                                     start=self.start,
                                     end=self.end)

            msg = "".join(["Read data from web: ", self.code,
                           " Records: ", str(len(stock_tse))])
            print(msg)

        if stock_tse.empty:
            msg = "".join(["Data empty: ", self.code])
            print(msg)
            return None

        if not self.csvfile:
            io.save_data(stock_tse, self.code, 'stock_')

        try:
            stock_d = stock_tse.asfreq('B').dropna()[self.days:]

            ti = TechnicalIndicators(stock_d)

            ti.calc_sma()
            ti.calc_sma(timeperiod=5)
            ti.calc_sma(timeperiod=25)
            ti.calc_sma(timeperiod=50)
            ti.calc_sma(timeperiod=75)
            ewma = ti.calc_ewma(span=5)
            ewma = ti.calc_ewma(span=25)
            ewma = ti.calc_ewma(span=50)
            ewma = ti.calc_ewma(span=75)
            bbands = ti.calc_bbands()
            sar = ti.calc_sar()
            draw = Draw(self.code, self.fullname)

            ret = ti.calc_ret_index()
            ti.calc_vol(ret['ret_index'])
            rsi = ti.calc_rsi(timeperiod=9)
            rsi = ti.calc_rsi(timeperiod=14)
            mfi = ti.calc_mfi()
            roc = ti.calc_roc(timeperiod=10)
            roc = ti.calc_roc(timeperiod=25)
            roc = ti.calc_roc(timeperiod=50)
            roc = ti.calc_roc(timeperiod=75)
            roc = ti.calc_roc(timeperiod=150)
            ti.calc_cci()
            ultosc = ti.calc_ultosc()
            stoch = ti.calc_stoch()
            ti.calc_stochf()
            ti.calc_macd()
            willr = ti.calc_willr()
            ti.calc_momentum(timeperiod=10)
            ti.calc_momentum(timeperiod=25)
            tr = ti.calc_tr()
            ti.calc_atr()
            ti.calc_natr()
            vr = ti.calc_volume_rate()

            ret_index = ti.stock['ret_index']
            clf = Classifier(self.clffile)
            train_X, train_y = clf.train(ret_index, will_update)
            msg = "".join(["Train Records: ", str(len(train_y))])
            print(msg)
            clf_result = clf.classify(ret_index)[0]
            msg = "".join(["Classified: ", str(clf_result)])
            print(msg)
            ti.stock.ix[-1, 'classified'] = clf_result

            reg = Regression(self.regfile,
                             alpha=1,
                             regression_type="Ridge")
            train_X, train_y = reg.train(ret_index, will_update)
            msg = "".join(["Train Records: ", str(len(train_y))])
            base = ti.stock_raw['Adj Close'][0]
            reg_result = int(reg.predict(ret_index, base)[0])
            msg = "".join(["Predicted: ", str(reg_result)])
            print(msg)
            ti.stock.ix[-1, 'predicted'] = reg_result

            if len(self.reference) > 0:
                ti.calc_rolling_corr(self.reference)
                ref = ti.stock['rolling_corr']
            else:
                ref = []

            io.save_data(io.merge_df(stock_d, ti.stock),
                         self.code, 'ti_')

            draw.plot(stock_d, ewma, bbands, sar,
                      rsi, roc, mfi, ultosc, willr,
                      stoch, tr, vr,
                      clf_result, reg_result,
                      ref,
                      axis=self.axis,
                      complexity=self.complexity)

            return ti

        except (ValueError, KeyError) as e:
            print("Error occured in", self.code, "at analysis.py")
            print('type:', str(type(e)))
            print('args:', str(e.args))
            print('message:', e.message)
            print('e:' + str(e))
            return None
class Game:
    clock = pygame.time.Clock()
    pockets = {
        "ur_pocket": [Vec2D(UR_POCKET), Vec2D(125, 94), Vec2D(113, 78), Vec2D(143, 75), Vec2D(128, 63)],
        "ul_pocket": [Vec2D(UL_POCKET), Vec2D(125, 480), Vec2D(113, 495), Vec2D(143, 498), Vec2D(128, 510)],
        "dl_pocket": [Vec2D(DL_POCKET), Vec2D(974, 480), Vec2D(986, 495), Vec2D(956, 498), Vec2D(971, 510)],
        "dr_pocket": [Vec2D(DR_POCKET), Vec2D(956, 75), Vec2D(971, 63), Vec2D(974, 94), Vec2D(986, 79)],
        "ml_pocket": [Vec2D(ML_POCKET), Vec2D(530, 498), Vec2D(539, 510), Vec2D(568, 498), Vec2D(560, 510)],
        "mr_pocket": [Vec2D(MR_POCKET), Vec2D(530, 75), Vec2D(539, 63), Vec2D(568, 75), Vec2D(560, 63)],
    }

    def __init__(self):
        self.moving_balls = deque([])
        self.hitted_balls = deque([])
        self.potted = []
        pygame.display.set_caption("Cool Snooker")
        self.table = pygame.image.load("Snooker_table3.png")
        self.white_ball = balls.WhiteBall(coords=POS_WHITE)
        self.redball1 = balls.RedBall(coords=POS_RED1)
        self.redball2 = balls.RedBall(coords=POS_RED2)
        self.redball3 = balls.RedBall(coords=POS_RED3)
        self.redball4 = balls.RedBall(coords=POS_RED4)
        self.redball5 = balls.RedBall(coords=POS_RED5)
        self.redball6 = balls.RedBall(coords=POS_RED6)
        self.redball7 = balls.RedBall(coords=POS_RED7)
        self.redball8 = balls.RedBall(coords=POS_RED8)
        self.redball9 = balls.RedBall(coords=POS_RED9)
        self.redball10 = balls.RedBall(coords=POS_RED10)
        self.redball11 = balls.RedBall(coords=POS_RED11)
        self.redball12 = balls.RedBall(coords=POS_RED12)
        self.redball13 = balls.RedBall(coords=POS_RED13)
        self.redball14 = balls.RedBall(coords=POS_RED14)
        self.redball15 = balls.RedBall(coords=POS_RED15)
        self.black = balls.ColorBall(coords=POS_BLACK, COLOR=BLACK, points=7)
        self.pink = balls.ColorBall(coords=POS_PINK, COLOR=PINK, points=6)
        self.blue = balls.ColorBall(coords=POS_BLUE, COLOR=BLUE, points=5)
        self.brown = balls.ColorBall(coords=POS_BROWN, COLOR=BROWN, points=4)
        self.green = balls.ColorBall(coords=POS_GREEN, COLOR=GREEN, points=3)
        self.yellow = balls.ColorBall(coords=POS_YELLOW, COLOR=YELLOW, points=2)
        self.first_player = Player("Player 1")
        self.second_player = Player("Player 2")
        self.all_balls = deque(
            [
                self.redball1,
                self.redball2,
                self.redball3,
                self.redball4,
                self.redball5,
                self.redball6,
                self.redball7,
                self.redball8,
                self.redball9,
                self.redball10,
                self.redball11,
                self.redball12,
                self.redball13,
                self.redball14,
                self.redball15,
                self.white_ball,
                self.black,
                self.pink,
                self.blue,
                self.brown,
                self.green,
                self.yellow,
            ]
        )
        self.cue = Cue()
        self.turn = self.first_player
        self.board_status = STATICK
        self.colol_order = iter([x for x in range(2, 8)])
        self.next_target_ball = next(self.colol_order)
        self.condition = STILL_RED
        self.score = Score()
        self.foul = False
        self.hit = False
        self.painter = Draw()

    def ball_update(self):
        for a in range(0, len(self.all_balls) - 1):
            for b in range(a + 1, len(self.all_balls)):
                ball, next_ball = self.all_balls[a], self.all_balls[b]
                delta = next_ball.coords - ball.coords
                if (next_ball.coords - ball.coords).length <= ball.RADIUS * 2:
                    if ball.velocity.length > 0 and next_ball.velocity.length > 0:
                        ball.coords += Vec2D.normalized(delta) * (delta.length - ball.RADIUS * 2)
                        next_ball.coords += Vec2D.normalized(-delta) * (delta.length - ball.RADIUS * 2)
                        self.ball_collision(ball, next_ball)
                    elif ball.velocity.length > 0:
                        if isinstance(ball, balls.WhiteBall):
                            self.hitted_balls.append(next_ball)
                        ball.coords += Vec2D.normalized(delta) * (delta.length - ball.RADIUS * 2)
                        self.ball_collision(ball, next_ball)
                    elif next_ball.velocity.length > 0:
                        if isinstance(next_ball, balls.WhiteBall):
                            self.hitted_balls.append(ball)
                        next_ball.coords += Vec2D.normalized(-delta) * (delta.length - ball.RADIUS * 2)
                        self.ball_collision(ball, next_ball)

    def balls_handler(self):
        for ball in self.all_balls:
            if ball.velocity.length > 0:
                ball.move(self.pockets)
            if ball.is_potted and ball not in self.potted:
                self.potted.append(ball)
            if ball.vizibility:
                self.painter.draw_balls(ball)

    def white_ball_grab(self):
        mouse_pos = Vec2D(pygame.mouse.get_pos())
        if (
            self.white_ball.coords.x - 8 < mouse_pos.x < self.white_ball.coords.x + 8
            and self.white_ball.coords.y - 8 < mouse_pos.y < self.white_ball.coords.y + 8
        ):
            for event in pygame.event.get():
                (mouse1, mouse2, mouse3) = pygame.mouse.get_pressed()
                if mouse1:
                    self.white_ball.grabed = True
                else:
                    self.white_ball.grabed = False
        if self.white_ball.grabed:
            self.white_ball.coords = mouse_pos

    def cue_handler(self):
        start_pos, end_pos = self.cue.get_cue_pos(self.white_ball.coords)
        self.painter.cue_draw(self.cue, start_pos, end_pos)
        keys = pygame.key.get_pressed()
        if keys[pygame.K_KP_ENTER]:
            new_velocity = Vec2D.normalized(start_pos - end_pos)
            force = Vec2D(self.white_ball.coords - start_pos).length
            self.white_ball.velocity = new_velocity * force ** 2 / MIN_HITTING_FORCE
            self.hit = True

    def if_statick_board(self):
        for ball in self.all_balls:
            if ball.velocity.length > 0 and ball not in self.moving_balls:
                self.moving_balls.append(ball)
            elif ball in self.moving_balls and ball.velocity.length == 0:
                self.moving_balls.remove(ball)
        if not self.moving_balls:
            self.board_status = STATICK
        else:
            self.board_status = NON_STATICK

    def potted_ball_handler(self, potted, color_points=None):
        red_ball = 0
        color_ball = 0
        points = 0
        if color_points is None:
            color_points = [0]
        else:
            color_points = color_points
        for ball in potted:
            if isinstance(ball, balls.WhiteBall):
                self.foul = True
            if isinstance(ball, balls.ColorBall):
                color_ball += 1
                color_points.append(ball.points)
                if self.turn.target != COLOR_TARGET:
                    self.foul = True
            if isinstance(ball, balls.RedBall):
                if self.turn.target != RED_TARGET:
                    self.foul = True
                red_ball += 1
                points += ball.points
            ball.velocity = Vec2D(0, 0)
            if isinstance(ball, balls.RedBall):
                self.all_balls.remove(ball)
                ball.is_potted = False
            else:
                self.ball_return(ball)
            ball.is_potted = False
        self.potted = []
        if color_ball > 1 or (red_ball > 0 and color_ball > 0):
            self.foul = True
        if self.foul is True:
            # print("Foul wrong ball potted")
            self.change_turn()
            if max(color_points) > FOUL_POINTS:
                self.turn.points += max(color_points)
            else:
                self.turn.points += FOUL_POINTS
        else:
            if self.turn.target == RED_TARGET:
                self.turn.points += points
            else:
                self.turn.points += max(color_points)
            self.turn.change_target()

    def game_handler(self):
        self.score.show_score(self.first_player, self.second_player, self.turn)
        self.ball_update()
        self.if_statick_board()
        self.check_condition()
        self.foul = False
        if self.board_status == STATICK:
            if not self.hitted_balls and self.hit is True and not self.potted:
                self.change_turn()
                self.turn.points += FOUL_POINTS
                # print("Foul no ball hit")
            self.hit = False
            self.cue_handler()
            if self.hitted_balls:
                if self.condition == STILL_RED:
                    if (isinstance(self.hitted_balls[0], balls.ColorBall) and self.turn.target != COLOR_TARGET) or (
                        isinstance(self.hitted_balls[0], balls.RedBall) and self.turn.target != RED_TARGET
                    ):
                        if not self.potted:
                            self.foul = True
                            self.change_turn()
                            # print("Foul wrong ball hit")
                            if self.hitted_balls[0].points > FOUL_POINTS:
                                self.turn.points += self.hitted_balls[0].points
                            else:
                                self.turn.points += FOUL_POINTS
                        else:
                            self.foul = True
                            points = [self.hitted_balls[0].points]
                            self.potted_ball_handler(self.potted, color_points=points)
                    if self.potted and self.foul is not True:
                        self.potted_ball_handler(self.potted)
                    elif self.foul is not True:
                        # print("No ball poted")
                        self.change_turn()
                else:
                    self.no_red_game_handler()
                self.hitted_balls = deque([])
            if self.potted:
                self.potted_ball_handler(self.potted)

    def change_turn(self):
        if self.turn == self.first_player:
            self.turn = self.second_player
        else:
            self.turn = self.first_player
        self.turn.target = RED_TARGET

    def ball_return(self, potted_ball):
        potted_ball.vizibility = True
        returning_pos = Vec2D(potted_ball.pos)
        color_balls_pos = [x.pos for x in self.all_balls if isinstance(x, balls.ColorBall)]
        empty_place = False
        my_place_taken = self.chek_for_place(potted_ball)
        if my_place_taken is True:
            for position in color_balls_pos:
                empty_position = self.chek_for_place(potted_ball, pos=position)
                if empty_position is not True:
                    empty_place = True
                    returning_pos = position
                    break
        if my_place_taken is True and empty_place is not True:
            found_place = False
            while found_place is not True:
                flag = self.chek_for_place(potted_ball, pos=returning_pos)
                if flag is not True:
                    found_place = True
                    break
                returning_pos.x += 1
            potted_ball.coords = returning_pos
        else:
            potted_ball.coords = returning_pos

    def chek_for_place(self, potted_ball, pos=None):
        if pos is None:
            pos = potted_ball.pos
        for ball in self.all_balls:
            if ball is not potted_ball:
                delta = ball.coords - pos
                if delta.length < ball.RADIUS * 2:
                    return True
        return False

    def check_condition(self):
        flag = True
        for ball in self.all_balls:
            if isinstance(ball, balls.RedBall):
                flag = False
                break
        if flag:
            if self.turn.target == COLOR_TARGET:
                self.condition = STILL_RED
            else:
                self.condition = RED_FREE

    def no_red_game_handler(self):
        points = [0]
        if self.hitted_balls[0].points == self.next_target_ball:
            if self.potted:
                if len(self.potted) > 1:
                    # print("Foul more then 1 colorball potted")
                    self.change_turn()
                    for ball in self.potted:
                        points.append(ball.points)
                        self.ball_return(ball)
                        ball.is_potted = False
                    self.potted = []
                    if max(points) > FOUL_POINTS:
                        self.turn.points += max(points)
                    else:
                        self.turn.points += FOUL_POINTS
                else:
                    if self.potted[0].points == self.next_target_ball:
                        self.turn.points += self.potted[0].points
                        self.all_balls.remove(self.potted[0])
                        try:
                            self.next_target_ball = next(self.colol_order)
                        except:
                            self.next_target_ball = False
                            # print("Game finished")
                    else:
                        # print("Foul wrong colorball potted")
                        self.change_turn()
                        if self.potted[0].points > FOUL_POINTS:
                            self.turn.points += self.potted[0].points
                        else:
                            self.turn.points += FOUL_POINTS
                        self.ball_return(self.potted[0])
                    self.potted[0].is_potted = False
                    self.potted.remove(self.potted[0])
            else:
                # print("No colorball potted")
                self.change_turn()
        else:
            # print("Foul wrong colorball hited")
            self.change_turn()
            if self.potted:
                for ball in self.potted:
                    points.append(ball.points)
                    self.ball_return(ball)
                    ball.is_potted = False
                self.potted = []
                points.append(self.hitted_balls[0].points)
                if max(points) > FOUL_POINTS:
                    self.turn.points += max(points)
                else:
                    self.turn.points += FOUL_POINTS
            else:
                if self.hitted_balls[0].points > FOUL_POINTS:
                    self.turn.points += self.hitted_balls[0].points
                else:
                    self.turn.points += FOUL_POINTS

    def ball_collision(self, ball, next_ball):
        delta = next_ball.coords - ball.coords
        unit_delta = Vec2D(delta / delta.get_length())
        unit_tangent = Vec2D(unit_delta.perpendicular())
        velocity_1_n = unit_delta.dot(ball.velocity)
        velocity_1_t = unit_tangent.dot(ball.velocity)
        velocity_2_n = unit_delta.dot(next_ball.velocity)
        velocity_2_t = unit_tangent.dot(next_ball.velocity)
        new_velocity_1_t = velocity_1_t
        new_velocity_2_t = velocity_2_t
        new_velocity_1_n = velocity_2_n
        new_velocity_2_n = velocity_1_n
        new_velocity_1_n = Vec2D(new_velocity_1_n * unit_delta)
        new_velocity_2_n = Vec2D(new_velocity_2_n * unit_delta)
        new_velocity_1_t = Vec2D(new_velocity_1_t * unit_tangent)
        new_velocity_2_t = Vec2D(new_velocity_2_t * unit_tangent)
        new_velocity_1 = Vec2D(new_velocity_1_n + new_velocity_1_t)
        new_velocity_2 = Vec2D(new_velocity_2_n + new_velocity_2_t)
        ball.velocity = new_velocity_1
        next_ball.velocity = new_velocity_2
Example #18
0
class Lintools(object):
    """This class controls the behaviour of all other classes (Data,Plots,Molecule,Figure)
     of lintools and inherits and transfers them resulting in a final SVG file that contains
     the protein-ligand interactions.

    It also controls the analysis (Residence_time and HBonds classes).

    Takes:
        * topology * - topology file
        * trajectory * - trajectory file(s)
        * mol_file * - MOL file of the ligand
        * ligand * - MDAnalysis atomgroup of ligand that is going to be analysed
        * offset * - residue offset which determines by how many numbers the protein residue numbering
        should be offset (e.g. with offset = 30 the first residue will be changed from 1 to 30, 2 - 31, etc.)
        * cutoff * - cutoff distance in angstroms that defines the native contacts (default - 3.5A)
        * start_frame * - start frame(s) for trajectory analysis (can be different for each trajectory)
        * end_frame * - end frame(s) for trajectory analysis (can be different for each trajectory)
        * skip * - number of frames to skip (can be different for each trajectory)
        * analysis_cutoff * - a fraction of time a residue has to fullfil the analysis parameters for (default - 0.3)
        * sasa * - set this to 1 to turn on solvent accessible surface area calculation (currently only works across whole trajectory)
        * diagram_type * - string of the selected diagram type (e.g. "amino" or "clocks")
        * output_name * - name of the folder with results and the final SVG file

    """
    __version__ = "06.2018"
    def __init__(self,topology,trajectory,mol_file,ligand,offset,cutoff,start_frame,end_frame,skip,analysis_cutoff,sasa,diagram_type,output_name,cfg):
        """Defines the input variables."""
        self.topology = os.path.abspath(topology)
        try:
            self.trajectory = []
            for traj in trajectory:
                self.trajectory.append(os.path.abspath(traj))
        except Exception:
            self.trajectory = []
        if mol_file!=None:
            self.mol_file = os.path.abspath(mol_file)
        else:
            self.mol_file = mol_file
        self.ligand = ligand
        self.offset = offset
        self.cutoff = cutoff
        if cfg==False:
            self.start = [None if start_frame==[None] else int(start_frame[i]) for i in range(len(trajectory))]
            self.end = [None if end_frame==[None] else int(end_frame[i]) for i in range(len(trajectory))]
            self.skip = [None if skip==[None] else int(skip[i]) for i in range(len(trajectory))]
        else:
            self.start = start_frame
            self.end = end_frame
            self.skip = skip
        self.analysis_cutoff = analysis_cutoff
        self.sasa = sasa
        self.diagram_type = diagram_type
        self.output_name = output_name
    def data_input_and_res_time_analysis(self):
        """
        Loads the data into Data() - renumbers the residues, imports mol file in rdkit.
        If there are trajectories to analyse, the residues that will be plotted are determined
        from Residence_time() analysis.
        """
        self.topol_data = Data()
        self.topol_data.load_data(self.topology,self.mol_file,self.ligand,self.offset)
        if len(self.trajectory) == 0:
            self.topol_data.analyse_topology(self.topology,self.cutoff)
        else:
            self.res_time = Residence_time(self.topol_data,self.trajectory, self.start, self.end, self.skip,self.topology, self.ligand,self.offset)
            self.res_time.measure_residence_time(self.cutoff)
            self.res_time.define_residues_for_plotting_traj(self.analysis_cutoff)
            self.topol_data.find_the_closest_atoms(self.topology)
    def analysis_of_prot_lig_interactions(self):
        """
        The classes and function that deal with protein-ligand interaction analysis.
        """
        self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3)
        self.pistacking = PiStacking(self.topol_data,self.trajectory,self.start,self.end,self.skip, self.analysis_cutoff)
        if self.sasa==1:
            self.sasa = SASA(self.topol_data,self.trajectory)
        self.lig_descr = LigDescr(self.topol_data)
        if self.trajectory!=[]:
            self.rmsf = RMSF_measurements(self.topol_data,self.topology,self.trajectory,self.ligand,self.start,self.end,self.skip)
        self.salt_bridges = SaltBridges(self.topol_data,self.trajectory,self.lig_descr,self.start,self.end,self.skip,self.analysis_cutoff)
    def plot_residues(self):
        """
        Calls Plot() that plots the residues with the required diagram_type.
        """
        self.plots = Plots(self.topol_data,self.diagram_type)
    def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_color="viridis"):
        """
        Draws molecule through Molecule() and then puts the final figure together with
        Figure().
        """
        self.molecule = Molecule(self.topol_data)

        self.draw = Draw(self.topol_data,self.molecule,self.hbonds,self.pistacking,self.salt_bridges,self.lig_descr)
        self.draw.draw_molecule(data_for_color, data_for_size, data_for_clouds, rot_bonds, color_for_clouds, color_type_color)

        self.figure = Figure(self.molecule,self.topol_data,self.draw)
        self.figure.add_bigger_box()
        self.figure.manage_the_plots()
        self.figure.draw_white_circles()
        self.figure.put_everything_together()
        self.figure.write_final_draw_file(self.output_name)

    def save_files(self):
        """Saves all output from LINTools run in a single directory named after the output name."""
        while True:
            try:
                os.mkdir(self.output_name)
            except Exception as e:
                self.output_name = raw_input("This directory already exists - please enter a new name:")
            else:
                break
        self.workdir = os.getcwd()
        os.chdir(self.workdir+"/"+self.output_name)
    def write_config_file(self, cfg):
        if cfg!=None:
            #copy the config file to results directory
            shutil.copy("../"+cfg, "lintools.config")
        else:
            #If there was no config file, write one
            cfg_dir = {'input':{
                            'topology':self.topology,
                            'trajectory':self.trajectory,
                            'mol file':self.mol_file,
                            'ligand':self.ligand,
                            'traj start':self.start,
                            'traj end':self.end,
                            'traj skip': self.skip,
                            'offset': self.offset,
                            'distance cutoff': self.cutoff,
                            'analysis cutoff': self.analysis_cutoff,
                            'sasa': self.sasa,
                            'diagram type': self.diagram_type,
                            'output name': self.output_name},
                    'representation':{
                            'data to show in color':None,
                            'data to show as size':None,
                            'data to show as cloud':None,
                            'rotatable bonds':None,
                            'cloud color scheme':'Blues',
                            'atom color scheme':'viridis',
                            'clock color scheme':'summer'}
                            }

            with open("lintools.config","wb") as ymlfile:
                yaml.dump(cfg_dir,ymlfile,default_flow_style=False)
    def remove_files(self):
        """Removes intermediate files."""
        file_list = ["molecule.svg","lig.pdb","HIS.pdb","PHE.pdb","TRP.pdb","TYR.pdb","lig.mol","test.xtc"]
        for residue in self.topol_data.dict_of_plotted_res.keys():
            file_list.append(residue[1]+residue[2]+".svg")
        for f in file_list:
            if os.path.isfile(f)==True:
                os.remove(f)
Example #19
0
        "Method to create object if there are more than one attempt"
        return board.Board(self.__board, self.__fboard, self.__size)

    def createGameDisplay(self, obj):
        obj.createGameDisplay()
        pygame.display.update()


if __name__ == "__main__":
    plays = {}  #storing the number of plays

    #connect the backend with frontend
    pygame.init()
    screen_width = 500
    screen_height = 500
    startObj = Draw(screen_width, screen_height)

    while True:
        startObj.start_loop()
        print("\nPlayer #{}:\n".format(len(plays) + 1))

        while startObj.getStart():  #Catch any input error from the user's size
            pygame.time.wait(200)  #delay to avoid choosing the grip mistakenly
            startObj.chooseGridSize()

            try:
                print "size: ",
                size = startObj.getGridSize()
                print size
            except ValueError as VE:
                print("{}\n".format(VE))
Example #20
0
    def plot_clusters_all(self, array_path, dep_lim = None, map_background = True):
        """
        receives a path to the array of quakes.

        optionally it receives a depth limit and a map_background boolean
        if map_background = True, then the cluster is plot with a background map
        if map_background = False, then the cluster is plot with the coast of japan 
        as background 
        
        in order to plot study the mainshocks and it's associated clusters,
        plot some clusters on the map 
        """
        # obtain array of shocks within the depth limit 
        all_quakes = pickle.load(open(array_path, 'rb'))
        useful_quakes = []
        for index in range(len(all_quakes)):
            current_quake = all_quakes[index]
            if dep_lim != None and current_quake.depth > dep_lim:
                continue
            useful_quakes.append(current_quake)

        # get instance of classes so we can access methods
        draw = Draw()
        cat = Catalog()

        # get dictionary that for every region name gives bound and zoom for all regions
        regions = {}
        regions["japan"] = [cat.get_catalog_bounds('../catalogs/new_jma.txt'), 5]
        regions["kanto"] = [cat.get_kanto_bounds(), 9]
        regions["kansai"] = [cat.get_kansai_bounds(), 9]
        regions["tohoku"] = [cat.get_tohoku_bounds(), 9]
        regions["east_japan"] = [cat.get_east_japan_bounds(), 9]
        
        # index to add legibility to the code
        BOUNDS = 0
        ZOOM = 1
        
        # set list of how many clusters to plot, and which years to plot 
        num_clusters = [10]
        year_bound = [[0.0, 12*366*24.0*3600]] # this way we consider all years

        # iterate through the list containing how many clusters we plot
        for num in num_clusters:

            # iterate through the years 
            for time in year_bound:
                
                # iterate through the regions
                for region, info in regions.items():
                    
                    # if we need to plot a map in the background
                    if map_background:

                        # plot image for the current region 
                        draw.plot_image_quakes(useful_quakes, time, info[BOUNDS], info[ZOOM], num_clusters = num, dep_lim = dep_lim)
                        call(["pdftoppm", "-rx", "300", "-ry", "300", "-png", "Rplots.pdf", region + "_back"])
                        call(["mv",  region + "_back-1.png", "../images/"])
                        call(["rm", "Rplots.pdf"])
                        input("Edit the image and then press Enter")

                        # plot cluster for current region in the given year, for the current number of clusters
                        self.plot_clusters(useful_quakes, num, time, info[BOUNDS],  "../images/" + region +"_back-1.png")
                        ## save it in the correct format, and do cleaning
                        call(["mv", "temp.png", "../images/" + region + "_clusters_map.png"])
                    
                    # if we dont want to plot a japan map in the background
                    else:

                        # plot image for the current region 
                        draw.plot_quakes_coast(useful_quakes, time, info[BOUNDS], num_clusters = num, dep_lim = dep_lim)
                        call(["mv", "temp.png", "../images/" + region + "_back_coast-1.png"])
                        input("Edit the image and then press Enter")

                        # plot cluster for current region in the given year, for the current number of clusters
                        self.plot_clusters(useful_quakes, num, time, info[BOUNDS],  "../images/" + region +"_back_coast-1.png")
                                
                        ## save it in the correct format, and do cleaning
                        call(["mv", "temp.png", "../images/" + region + "_clusters_coast.png"])
Example #21
0
	def render( self, surface ):
		Draw.image( surface, self.image, self.__position )
Example #22
0
class Plugin(PandaSteerPlugin):
    """PandaSteer plugin demonstrating seek and flee steering behaviors."""
    
    def __init__(self):
        """Initialise the plugin."""
    
        PandaSteerPlugin.__init__(self)
    
        self.numVehicles = 6
        self.text = """"""
        self.obstaclesOn = True
        self.text = """Path Following:

Six vehicles follow two overlapping paths at different speeds.

Characters can steer around obstacles and other characters that intersect their
path (but cannot handle an obstacle that covers a waypoint).

This is a very primitive path following behaviour. A path is a list of 2D
waypoints. Characters first seek toward the nearest waypoint on the path, then
seek toward each following waypoint in turn. Because characters don't anticipate
the change of direction when passing a waypoint they may overshoot if moving too
fast, then have to find their way back to the path. When reaching the end of the
path, characters can either loop back to the first waypoint or can arrive and
stop at the final waypoint.
"""

        
    def restart(self):
        """Start or restart the plugin."""

        self.draw = Draw() # Utility for drawing 2D lines and shapes in 3-space
        path = Path([Vec2(40,40),Vec2(40,-40),Vec2(-40,40),Vec2(-40,-40)])
        for vehicle in self.vehicles[:3]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        c=(.6,.6,.6,.3)
        t=1
        z=1.5
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)
        path = Path([Vec2(-40,-40),Vec2(40,-40),Vec2(-40,40),Vec2(40,40)])
        for vehicle in self.vehicles[3:]:
            vehicle._pos = SteerVec((random.random()-0.5)*100,(random.random()-0.5)*100)
            vehicle._velocity = SteerVec((random.random()-0.5)*2,(random.random()-0.5)*2)
            vehicle.followPath(path,loop=True)
        self.draw.drawLine(Vec3(path[0].getX(),path[0].getY(),z),Vec3(path[1].getX(),path[1].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[1].getX(),path[1].getY(),z),Vec3(path[2].getX(),path[2].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[2].getX(),path[2].getY(),z),Vec3(path[3].getX(),path[3].getY(),z),color=c,thickness=t)
        self.draw.drawLine(Vec3(path[3].getX(),path[3].getY(),z),Vec3(path[0].getX(),path[0].getY(),z),color=c,thickness=t)        
        for vehicle in self.vehicles:
            vehicle.avoidObstacles = True
            vehicle.avoidVehicles = True
            vehicle.maxforce = 0.1
            vehicle.maxspeed = 0.5 + (random.random()/2)            
        node = self.draw.create()
        np = NodePath(node)   
        np.reparentTo(render)
Example #23
0
        if rectangles_second['red']:
            players_count['players2']['red'] = detectBall.calculate_sets(
                player_2, rectangles_second)

        if rectangles_second['white']:
            players_count['players2']['white'] = detectBall.calculate_games(
                player_2, rectangles_second)

        master_db.update(config.get('table_name'), 1,
                         ['red_balls', 'white_balls'], [
                             players_count['players1']['red'],
                             players_count['players1']['white']
                         ])
        master_db.update(config.get('table_name'), 2,
                         ['red_balls', 'white_balls'], [
                             players_count['players2']['red'],
                             players_count['players2']['white']
                         ])

        cv.imshow('players_1',
                  Draw.draw_rectangles(frame_first_players, player_1))
        cv.imshow('players_2',
                  Draw.draw_rectangles(frame_second_players, player_2))

        print(players_count)
        if cv.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv.destroyAllWindows()
Example #24
0
 def __init__(self):
     self.draw = Draw()
     self.board = Board()
     self.draw.set_board(self.board)
Example #25
0
import pygame
import random

GAMEOVER = pygame.USEREVENT  + 1
QUIT_USER = pygame.USEREVENT  + 2
game = Game()
game.start()
clock = pygame.time.Clock()
random.seed(clock)
loop = True
gameLoop = True
scoreLoop = True
playActive = True
exitActive = False
draw = Draw()
while loop:
    draw.drawMenu(playActive)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        playActive = True
    if keys[pygame.K_DOWN]:
        playActive = False
    if keys[pygame.K_RETURN]:
        if playActive:
            loop = False
            gameLoop = True
        else:
            pygame.event.post(pygame.event.Event(QUIT_USER))
    for event in pygame.event.get():
        if event.type == pygame.QUIT or event.type == QUIT_USER:
Example #26
0
import pygame, variables, math, game.main as Game
from draw import Draw
from endscreen import GameOver
from keyboard import Keyboard

# Initialise shit
CLOCK_SPEED = variables.CLOCK_SPEED
clock = pygame.time.Clock()
global clock_speed
key_handler = Keyboard()
draw = Draw()

# Game states
def start_game():
    global state, result
    state = 'game'
    result = Game.initialise()
    return variables.Movement.RIGHT

def end_game():
    global state, clock_speed
    clock_speed = CLOCK_SPEED
    state = 'over'
    return 0

pygame.init()

pygame.display.set_caption('ssnake')
screen = pygame.display.set_mode([variables.GAME_WIDTH, variables.GAME_HEIGHT])

direction = start_game()
Example #27
0
     listforname = ["MB_Command.Speed","MA_Command.Torque","Sensor-Torque",\
     "SUM/AVG-RMS.Voltage","SUM/AVG-F.Voltage","SUM/AVG-RMS.Current","SUM/AVG-F.Current",\
     "SUM/AVG-Kwatts","SUM/AVG-F.Kwatts","SUM/AVG-PF","SUM/AVG-F.PF","DC Current",\
     "MA-RTD 1","MA-RTD 2"]
     listforposition = ["G", "I", "K"]
     Dict_temp = TDMS(filename, group, listforname).Read_Tdms()
     Excel(Dict_temp, Excel_filename, sheetname,
           listforposition).WriteConti()
 elif Job_list[Job_num] == "High Speed":
     filename, group = DataPath().data_get()
     sheetname = "High Speed"
     listforname = ["MB_Command.Speed"]
     listforposition = ["J", "K"]
     Dict_temp = TDMS(filename, group, listforname).Read_Tdms()
     picname = filename[:-5] + ".png"
     RTD, i = Draw(filename, picname).drawXmin_returnRTD(5)
     Excel(Dict_temp, Excel_filename, sheetname,
           listforposition).WriteHighSpeed(RTD, picname, i)
 elif Job_list[Job_num] == "Winding Heating":
     filename, group = DataPath().data_get()
     sheetname = "Winding Heating"
     listforname = ["MA_Command.Torque","Sensor-Torque",\
     "U-PP.RMS.Voltage","V-PP.RMS.Voltage","W-PP.RMS.Voltage",\
     "SUM/AVG-RMS.Current"]#no need for RTD
     listforposition = ["L", "M"]
     Dict_temp = TDMS(filename, group, listforname).Read_Tdms()
     picname = filename[:-5] + ".png"
     RTD, i = Draw(filename, picname).drawXmin_returnRTD(8)
     Excel(Dict_temp, Excel_filename, sheetname,
           listforposition).WriteWinding(RTD, picname, i)
 elif Job_list[Job_num] == "Short Circuit":
Example #28
0
    def plot_heat_all(self, array_path, dep_lim = None, map_background = True):
        """
        receives the path to a serialized array object 
        optionally receives a depth limit and a map background boolean, to 
        indicate wheter we use the map as background or the coast as background
        in order to study the mainshocks plot heat map for all regions
        """
        # obtain array of shocks within the depth limit 
        all_quakes = pickle.load(open(array_path, 'rb'))
        useful_quakes = []
        for index in range(len(all_quakes)):
            current_quake = all_quakes[index]
            if dep_lim != None and current_quake.depth > dep_lim:
                continue
            useful_quakes.append(current_quake)

        # get instance of classes that we'll need methods
        draw = Draw() 
        cat = Catalog()

        # get dictionary that for every region name gives bound and zoom for all regions
        regions = {}
        regions["japan"] = [cat.get_catalog_bounds('../catalogs/new_jma.txt'), 5, 100]
        regions["kanto"] = [cat.get_kanto_bounds(), 9, 25]
        regions["kansai"] = [cat.get_kansai_bounds(), 9, 25]
        regions["tohoku"] = [cat.get_tohoku_bounds(), 9, 25]
        regions["east_japan"] = [cat.get_east_japan_bounds(), 9, 25]
        
        # index to add legibility to the code
        BOUNDS = 0
        ZOOM = 1
        BINS = 2

        # set time bound on which to plot and which years to plot 
        year_bound = [[0.0, 12*366*24.0*3600]] # this way all years are considered

        # iterate through the years 
        for time in year_bound:
            
            # iterate through the regions
            for region, info in regions.items():

                # if we are using a map as background
                if map_background: 

                    # plot image for the region
                    draw.plot_image_quakes(useful_quakes, time, info[BOUNDS], info[ZOOM])
                    call(["pdftoppm", "-rx", "300", "-ry", "300", "-png", "Rplots.pdf", region + "_back_heat"])
                    call(["mv",  region + "_back_heat-1.png", "../images/"])
                    call(["rm", "Rplots.pdf"])
                    input("Edit the image and then press Enter")

                    # plot heat map for the region in the given year
                    self.plot_heat(useful_quakes, time, info[BOUNDS], info[BINS], "../images/" + region + "_back_heat-1.png",\
                            only_main = False)
                    # save it in the correct format, and do cleaning
                    call(["mv", "temp.png", "../images/" + region + "_heat.png"])

                else:
                    # plot image for the current region 
                    draw.plot_quakes_coast(useful_quakes, time, info[BOUNDS], dep_lim = dep_lim)
                    call(["mv", "temp.png", "../images/" + region + "_back_heat_coast-1.png"])
                    input("Edit the image and then press Enter")

                    # plot heat map for the region in the given year
                    self.plot_heat(useful_quakes, time, info[BOUNDS], info[BINS], "../images/" + region + "_back_heat_coast-1.png",\
                            only_main = False)
                    # save it in the correct format, and do cleaning
                    call(["mv", "temp.png", "../images/" + region + "_heat_coast.png"])
Example #29
0
while not done:
    for event in pygame.event.get():
        keys = pygame.key.get_pressed()
        mouse = pygame.mouse.get_pressed()
        if event.type == pygame.QUIT:
            done = True

        if mouse[0]:
            if all(a == 0 for a in keys):
                pos = pygame.mouse.get_pos()
                if ([
                        pos[0] // (g_width + margin), pos[1] //
                    (g_height + margin)
                ]) == start or end:
                    continue
                coords = Draw().Wall(pos, win, "add")
                if coords not in wallList:
                    wallList.append(coords)
#			if keys[pygame.K_s] and start == 0:
#				pos = pygame.mouse.get_pos()
#				coords = Draw().Start(pos, win, "add")
#				start = coords
#			if keys[pygame.K_e] and end == 0:
#				pos = pygame.mouse.get_pos()
#				coords = Draw().End(pos, win, "add")
#				end = coords

        if mouse[2]:
            if all(a == 0 for a in keys):
                pos = pygame.mouse.get_pos()
                if ([
Example #30
0
class Reader(Dialog):

    PUNCT_MARKS = (",", ".", "-", ":", "?", "!")

    def __init__(self, cbk, book_title, book_path, last_pos):
        menu = [(u"Start", self.reader_start), (u"Pause", self.reader_pause),
                (u"Close book", self.close_reader)]

        self.book_title = book_title
        self.book_path = book_path
        self.pause = False
        self.currword_idx = last_pos
        self.wpm = 250
        self.init_delay()
        self.words = []
        self.words_num = 0
        self.parse_words()

        self.old_orientation = appuifw.app.orientation
        appuifw.app.orientation = "landscape"
        self.draw = Draw()

        Dialog.__init__(self, cbk, self.book_title, self.draw.canvas, menu,
                        self.close_reader)

        self.reader_pause()

    def init_delay(self):
        self.word_delay = 60. / self.wpm
        self.punct_delay = self.word_delay * 2

    def parse_words(self):
        """ Parse words from book into self.word """
        book_ext = self.book_path.split(".")[-1]

        if book_ext == "txt":
            self.parse_txt()
        elif book_ext == "fb2":
            self.parse_fb2()

        self.words_num = len(self.words) - 1

    def parse_txt(self):
        book_file = codecs.open(self.book_path, "r", "utf-8")

        for line in book_file:
            for w in line.split():
                self.words.append(w)

        book_file.close()

    def parse_fb2(self):
        fb2 = FB2Parser(self.book_path)
        self.words = fb2.parse_words()

    def reader_start(self):
        self.pause = False
        self.draw.canvas.bind(key_codes.EScancode5, self.reader_pause)
        # disable rewind when reading
        self.draw.canvas.bind(key_codes.EScancode6, lambda: None)
        self.draw.canvas.bind(key_codes.EScancode4, lambda: None)
        self.draw.canvas.bind(key_codes.EScancode7, lambda: None)
        self.draw.canvas.bind(key_codes.EScancode9, lambda: None)
        self.draw.canvas.bind(key_codes.EScancodeStar, lambda: None)
        self.draw.canvas.bind(key_codes.EScancodeHash, lambda: None)
        self.start_reading()

    def reader_pause(self):
        self.pause = True
        self.draw.canvas.bind(key_codes.EScancode5, self.reader_start)
        # enable rewind when pause
        self.draw.canvas.bind(key_codes.EScancode6, lambda: self.rewind(-1))
        self.draw.canvas.bind(key_codes.EScancode4, lambda: self.rewind(1))
        self.draw.canvas.bind(key_codes.EScancode7, lambda: self.rewind(10))
        self.draw.canvas.bind(key_codes.EScancode9, lambda: self.rewind(-10))
        self.draw.canvas.bind(key_codes.EScancodeStar, self.inc_wpm)
        self.draw.canvas.bind(key_codes.EKeyHash, self.dec_wpm)
        self.display_scene()

    def inc_wpm(self):
        new_wpm = self.wpm + 50
        if new_wpm <= 1000:
            self.wpm = new_wpm
            self.init_delay()
            self.display_scene()

    def dec_wpm(self):
        new_wpm = self.wpm - 50
        if new_wpm >= 50:
            self.wpm = new_wpm
            self.init_delay()
            self.display_scene()

    def rewind(self, offset):
        new_idx = self.currword_idx + offset

        if new_idx >= 0 and new_idx <= self.words_num:
            self.currword_idx = new_idx
        elif new_idx < 0:
            self.currword_idx = 0
        elif new_idx > self.words_num:
            self.currword_idx = self.words_num

        self.display_scene()

    def display_scene(self):
        word = self.words[self.currword_idx]
        best_letter = self.best_letter_pos(word)

        self.draw.clear()
        self.draw.word(word, best_letter)
        if self.pause:
            self.draw.info(self.wpm)
        self.draw.redraw()

    def best_letter_pos(self, word):
        """ Primitive algorithm for defining focus letter """
        word_len = len(word)
        best_letter = 0

        if word_len == 1:
            best_letter = 0
        elif word_len >= 2 and word_len <= 5:
            best_letter = 1
        elif word_len >= 6 and word_len <= 9:
            best_letter = 2
        elif word_len >= 10 and word_len <= 13:
            best_letter = 3
        else:
            best_letter = 4

        return best_letter

    def check_punct(self, word):
        if word[-1] in Reader.PUNCT_MARKS:
            return True
        return False

    def start_reading(self):
        offset = self.currword_idx
        last_idx = len(self.words) - 1

        for i in range(offset, last_idx):
            # when user press pause or exit from reader
            if self.pause or self.cancel:
                self.pause = False
                break

            self.currword_idx += 1
            self.display_scene()

            if self.check_punct(self.words[self.currword_idx]):
                e32.ao_sleep(self.punct_delay)
            else:
                e32.ao_sleep(self.word_delay)

        self.reader_pause()

    def close_reader(self):
        del self.words[:]
        appuifw.app.orientation = self.old_orientation
        self.cancel_app()
Example #31
0
def test_multi(model1, model2, model3, grid_size, wolf_speed, sheep_speed,
               cuda):

    games_to_test = 10

    # Set cuda
    cuda_available = cuda

    # Instantiate game
    game_state = State(grid_size, wolf_speed, sheep_speed)

    # Set initial action for all three wolves
    action1 = torch.zeros([model1.n_actions], dtype=torch.float32)
    action2 = torch.zeros([model2.n_actions], dtype=torch.float32)
    action3 = torch.zeros([model3.n_actions], dtype=torch.float32)
    action1[0] = 1
    action2[0] = 1
    action3[0] = 1

    #Get game grid and reward
    grid, reward1, reward2, reward3, finished = game_state.frame_step(
        action1, action2, action3)

    # Create drawing board and draw initial state
    window = Draw(grid_size, grid, False)
    window.update_window(grid)

    #Convert to tensor
    tensor_data = torch.Tensor(grid)

    if cuda_available:
        tensor_data = tensor_data.cuda()
    # Unsqueese to get the correct dimensons
    state = tensor_data.unsqueeze(0).unsqueeze(0)

    games = 0

    while games < games_to_test:

        # get output from the neural network
        output1 = model1(state)[0]
        output2 = model2(state)[0]
        output3 = model3(state)[0]

        # initialize actions
        action1 = torch.zeros([model1.n_actions], dtype=torch.float32)
        action2 = torch.zeros([model2.n_actions], dtype=torch.float32)
        action3 = torch.zeros([model3.n_actions], dtype=torch.float32)
        if cuda_available:  # put on GPU if CUDA is available
            action1 = action1.cuda()
            action2 = action2.cuda()
            action3 = action3.cuda()

        # Action
        action_index1 = torch.argmax(output1)
        action_index2 = torch.argmax(output2)
        action_index3 = torch.argmax(output3)
        if cuda_available:
            action_index1 = action_index1.cuda()
            action_index2 = action_index2.cuda()
            action_index3 = action_index3.cuda()

        action1[action_index1] = 1
        action2[action_index2] = 1
        action3[action_index3] = 1

        # State
        grid, reward1, reward2, reward3, finished = game_state.frame_step(
            action1, action2, action3)
        tensor_data_1 = torch.Tensor(grid)
        if cuda_available:
            tensor_data_1 = tensor_data_1.cuda()
        state_1 = tensor_data_1.unsqueeze(0).unsqueeze(0)

        #Draw new state
        window.update_window(grid)

        # set state to be state_1
        state = state_1

        if finished:
            games += 1
Example #32
0
   |           x o o o o o o o o o o o o o o | 
   - - - - - - - - - - - - - - - - - - - - -   
   """
   id= c.add(Bucket(10, 3, 'o'))
   c.render()

def parse_args(argv):

   optParser= OptionParser()

   [ optParser.add_option(opt) for opt in [
      make_option("-t", "--test", action= "store_true", dest= "test", default= False, help= "run test"),
      make_option("-i", "--input", default= stdin, help= "input file (default: stdin)")
   ]]
  
   opts, args= optParser.parse_args()
   if opts.input != stdin:
      setattr(opts, 'input', open(opts.input, 'r'))
 
   return opts

if __name__ == '__main__':

   opts= parse_args(argv)
   if opts.test:
      test()
      exit(0)

   draw= Draw(opts.input)
   draw.run()
Example #33
0
def test_single(model, grid_size, wolf_speed, sheep_speed, cuda):

    games_to_test = 10

    # Set cuda
    cuda_available = cuda

    # Instantiate game
    game_state = State(grid_size, wolf_speed, sheep_speed)

    action_wolf_1 = torch.zeros([4], dtype=torch.float32)
    action_wolf_2 = torch.zeros([4], dtype=torch.float32)
    action_wolf_3 = torch.zeros([4], dtype=torch.float32)
    # Set initial action
    action_wolf_1[0] = 1
    action_wolf_2[0] = 1
    action_wolf_3[0] = 1

    #Get game grid and reward
    grid, reward, finished = game_state.frame_step_single_reward(
        action_wolf_1, action_wolf_2, action_wolf_3)

    # Create drawing board and draw initial state
    window = Draw(grid_size, grid, False)
    window.update_window(grid)

    #Convert to tensor
    tensor_data = torch.Tensor(grid)

    if cuda_available:
        tensor_data = tensor_data.cuda()
    # Unsqueese to get the correct dimensons
    state = tensor_data.unsqueeze(0).unsqueeze(0)

    games = 0

    while games < games_to_test:

        # get output from the neural network for moving a wolf
        output = model(state)[0]

        # initialize actions
        action = torch.zeros([model.n_actions], dtype=torch.float32)
        if cuda_available:  # put on GPU if CUDA is available
            action = action.cuda()

        # Action #1
        action_index = torch.argmax(output)
        if cuda_available:
            action_index = action_index.cuda()
        action[action_index] = 1

        action_wolf_1, action_wolf_2, action_wolf_3 = get_wolf_actions(
            action_index)

        # Update state
        grid, reward, finished = game_state.frame_step_single_reward(
            action_wolf_1, action_wolf_2, action_wolf_3)
        tensor_data_1 = torch.Tensor(grid)
        if cuda_available:
            tensor_data_1 = tensor_data_1.cuda()
        state_1 = tensor_data_1.unsqueeze(0).unsqueeze(0)

        #Draw new state
        window.update_window(grid)

        # set state to be state_1
        state = state_1
        if finished:
            games += 1
Example #34
0
from draw import Draw

## Simulations to draw the convenient maps
# draw the japan map - TESTED
#draw = Draw()
#draw.draw_japan()

# draw all the maps - TESTED
#draw = Draw()
#draw.draw_all_maps()

# draw japan coast and faults, with background image
draw = Draw()
#draw.draw_japan('../catalogs/coast.txt', "coast.png")
draw.draw_japan('../catalogs/faults.txt', "faults.png")
Example #35
0
 def __init__(self):
     pygame.init()
     self.draw = Draw(pygame.display.set_mode(config.SCREEN_RESOUTION))
     pygame.display.set_caption(config.GAME_WINDOW_TITLE)