import time from graphics import Graphics from state import State from search import bfs, dfs M = 3 N = 3 G = Graphics(M, N) G.shuffle() value = G.value() state = State(M, N, value) goal_state = State(M, N) s = input('search[dfs, bfs]: ') if s == 'dfs': search = dfs d = .0005 elif s == 'bfs': search = bfs d = .05 else: raise ValueError("Search method '{}' not exist".format(s)) end = search(state, goal_state) actions = end.path() print('#move: ', len(actions)) input("show me the answer?") for (i, v) in enumerate(actions): if i % 2000 == 0: print(i)
def __init__(self): self.running = True self.screen = None pygame.init() self.world = World() self.graphics = Graphics(self.world)
os.remove("save.xml") quit() def new_block(): global next_block game.set_block(next_block) next_block = Block(4, 0, None, None) pygame.mixer.pre_init(22050, -16, 2, 128) pygame.init() os.environ["SDL_VIDEO_CENTERED"] = "1" game = Game(10, 20) graphics = Graphics(10, 20) mixer = pygame.mixer mixer.music.load("audio\\theme-song.mp3") drop_sound = mixer.Sound("audio\\sfx_sounds_impact1.wav") score_sound = mixer.Sound("audio\\sfx_sounds_powerup5.wav") pause_sound = mixer.Sound("audio\\sfx_sounds_pause2_out.wav") unpause_sound = mixer.Sound("audio\\sfx_sounds_pause2_in.wav") end_sound = mixer.Sound("audio\\minecraft-damage.wav") if os.path.exists("save.xml"): chosen = 1 graphics.menu(chosen) choice = 0 while choice == 0: for event in pygame.event.get():
def __init__(self): self.game = None self.gui = Graphics()
def __init__(self): self.game = Game(BOARD_SIZE, START_TILES) self.gui = Graphics(self.game.get_board(), self.play) self.gui.mainloop()
params.show_faces = kwargs.get(Args.SHOW_FACES) params.use_feature_angle = kwargs.get(Args.USE_FEATURE_ANGLE) return params if __name__ == '__main__': init_logging() args, print_help = parse_args() params = set_parameters(**vars(args)) if not params: logger.error("Error in parameters.") sys.exit(1) ## Create graphics interface. graphics = Graphics() ## Read in the model. mesh = Mesh(params) mesh.graphics = graphics mesh.read_mesh() graphics.mesh = mesh if params.check_area: mesh.check_area(params.area_tolerance) ''' mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(mesh.surface) mapper.SetScalarVisibility(True) mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarRange(mesh.scalar_range)
#0: (LeastSquare(1, 2, 1, 0, 1, 3, 1, 0.5, 'x**2', '-x', '(6 - (3*(x**3))) / (x**4)'), lambda x: x**(-2)), 1: (LeastSquare(0.5, 1, 0, 1, 1.5, 1, 1, 4, '2', '-4/x', '1'), lambda x: x**2 + 0.5 * x), #2: (LeastSquare(0, 1, 1, 0, 1, 1, 2, 0, '-1', '-2', '-3*2.7182**(-x)'), lambda x: (x+1)*2.7181**(-x)), #3: (LeastSquare(0, 0.5, 0, 1, 0, 1, 0, 0.5 * sin(0.5), '2*x', '-1', '2 * cos(x) * (x**2 + 1)'), lambda x: x*sin(x)), #4: (LeastSquare(0, 1, 1, 1, 1, 0, 1, 4, '2', '-3', '-6*x**2+8*x+1'), lambda x: 2*x**2 + 1), #5: (LeastSquare(0, 1, 1, 0, -0.25, 1, -3, 0, '2 / (x-4)', '(x-4)', '1'), lambda x: 1 / (x-4)), #6: (LeastSquare(1, 2, 1, 0, 0, 0, 1, log(2) + 1, 'x', '-4', 'x + 1/x - 3*x*log(x)'), lambda x: x * log(x)), #7: (LeastSquare(0, 1, 1, 1, 1, 1, 0, cos(1), 'x', '-1', '-(x**2) * sin(x) - x*cos(x) - 2*sin(x)'), lambda x: x * cos(x)), #8: (LeastSquare(0, 1, 1, 0, 0, 0, 1, 2*e, 'x', '-1', '(x*(x+1) + 2)*(e**x)'), lambda x: x * e**x), #9: (LeastSquare(0, 1, 1, 0, -1/3, 1, 4, 15, 'x+3', '-2/((x+3)**2)', '-6*x/((x+3)**2) + 3*(x+3) + 1/(x+3)'), lambda x: 3*x - 1/(x+3)), #10: (LeastSquare(0, 1, 0, 1, 3, 2, -1, e, '-1', '-2', '-2*e**(x)'), lambda x: e**x + e**(2*x)), #11: (LeastSquare(-1, 0, 1, 1, 1, 1, 0, 0, '1/x', '-1/x**2', '8*x+3'), lambda x: x**2 + x**3), #12: (LeastSquare(1, 2, 0, 1, 1, 1, 0, 2*log(2), 'x', '-x**2', '1/x + x*log(x) + x - (x**3) * log(x)'), lambda x: x * log(x)), #13: (LeastSquare(1, 2, 1, 0, 1, 0, 1, 1.5, '1/x', '-4', '-4*x + 1/x - 4 * log(x)'), lambda x: x + log(x)), } destiny = 1 # Change this to switch equations step = 0.1 # Change this to change step xs, ys, rys = list(), list(), list() grph = Graphics() x = "hello there" for x, y in conditions[destiny][0].get_values(step): xs.append(x) ys.append(y) rys.append(conditions[destiny][1](x)) grph.draw([xs, xs], [ys, rys], 'Title') print('Finish!')
def __init__(self): self.graphics = Graphics() self.board = Board() self.selected_piece = None
# -*- coding: utf8 -*- """ Graphics (3D) """ import numbers from mathics.core.expression import Expression, NumberError, from_python from mathics.builtin.base import BoxConstructError, Builtin, InstancableBuiltin from graphics import (Graphics, GraphicsBox, PolygonBox, create_pens, _Color, LineBox, PointBox, Style, RGBColor, get_class, asy_number, CoordinatesError, _GraphicsElements) import json from django.utils.html import escape as escape_html def coords3D(value): if value.has_form('List', 3): return (value.leaves[0].to_number(), value.leaves[1].to_number(), value.leaves[2].to_number()) raise CoordinatesError class Coords3D(object): def __init__(self, graphics, expr=None, pos=None, d=None): self.graphics = graphics self.p = pos self.d = d if expr is not None: if expr.has_form('Offset', 1, 2):
def main(): data = GetData('poloniex', newdata=True) tickers = [ 'LTC/USDT' ] #,'BTC/USDT'] #tickers = data.tickers() ## tickers = ['OMG/BTC']#,'ETH/BTC','XMR/BTC','ZEC/BTC','BTC/USDT'] periods = ['5m', '15m', '30m', '1h'] #periods = ['5m','15m','30m','1h'] maximum_parameters = [] proportion_test = 0.1 graph_results = True data.fetch('BTC/USDT') # use if list length error'ETH/USDT','XRP/USDT', type_coin = 'USDT' for tick in tickers: if tick[-len(type_coin):] == type_coin: data.fetch(tick) temp_results = [] for numsimul in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: for period in periods: '''formats the bitcoin and current coin data to the right period''' tick_data = data.periodFormatter(tick, period) startDate = tick_data.index[0] btc_data = data.periodFormatter('BTC/USDT', period, startDate) '''formats the raw data to the proportion of data chosen''' startDate = tick_data.index[int( (1 - proportion_test) * len(tick_data))] endDate = tick_data.index[-1] btc_prices = btc_data.loc[startDate:endDate]['Close'] tick_prices = tick_data.loc[startDate:endDate]['Close'] if len(tick_prices) != len(btc_prices): tick_prices.drop(tick_prices.index[0], inplace=True) if len(tick_prices) == len( btc_prices) or tick[-len(type_coin):] == type_coin: strategy = Strategy(len(tick_prices), numsimul) for count, price in enumerate(tick_prices.values): if type_coin == 'BTC': strategy.tick(price, btc_prices.values[count]) elif type_coin == 'USDT': strategy.tick(price) strategy.macd(26, 12, 9, count, len(tick_prices)) temp_results.append([ tick, period, strategy.profit, strategy.balance, tick_prices, strategy.numtrades, min(strategy.balanceList), strategy ]) else: print('length error') break optimumParam = None for result in temp_results: if optimumParam == None: optimumParam = result optimum = result elif result[3] > optimumParam[3]: optimumParam = result else: pass print(optimumParam[0], optimumParam[1], '\nProfit on one coin per trade:', optimumParam[2], '\nBalance on', optimumParam[-1].USDpertrade, 'USD per trade:', optimumParam[3], '\nNumber of simeltaneuos trades:', optimumParam[-1].numSimul, '\nNumber of trades:', optimumParam[-1].numtrades) maximum_parameters.append(optimumParam) for param in maximum_parameters: plot = Graphics(param[4], bal=param[-1].balanceList, buylist=param[-1].buylist, selllist=param[-1].selllist, MACD=param[-1].MACD, signal=param[-1].signal, EMAfast=param[-1].EMAfast, EMAslow=param[-1].EMAslow) plot.MACD_plot(26)
from board import Board import pygame from graphics import Graphics board = Board() graphics = Graphics(board) is_running = True while is_running: # Board Logic board.update() # Update Graphics is_running = graphics.update(board) pygame.quit()
#!/usr/bin/python3 try: from tkinter import * except ImportError: from Tkinter import * from graphics import Graphics from game import Game root = Tk() graphics = Graphics(root) game = Game(graphics, root) root.mainloop()
#================================================================================================= pygame.init() #pygame.display.set_mode((800,600), pygame.OPENGL|pygame.DOUBLEBUF) #pygame.display.set_mode(SCREEN_SIZE,HWSURFACE|OPENGL|DOUBLEBUF) size = list((800, 600)) speed = [2, 2] black = 0, 0, 0 #screen = pygame.Surface( size )#pygame.display.set_mode(size) # clock = pygame.time.Clock() # gfx = Graphics() dg = DungeonGenerator(10, 64) dungeon = dg.generate() # decorator = DungeonDecorator() pc = decorator.decorate(dungeon) selection = pc.controller.selection dungeonmaster = DungeonMaster(dungeon) print "character list len %(num)i" % {'num': len(dungeon.characters)} # update_list = list( ) #every frame, items in this list are updated and blitted to screen
if __name__ == '__main__': init_logging() args, print_help = parse_args() params = set_parameters(**vars(args)) if params == None: sys.exit() ## Create graphics interface. # # Creating a Graphics() object fails is vtk # is not installed. try: graphics = Graphics(params) except: graphics = None pass ## Read in the solver file. solver = Solver(params) solver.graphics = graphics solver.read_solver_file() if graphics: graphics.solver = solver ## Read segment data. solver.read_segment_data() ## Write segment data if segments are not going
def main(thresh1, kernel): print(kernel) HEIGHT = 3 # distance of kernel from x-y plane img = cv2.imread('./Dilation/assets/dilation7x7sample2.jpg', 0) ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) n1, n2 = thresh1.shape n1 += 2 # horizontal number of pixels plus 2 for padding n2 += 2 # vertical number of pixels plus 2 for padding threshNew = [['' for j in range(n1)] for i in range(n2)] resultMatrix = [['' for j in range(n1)] for i in range(n2)] dilationSquareMatrixFront = [[[(2 + n1, -n2 - 2, 0), (2 + n1, 0.5 - n2 - 2, 1), (n1 - 2, 0.5 - n2 - 2, 1), (n1 - 2, -n2 - 2, 0)]]] dilationSquareMatrixBack = [[[(2 + n1, -n2 - 2 + 1, 0), (2 + n1, 0.5 - n2 - 2, 1), (n1 - 2, 0.5 - n2 - 2, 1), (n1 - 2, -n2 - 2 + 1, 0)]]] for y in range(n2): for x in range(n1): if (y == 0 or x == 0 or y == n2 - 1 or x == n1 - 1): threshNew[y][x] = 0 else: threshNew[y][x] = thresh1[y - 1][x - 1] resultMatrix[y][x] = '' thresh1 = np.array(threshNew, np.uint8) kernel = np.array([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0]], np.uint8) kn1, kn2 = kernel.shape squareMatrix = makeSquareMatrix(n1, n2) squareResultMatrix = makeSquareResultMatrix(n1, n2) kernelSquareMatrix = makeKernelMatrix(0, 0, HEIGHT, kn1, kn2) pygame.init() display = (1000, 563) img = pygame.display.set_mode(display, DOUBLEBUF | OPENGL) gluPerspective(45, (display[0] / display[1]), 0.1, 50.0) glTranslatef(-n1, n1 / 3, -(n1 + n2)) glEnable(GL_LINE_SMOOTH) glEnable(GL_POLYGON_SMOOTH) glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) glEnable(GL_MULTISAMPLE) glRotatef(20, 0, 0, 1) glRotatef(-50, 1, 0, 0) glRotatef(20, 0, 1, 0) xindex = 0 yindex = 0 texture = textures.Texture(True, n1, n2) texture.loadTexture(0) tmp_texture = textures.Texture(True, n1, n2) tmp_texture.loadTexture(1) tmp_texture.set_vertices(1) tmp_texture2 = textures.Texture(True, n1, n2) tmp_texture2.loadTexture(2) tmp_texture2.set_vertices(2) rate = 0 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 4: glTranslatef(0, -1, 0) elif event.button == 5: glTranslatef(0, 1, 0) keys = pygame.key.get_pressed() if keys[K_LEFT]: glTranslatef(1, 0, 0) if keys[K_RIGHT]: glTranslatef(-1, 0, 0) if keys[K_UP]: glTranslatef(0, 0, -1) if keys[K_DOWN]: glTranslatef(0, 0, 1) # glClearColor(0.88, 0.3, 0.53, 1) glClearColor(0.29, 0.32, 0.6, 1) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) if (xindex == 0 and yindex == 0): for y in range(n2): for x in range(n1): resultMatrix[y][x] = '' texture.draw() tmp_texture2.draw() Graphics(xindex, yindex, HEIGHT, kn1, kn2, n1, n2, squareMatrix, kernel, thresh1, squareResultMatrix, resultMatrix, dilationSquareMatrixBack, dilationSquareMatrixFront) tmp_texture.draw() if (rate == 0): xindex = (xindex + 1) % (n1 - kn1 + 1) if (xindex == 0): yindex = (yindex + 1) % (n2 - kn2 + 1) rate = (rate + 1) % 10 pygame.display.flip() pygame.time.wait(50)
# main.py # Description: project constants. # --------------------------------------------------------------------------------------------------------------------- # Imports import sys from graphics import Graphics from simulation import Simulation # Run simulation. if __name__ == '__main__': print("Starting simulation.") simulation = Simulation() graphics = Graphics(simulation) graphics.run() sys.exit(1)
pygame.display.set_caption('Pygame Platformer') WINDOW_SIZE = (1200, 800) screen = pygame.display.set_mode(WINDOW_SIZE, 0, 32) # initiate the window display = pygame.Surface((600, 400)) # used as the surface for rendering, which is scaled game_folder = os.path.dirname(__file__) img_folder = os.path.join(game_folder, 'images') graphics_folder = os.path.join(game_folder, 'Graphics') music_folder = os.path.join(game_folder, 'music') # Gets the basic game music going (Commented Cause Im listening to music. Uncomment if forgotten) # pygame.mixer.init() # pygame.mixer.music.load(os.path.join(music_folder, 'GameMusic_1.mp3')) # pygame.mixer.music.play(-1, 0.0) graphics = Graphics(graphics_folder, display, FPS) dirt_img = pygame.image.load(os.path.join(img_folder, 'dirt.png')) castle_img = pygame.image.load(os.path.join(img_folder, 'castleCenter.png')) item_img = pygame.image.load(os.path.join(img_folder, 'Chest.png')).convert_alpha() player_img = graphics.Player.get_model() spear_character_img = pygame.image.load(os.path.join(img_folder, 'MainCharacterSpear.png')).convert_alpha() enemy1_img = graphics.Enemy1.get_model() enemy2_img = graphics.Enemy2.get_model() items = [] item1 = Item("SPEAR", 6, True, item_img, spear_character_img, [10, 6]) item2 = Item("SPEAR2", 6, False, item_img, spear_character_img, [0, 0]) print(item2.is_on_ground) items.append(item1)
def __init__(self): # init graphic library self.graphics = Graphics()
def __init__(self, handle): activity.Activity.__init__(self, handle) # we do not have collaboration features # make the share option insensitive self.max_participants = 1 # toolbar with the new toolbar redesign toolbar_box = ToolbarBox() activity_button = ActivityButton(self) toolbar_box.toolbar.insert(activity_button, 0) activity_button.show() title_entry = TitleEntry(self) toolbar_box.toolbar.insert(title_entry, -1) title_entry.show() description_item = DescriptionItem(self) toolbar_box.toolbar.insert(description_item, -1) description_item.show() share_button = ShareButton(self) toolbar_box.toolbar.insert(share_button, -1) share_button.show() separator = Gtk.SeparatorToolItem() separator.props.draw = False separator.set_expand(True) toolbar_box.toolbar.insert(separator, -1) separator.show() stop_button = StopButton(self) toolbar_box.toolbar.insert(stop_button, -1) stop_button.show() # FONT DEFINITIONS FONT_FACE = 'Monospace' input_font = Pango.FontDescription('%s %d' % (FONT_FACE, int(FONT_SIZE * 1.2))) entry_font = Pango.FontDescription('%s %d' % (FONT_FACE, int(FONT_SIZE * 10.0 ))) self.set_toolbar_box(toolbar_box) toolbar_box.show() # label with the text, make the string translatable center_in_panel = Gtk.Alignment.new(0.5, 0, 0, 0) graphics = Graphics() first = 'methane' self._first_entry = graphics.add_entry(first) self._first_entry.override_font(input_font) self._spac1 = graphics.add_text(' ') print("LOG: #56, ", self._first_entry, self._first_entry ) button = graphics.add_button(_("COMPUTE"), self.something ) self._spac2 = graphics.add_text(' ') button.show() self.hold_hi3 = graphics.add_text( _(" "), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold_hi3.override_font(input_font) self.hold_hi2 = graphics.add_text( _(" "), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold_hi2.override_font(input_font) self.hold_hi1 = graphics.add_text( _(" "), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold_hi1.override_font(input_font) self.hold0 = graphics.add_text( _("CH4"), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold0.override_font(input_font) self.hold_lo1 = graphics.add_text( _(" "), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold_lo1.override_font(input_font) self.hold_lo2 = graphics.add_text( _(" "), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold_lo2.override_font(input_font) self.hold_lo3 = graphics.add_text( _(" "), size="xx-large", bold=True, justify=Gtk.Justification.CENTER) self.hold_lo3.override_font(input_font) center_in_panel.add(graphics) graphics.show() self.set_canvas(center_in_panel) center_in_panel.show()
def angular_distance(end, start): return float(end) - float(start) def get_min_travel(end, start): # true is forwards # false is backwards d = angular_distance(end, start) test = min(d, (2 * math.pi) - d) if d == test: return (test, True) else: return (test, False) if __name__ == "__main__": starting_angles = START end_angles = GOAL robot_test = Robot(starting_angles) environment_test = Environment(robot_test, 5) print(environment_test.check_motion(starting_angles, end_angles, 100)) graphics = Graphics(environment_test) graphics.render()
q_table[state, action] = new_value if reward == -10: penalties += 1 state = next_state epochs += 1 if i % 100 == 0: print(f"Episode: {i}") print("Training finished.\n") """Evaluate agent's performance after Q-learning""" if ENABLE_GRAPHICS: gra = Graphics(env) t = Thread(target=gra.start) t.start() sleep(0.5) total_epochs, total_penalties = 0, 0 episodes = 100 for _ in range(episodes): state = env.reset() decoded = env.decode(state) print("----- STATE -----") print(*env.decode(state)) print("-----------------")
def __init__(self): self.graphics = Graphics() self.character = Character(Point(400, 300)) self.graphics.register(self.character) self.event = Event() self.event.register(self.character.handler)
def main(): data = GetData('poloniex', newdata=False) tickers = ['OMG/BTC'] #tickers = data.tickers() periods = ['30m'] #periods = ['5m','15m','30m','1h'] maximum_parameters = [] proportion_test = 0.1 graph_results = True #data.fetch('BTC/USDT') # use if list length error for tick in tickers: if tick[-3:] == 'BTC': data.fetch(tick) temp_results = [] for period in periods: '''formats the bitcoin and current coin data to the right period''' tick_data = data.periodFormatter(tick, period) startDate = tick_data.index[0] btc_data = data.periodFormatter('BTC/USDT', period, startDate) prices = [close for close in tick_data['Close']] '''formats the raw data to the proportion of data chosen''' startDate = tick_data.index[int( (1 - proportion_test) * len(prices))] endDate = tick_data.index[-1] btc_prices = btc_data.loc[startDate:endDate]['Close'] tick_prices = tick_data.loc[startDate:endDate]['Close'] for MAlong in [10, 15, 30]: for x in [2, 3, 4]: MAshort = int(MAlong / x) if len(tick_prices) == len(btc_prices): strategy = Strategy(len(tick_prices)) for count, price in enumerate(tick_prices.values): strategy.tick(price, btc_prices.values[count]) strategy.movingaverage(MAlong, MAshort, count) profit, balance = strategy.returnParam() temp_results.append([ tick, period, tick_prices, strategy, profit, balance, MAlong, MAshort ]) else: print('length error') break optimumParam = None for result in temp_results: if optimumParam == None: optimumParam = result optimum = result elif result[5] > optimumParam[5]: optimumParam = result else: pass print(optimumParam[0], optimumParam[1], optimumParam[4], optimumParam[5], optimumParam[6], optimumParam[7]) maximum_parameters.append(optimumParam) for param in maximum_parameters: plot = Graphics(param[2], param[3].MAlong, param[3].MAshort, param[3].buylist, param[3].selllist, param[3].balanceList) plot.MA_plot()