def gameloop(): theta1 = 0 theta2 = 0 frame = 0 inord = 0 headingin = 0 WIDTH = 4 CHANNELS = 1 RATE = 22050 save_screen = make_video(main_surface) wf = wave.open('long.wav', 'rb') song = wave.open('10simm.wav', 'rb') p = pyaudio.PyAudio() main_surface.fill((0, 0, 0)) def callback(in_data, frame_count, time_info, status): #Uncomment to output frames #next(save_screen) data = wf.readframes(frame_count) data2 = song.readframes(frame_count) decoded = np.fromstring(data, dtype=np.int32) decoded2 = np.fromstring(data2, dtype=np.int32) if np.fabs(decoded[0]) > 0: if np.fabs(decoded[1]) > 0: for i, l in zip(decoded, decoded2): theta1 = (2 * np.pi * (i / 2147483647)) theta2 = np.cos(2 * np.pi * (np.exp( (l / 50) / 2147483647))) + np.sin(-2 * np.pi * (np.exp( (l / 50) / 2147483647))) draw_tree(inord, 2, theta1, theta2, surface_size * 0.3 * (i / 2147483647), (500, 500), (i / 2147483647) * np.pi * (np.exp( (l / 50) / 2147483647))) return (data, pyaudio.paContinue) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=96000, output=True, stream_callback=callback) stream.start_stream() while True: pygame.display.flip() ev = pygame.event.poll() if ev.type == pygame.QUIT: break #Output current screen elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_s: next(save_screen)
def run(self, video=False, filename=""): ''' Forward method for Environments. Actually runs the scenarios you view on (or off) screen. video::bool -- whether you want to record the simulation filename::str -- the name of the video file ''' # Agent velocities a_vel, p_vel, f_vel = self.vel # Agent action generators (yield actions of agents) a_generator = self.agent.act(a_vel, self.clock, self.screen, self.space, self.options, self.view, self.std_dev) p_generator = self.patient.act(p_vel, self.clock, self.screen, self.space, self.options, self.view, self.std_dev) f_generator = self.fireball.act(f_vel, self.clock, self.screen, self.space, self.options, self.view, self.std_dev) # Running flag running = True # Video creation save_screen = make_video(self.screen) # Main loop. Run simulation until collision between Green Agent # and Fireball while running and not handlers.PF_COLLISION: try: # Generate the next tick in the simulation for each object next(a_generator) next(p_generator) next(f_generator) # Render space on screen (if requested) if self.view: self.screen.fill((255, 255, 255)) self.space.debug_draw(self.options) pygame.display.flip() self.clock.tick(50) self.space.step(1 / 50.0) # Update the values for the Blender JSON file self.update_blender_values() # Increment the simulation tick self.tick += 1 if video: next(save_screen) except Exception as e: running = False if self.view: pygame.quit() pygame.display.quit() # Record whether Green Agent and Fireball collision occurred self.patient_fireball_collision = 1 if handlers.PF_COLLISION else 0 # Reset collision handler handlers.PF_COLLISION = [] handlers.AP_COLLISION = [] handlers.AF_COLLISION = [] if video: vid_from_img(filename)
def gameloop(): theta1 = 0 theta2 = 0 frame = 0 inord = 0 headingin = 0 WIDTH = 4 CHANNELS = 1 RATE = 22050 save_screen = make_video(main_surface) wf = wave.open('432loud.wav', 'rb') p = pyaudio.PyAudio() def callback(in_data, frame_count, time_info, status): pygame.display.flip() #my_clock.tick(20) #next(save_screen) data = wf.readframes(frame_count) decoded = numpy.fromstring(data, dtype=numpy.int32) yf = scipy.fftpack.fft(decoded) decoded_oh = decoded[::2] yf_oh = yf[::2] main_surface.fill((0, 0, 0)) if numpy.fabs(decoded[0]) > 0: if numpy.fabs(decoded[1]) > 0: for i, j in zip(decoded_oh, yf_oh): theta1 = numpy.cos((numpy.exp( ((i) / 2147483647) * 1))) * 1j theta2 = numpy.cos((numpy.exp( ((i) / 2147483647) * 1))) * 1j draw_tree(inord, 6, theta1, theta2, surface_size * 5, (800, 450), (j / 2147483647) * numpy.pi) return (data, pyaudio.paContinue) print(wf.getsampwidth()) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True, stream_callback=callback) stream.start_stream() while True: ev = pygame.event.poll() if ev.type == pygame.QUIT: break
def gameloop(): theta1 = 0 theta2 = 0 frame = 0 inord = 0 headingin = 0 WIDTH = 4 CHANNELS = 1 RATE = 22050 save_screen = make_video(main_surface) wf = wave.open('noise.wav', 'rb') p = pyaudio.PyAudio() main_surface.fill((0, 0, 0)) def callback(in_data, frame_count, time_info, status): pygame.display.flip() #my_clock.tick(60) #next(save_screen) data = wf.readframes(frame_count) decoded = numpy.fromstring(data, dtype=numpy.int32) #yf = scipy.fftpack.fft(decoded) #print(yf) #here = numpy.fft( #theta1 = 5+(math.log10((1/math.fabs(0.00001+decoded[0])))*1j) #theta2 = 5+(math.log10((1/math.fabs(0.00001+decoded[1])))*1j) #theta1 = (math.exp(math.sin(decoded[0])))*1j #theta2 = (math.exp(math.sin(decoded[1])))*1j decoded_oh = decoded[::] #yf_oh = yf[::] #theta1 = decoded[0] #theta2 = decoded[1] #print(decoded[0]) if math.fabs(decoded[0]) > 0: if math.fabs(decoded[1]) > 0: #print(decoded[0]) for i in (decoded_oh): #theta1 = math.cos((math.exp(((i)/32767)*1)))*1j #theta2 = math.cos((math.exp(((i)/32767)*1)))*1j #theta1 = math.cos((pygame.mouse.get_pos()[1]/225)*math.pi*(i/2147483647))*1j #theta2 = math.sin((pygame.mouse.get_pos()[1]/225)*math.pi*(i/2147483647))*1 theta1 = math.cos( 2 * math.pi * (i / 2147483647)) * (1 * (pygame.mouse.get_pos()[0] / 450)) theta2 = math.sin(2 * math.pi * (i / 2147483647)) * 1 #theta1 = ((math.exp(((i)/6000)*1 )))*1j #theta2 = ((math.exp(((i)/6000)*1)))*1j #theta1 = math.cos((math.exp((math.fabs(i)/6000)*1 )))*1j #theta2 = math.cos((math.exp((math.fabs(i)/6000)*1)))*1j draw_tree(inord, 3, theta1, theta2, surface_size * 0.2, (450, 450), (math.pi * (i / 2147483647))) #draw_tree2(inord,8, theta1, theta2, surface_size*0.2, (450,450), (math.pi*(i/2147483647))) #draw_tree3(inord,8, theta1, theta2, surface_size*0.2, (450,450), (math.pi*(i/2147483647))) #draw_tree4(inord,8, theta1, theta2, surface_size*0.2, (450,450), (math.pi*(i/2147483647))) #draw_tree2(inord,8, theta1, theta2, surface_size*0.2, (450,450), (pygame.mouse.get_pos()[0]/225)*math.pi*(i/2147483647)) #draw_tree3(inord,8, theta1, theta2, surface_size*0.2, (450,450), (pygame.mouse.get_pos()[0]/225)*math.pi*(i/2147483647)) #draw_tree4(inord,8, theta1, theta2, surface_size*0.2, (450,450), (pygame.mouse.get_pos()[0]/225)*math.pi*(i/2147483647)) #pygame.display.flip() #draw_tree(inord, 8, theta1, theta2, surface_size*0.8, (400,400), math.pi) #pass #print(decoded) return (data, pyaudio.paContinue) print(wf.getsampwidth()) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True, stream_callback=callback) stream.start_stream() while True: # Handle evente from keyboard, mouse, etc. ev = pygame.event.poll() if ev.type == pygame.QUIT: break
class searchviz: pygame.init() clock = pygame.time.Clock() block_size = 50 w = block_size * 10 h = block_size * 10 gameDisplay = pygame.display.set_mode((w, h)) save_screen = make_video(gameDisplay) def __init__(self, title): pygame.display.set_caption(title) self.unvisited = (255, 255, 255) self.black = (0, 0, 0) self.visited = (5, 43, 104) self.alive = (255, 255, 0) self.current = (30, 196, 15) self.dead = (2, 49, 56) self.textcol = (2, 49, 56) self.done = False self.start_x = 0 self.start_y = 0 self.x = self.start_x self.y = self.start_y self.visited = [] self.dead = [] def update(self): pygame.display.update() next(self.save_screen) next(self.save_screen) next(self.save_screen) def color(self, row=0, col=0, clr=(30, 196, 15)): start_x = row * self.block_size start_y = col * self.block_size self.gameDisplay.fill( clr, (start_x, start_y, self.block_size, self.block_size)) def up(self): self.x = self.x if (self.y == 0): self.y = self.y else: self.y = self.y - 1 def down(self): self.x = self.x if (self.y == 9): self.y = self.y else: self.y = self.y + 1 def left(self): self.y = self.y if (self.x == 0): self.x = self.x else: self.x = self.x - 1 def right(self): self.y = self.y if (self.x == 9): self.x = self.x else: self.x = self.x + 1 def draw_grids(self): for y in range(0, self.h, self.block_size): for x in range(self.w): self.gameDisplay.fill( self.textcol, (x, y, 1, 1)) ## Horizontal lines for grids for x in range(0, self.w, self.block_size): for y in range(0, self.h): self.gameDisplay.fill( self.textcol, (x, y, 1, 1)) ## vertical lines for grids def color_visited(self): for i in range(len(self.visited)): self.color(self.visited[i][0], self.visited[i][1], (175, 222, 243)) def color_dead(self): for i in range(len(self.dead)): self.color(self.dead[i][0], self.dead[i][1], (170, 170, 170)) def capture_keyboard(self): ###### capturing keystrokes for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: self.done = True if (event.type == pygame.QUIT): self.done = True def paint_background(self, w=1028, h=600): self.gameDisplay.fill(self.unvisited, (0, 0, w, h)) def set_fps(self, rate=30): self.clock.tick(30) def step(self): self.set_fps(30) self.capture_keyboard() self.paint_background(self.w, self.h) self.color_visited() self.color_dead() self.color(self.x, self.y, clr=self.current) self.draw_grids() self.update() if (self.done == True): pygame.quit() return self.done
def run(self, seed=None, robust=True, video=False, iteration=-1): ppu = 32 T = 150 # Max simulation time # Initiate video generator if (video): if (robust): save_screen = make_video(self.screen, iteration, "robust") else: save_screen = make_video(self.screen, iteration, "primal") # Random Initialization Seed if (seed is not None): np.random.seed(seed) # Initialize settings eps = 0.001 p_threshold = 1 - 0.95 dist_threshold = 1.0 coll_threshold = 4.9 success = False collision_flag = False min_dist = np.inf # Initialize agents N_a = np.random.randint(3, 10) agents = [0] * N_a agents_ctrl = [0] * N_a # Set start point for i in range(N_a): start_collision = True while (start_collision): start_collision = False x1, y1 = 60 * np.random.rand(), 60 * np.random.rand() for j in range(i): dist = np.sqrt((x1 - agents[j].position[0])**2 + (y1 - agents[j].position[1])**2) if (dist < 8.0): start_collision = True break agents[i] = Car(x1, y1) agents[0].max_acceleration = 8.0 # Set goal point for i in range(N_a): start_collision = True while (start_collision): start_collision = False x1, y1 = 60 * np.random.rand(), 60 * np.random.rand() for j in range(i): dist = np.sqrt((x1 - agents[j].goal[0])**2 + (y1 - agents[j].goal[1])**2) if (dist < 8.0): start_collision = True break agents[i].goal = np.array([x1, y1]) # Initialize GP all_gp = [] state = np.zeros((N_a, 4)) next_state = np.zeros((N_a, 4)) x_state = np.zeros((N_a, 4)) d_state = np.zeros((N_a, 4)) all_gp.append( GP(None, None, omega=np.eye(4), l=60.0, sigma=8.5, noise=0.01, horizon=15)) # Robot GP all_gp[0].load_parameters('hyperparameters_robot.pkl') for i in range(1, N_a): all_gp.append( GP(None, None, omega=np.eye(4), l=60.0, sigma=8.5, noise=0.01, horizon=15)) # Human GP all_gp[i].load_parameters('hyperparameters_human.pkl') G_all = np.zeros((N_a - 1, 8 * 2, 8)) g_all = np.zeros((N_a - 1, 8 * 2)) m_all = np.zeros((N_a, 4)) z_all = np.zeros((N_a, 2)) G_base = np.array([[1, 0, 0, 0], [-1, 0, 0, 0], [0, 1, 0, 0], [0, -1, 0, 0], [0, 0, 1, 0], [0, 0, -1, 0], [0, 0, 0, 1], [0, 0, 0, -1]]) g_base = np.array([eps, eps, eps, eps, eps, eps, eps, eps]) # Set barrier for each agent horizon_set = [0, 0, 0, 0, 7, 8] for i in range(1, N_a): agents[i].Ds = horizon_set[np.random.randint(len(horizon_set))] for i in range(T): # Get nominal trajectory for our robot u, x_path, x0 = get_trajectory(agents[0], N=10) state[0, :] = x0 # Simulate trajectory for other agents for j in range(1, N_a): # Obtain (CBF) controller for other agent (if applicable) u2, x2_path, x2_0 = get_trajectory(agents[j]) if (agents[j].Ds > 0): u2 = filter_output_primal(j, agents, x2_path) agents_ctrl[j] = u2 # Get agent's states (for inference) state[j, :] = x2_0 - x0 if (np.linalg.norm(x2_0[0:2] - x0[0:2]) < min_dist): min_dist = np.linalg.norm(x2_0[0:2] - x0[0:2]) if (robust): # Infer uncertainty polytope for robot and other agents if (all_gp[0].N_data > 0): start_time = time.time() m_d, cov_d = all_gp[0].predict(state[0, :]) G_r, g_r = all_gp[0].extract_box( cov_d, p_threshold=p_threshold) # G: 8x4, g: 8x1 m_all[0, :] = m_d z_all[0, 0], z_all[0, 1] = all_gp[0].extract_norms( cov_d, p_threshold=p_threshold) for j in range(1, N_a): if (all_gp[j].N_data > 0): m_d, cov_d = all_gp[j].predict(state[j, :]) G_h, g_h = all_gp[j].extract_box( cov_d, p_threshold=p_threshold) m_all[j, :] = m_d z_all[j, 0], z_all[j, 1] = all_gp[j].extract_norms( cov_d, p_threshold=p_threshold) G_all[j - 1, 0:8, 0:4] = G_r g_all[j - 1, 0:8] = g_r if (np.linalg.norm(next_state[j, 2:4]) < eps): G_all[j - 1, 8:16, 4:8] = G_base g_all[j - 1, 8:16] = g_base else: G_all[j - 1, 8:16, 4:8] = G_h g_all[j - 1, 8:16] = g_h # Obtain safe control given uncertainty polytopes if (all_gp[0].N_data > 0): start_time = time.time() u = filter_output(0, agents, x_path, G_all=G_all, g_all=g_all, m=m_all, z=z_all) else: u = filter_output(0, agents, x_path) else: u = filter_output_primal(0, agents, x_path) agents_ctrl[0] = u # Add noise to agents' actions and collect data noise_a = 0.001 for j in range(N_a): if (j == 0): x0 = np.array([ agents[j].position[0], agents[j].position[1], agents[j].velocity[0], agents[j].velocity[1] ]) else: xj = np.array([ agents[j].position[0], agents[j].position[1], agents[j].velocity[0], agents[j].velocity[1] ]) agents[j].update(agents_ctrl[j] + noise_a * (np.random.rand(2) - 0.5)) next_state[j, :] = np.array([ agents[j].position[0], agents[j].position[1], agents[j].velocity[0], agents[j].velocity[1] ]) if (j == 0): p, v = agents[j].f_err(x0, agents_ctrl[j]) x_state[j, :] = x0 d_state[j, :] = next_state[j, :] - np.concatenate((p, v)) else: p, v = agents[j].fh_err(xj) x_state[j, :] = xj - x0 d_state[j, :] = next_state[j, :] - np.concatenate((p, v)) # Update GPs if (robust): start_time = time.time() all_gp[0].add_data(x_state[0, :], d_state[0, :]) all_gp[0].get_obs_covariance() for j in range(1, N_a): all_gp[j].add_data(x_state[j, :], d_state[j, :]) all_gp[j].get_obs_covariance() # Draw screen self.screen.fill((220, 220, 220)) # Draw other agents for j in range(1, N_a): pygame.draw.circle(self.screen, [200, 0, 0], (agents[j].position * ppu).astype(int), 80) # Draw our goal agent1_goal = pygame.image.load('star.png') rect = agent1_goal.get_rect() self.screen.blit( agent1_goal, agents[0].goal * ppu - (rect.width / 2, rect.height / 2)) # Draw our agent pygame.draw.circle(self.screen, [0, 0, 200], (agents[0].position * ppu).astype(int), 80) if (kDraw): pygame.display.flip() if (kVideo): next(save_screen) # Check if there is collision, or if goal is reached for j in range(1, N_a): if (np.linalg.norm(agents[0].position - agents[j].position) < coll_threshold): success = False collision_flag = True if (np.linalg.norm(agents[0].position - agents[0].goal) < dist_threshold and collision_flag): success = False break elif (np.linalg.norm(agents[0].position - agents[0].goal) < dist_threshold and not collision_flag): success = True break else: pass self.clock.tick(self.ticks) time.sleep(0.1) return data, data_u, success, collision_flag, i, min_dist
def gameloop(): theta1 = 0 theta2 = 0 frame = 0 inord = 0 headingin = 0 WIDTH = 4 CHANNELS = 1 RATE = 22050 save_screen = make_video(main_surface) wf = wave.open('sawramp1.wav', 'rb') timer = wave.open('holdramp1.wav', 'rb') #song = wave.open('fish.wav', 'rb') song2 = wave.open('fish.wav', 'rb') p = pyaudio.PyAudio() main_surface.fill((0, 0, 0)) def callback(in_data, frame_count, time_info, status): pygame.display.flip() #my_clock.tick(24) next(save_screen) data = wf.readframes(frame_count) data2 = timer.readframes(frame_count) #data3 = song.readframes(frame_count) data4 = song2.readframes(frame_count) decoded = numpy.fromstring(data, dtype=numpy.int32) decoded2 = numpy.fromstring(data2, dtype=numpy.int32) #decoded3 = numpy.fromstring(data3, dtype=numpy.int32) decoded4 = numpy.fromstring(data4, dtype=numpy.int32) #yf = scipy.fftpack.fft(decoded) #print(yf) #here = numpy.fft( #theta1 = 5+(math.log10((1/math.fabs(0.00001+decoded[0])))*1j) #theta2 = 5+(math.log10((1/math.fabs(0.00001+decoded[1])))*1j) #theta1 = (math.exp(math.sin(decoded[0])))*1j #theta2 = (math.exp(math.sin(decoded[1])))*1j decoded_oh = decoded[::] #yf_oh = yf[::] #decoded_ohh = yf_oh*decoded_oh #theta1 = decoded[0] #theta2 = decoded[1] #print(decoded[0]) if math.fabs(decoded[0]) > 0: if math.fabs(decoded[1]) > 0: #print(decoded[0]) for i,x,l in zip(decoded_oh,decoded2,decoded4): #theta1 = math.cos((math.exp(((i)/32767)*1)))*1j #theta2 = math.cos((math.exp(((i)/32767)*1)))*1j #theta1 = math.cos((pygame.mouse.get_pos()[1]/225)*math.pi*(i/2147483647))*1j #theta2 = math.sin((pygame.mouse.get_pos()[1]/225)*math.pi*(i/2147483647))*1 theta1 = ((2*math.pi*(4*(i/2147483647)))*(x/2147483647)*1600/225)#**math.cos(math.pi*((i/2147483647)))#*((x/2147483647))#*(1*(pygame.mouse.get_pos()[0]/450)) theta2 = math.cos(2*math.pi*(math.exp((l/50)/2147483647)))+math.sin(-2*math.pi*(((l/50)/2147483647)))#**math.cos(2*math.pi*((j/2147483647)))#*(1*(pygame.mouse.get_pos()[1]/450)) #theta1 = ((math.exp(((i)/6000)*1 )))*1j #theta2 = ((math.exp(((i)/6000)*1)))*1j #theta1 = math.cos((math.exp((math.fabs(i)/6000)*1 )))*1j #theta2 = math.cos((math.exp((math.fabs(i)/6000)*1)))*1j draw_tree(inord,4, theta1, theta2, surface_size*0.3*(i/2147483647)*-1600/1125, (800*1600/1800,450), (i/2147483647)*math.pi*(((l/50)/2147483647))) #draw_tree2(inord,8, theta1, theta2, surface_size*0.2, (450,450), (math.pi*(i/2147483647))) #draw_tree3(inord,8, theta1, theta2, surface_size*0.2, (450,450), (math.pi*(i/2147483647))) #draw_tree4(inord,8, theta1, theta2, surface_size*0.2, (450,450), (math.pi*(i/2147483647))) #draw_tree2(inord,8, theta1, theta2, surface_size*0.2, (450,450), (pygame.mouse.get_pos()[0]/225)*math.pi*(i/2147483647)) #draw_tree3(inord,8, theta1, theta2, surface_size*0.2, (450,450), (pygame.mouse.get_pos()[0]/225)*math.pi*(i/2147483647)) #draw_tree4(inord,8, theta1, theta2, surface_size*0.2, (450,450), (pygame.mouse.get_pos()[0]/225)*math.pi*(i/2147483647)) #pygame.display.flip() #draw_tree(inord, 8, theta1, theta2, surface_size*0.8, (400,400), math.pi) #pass #print(decoded) return (data, pyaudio.paContinue) #print(wf.getsampwidth()) stream = p.open(format=p.get_format_from_width(song2.getsampwidth()), channels=song2.getnchannels(), rate= song2.getframerate(), output=True, stream_callback=callback) stream.start_stream() while True: # Handle evente from keyboard, mouse, etc. ev = pygame.event.poll() if ev.type == pygame.QUIT: break; elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_s: next(save_screen)
import matplotlib.pyplot as plt import pygame import numpy as np import random from video import make_video pygame.init() width = 1000 height = 1000 no = 100 resolution = int(width/no) #box = main_surface = pygame.display.set_mode((width,height)) save_screen = make_video(main_surface, "anti") arr = np.zeros((no,no), dtype="uint8") nex = np.zeros((no,no), dtype="uint8") lifedeath = np.zeros((no,no), dtype="uint8") single = np.zeros((no,no), dtype="uint8") for x in range(no): for y in range(no): arr[x][y] = random.randint(0,1) print(arr) def countNeighbours(ar, x, y): summ = 0 for i in range(3): for j in range(3): q = (x-1+i+no) % no #print(x) w = (y-1+j+no) % no
def run_rotate(): ''' Runs the simulations and saves the JSON files with an arbitrary rotation about the center of the screen. ''' def rotate(obj,theta=-20,origin=(500,300)): ''' Rotates objects about a center ''' # Translate w/r to visual origin (500,300) obj.body.position -= Vec2d(origin) # Radians to degrees theta = radians(theta) x, y = obj.body.position x_ = x*cos(theta) - y*sin(theta) y_ = y*cos(theta) + x*sin(theta) obj.body.position = [x_,y_] # Translate w/r to actual origin (0,0) obj.body.position += Vec2d(origin) video = False thetas = list(range(-19,-9))+list(range(10,19)) for scene in scenarios.__experiment3__: theta = choice(thetas) sim = getattr(scenarios, scene) env = sim(True) env.run() # Gather position data pos = env.position_dict agent_positions = env.position_dict['agent'] patient_positions = env.position_dict['patient'] fireball_positions = env.position_dict['fireball'] # Setup pygame and pymunk space = pymunk.Space() space.damping = 0.05 screen = pygame.display.set_mode((1000,600)) options = pymunk.pygame_util.DrawOptions(screen) clock = pygame.time.Clock() if video: save_screen = make_video(screen) # Setup empty agents agent = Agent(0,0,'blue',0,[]) patient = Agent(0,0,'green',0,[]) fireball = Agent(0,0,'red',0,[]) # Add agent to space space.add(agent.body, agent.shape, patient.body, patient.shape, fireball.body, fireball.shape) pygame.init() running = True while running: # print(agent_positions[0]) try: # Extract position data a_pos = agent_positions.pop(0) p_pos = patient_positions.pop(0) f_pos = fireball_positions.pop(0) # Set positions of objects agent.body.position = Vec2d(a_pos['x'],a_pos['y']) patient.body.position = Vec2d(p_pos['x'],p_pos['y']) fireball.body.position = Vec2d(f_pos['x'],f_pos['y']) # Rotate objects about the center rotate(agent,theta) rotate(patient,theta) rotate(fireball,theta) # Render space on screen (if requested) screen.fill((255,255,255)) space.debug_draw(options) pygame.display.flip() clock.tick(60) space.step(1/60.0) if video: next(save_screen) except Exception as e: running = False pygame.quit() pygame.display.quit() if video: vid_from_img("final_"+scene)
def gameloop(): theta1 = 0 theta2 = 0 frame = 0 inord = 0 headingin = 0 WIDTH = 4 CHANNELS = 1 RATE = 22050 save_screen = make_video(main_surface) wf = wave.open('sim.wav', 'rb') p = pyaudio.PyAudio() def callback(in_data, frame_count, time_info, status): pygame.display.flip() my_clock.tick(20) next(save_screen) data = wf.readframes(frame_count) decoded = numpy.fromstring(data, dtype=numpy.int16) yf = scipy.fftpack.fft(decoded) #print(yf) #here = numpy.fft( #theta1 = 5+(math.log10((1/math.fabs(0.00001+decoded[0])))*1j) #theta2 = 5+(math.log10((1/math.fabs(0.00001+decoded[1])))*1j) #theta1 = (math.exp(math.sin(decoded[0])))*1j #theta2 = (math.exp(math.sin(decoded[1])))*1j decoded_oh = decoded[::2] yf_oh = yf[::2] #theta1 = decoded[0] #theta2 = decoded[1] #print(decoded[0]) main_surface.fill((0, 0, 0)) if math.fabs(decoded[0]) > 0: if math.fabs(decoded[1]) > 0: #print(decoded[0]) for i, j in zip( decoded_oh, yf_oh ): # Change to every other value for left/right side [0] = left [1] = right theta1 = math.cos((math.exp(((i) / 6000) * 1))) * 1j theta2 = math.cos((math.exp(((i) / 6000) * 1))) * 1j #theta1 = ((math.exp(((i)/6000)*1 )))*1j #theta2 = ((math.exp(((i)/6000)*1)))*1j #theta1 = math.cos((math.exp((math.fabs(i)/6000)*1 )))*1j #theta2 = math.cos((math.exp((math.fabs(i)/6000)*1)))*1j draw_tree(inord, 6, theta1, theta2, surface_size * 3, (300, 300), math.pi * j) #pygame.display.flip() #draw_tree(inord, 8, theta1, theta2, surface_size*0.8, (400,400), math.pi) #pass #print(decoded) return (data, pyaudio.paContinue) print(wf.getsampwidth()) stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True, stream_callback=callback) stream.start_stream() while True: # Handle evente from keyboard, mouse, etc. ev = pygame.event.poll() if ev.type == pygame.QUIT: break
def counterfactual_run(self, std_dev, video=False, filename=''): ''' Forward method for Environments. Actually runs the scenarios you view on (or off) screen. std_dev::float -- noise parameter for simulation video::bool -- whether you want to record the simulation filename::str -- file name for video ''' # We remove the agent from the environment self.space.remove(self.space.shapes[0]) self.space.remove(self.space.bodies[0]) # Reinitialize pygame pygame.init() # If viewing, draw simulaiton to screen if self.view: pygame.init() self.screen = pygame.display.set_mode((1000, 600)) self.options = pymunk.pygame_util.DrawOptions(self.screen) self.clock = pygame.time.Clock() # Set noise parameter self.std_dev = std_dev save_screen = make_video(self.screen) # Agent velocities _, p_vel, f_vel = self.vel # Counterfactual ticks for agents self.patient.counterfactual_tick = self.agent_patient_collision self.fireball.counterfactual_tick = self.agent_fireball_collision # Agent action generators (yield actions of agents) p_generator = self.patient.act(p_vel, self.clock, self.screen, self.space, self.options, self.view, self.std_dev) f_generator = self.fireball.act(f_vel, self.clock, self.screen, self.space, self.options, self.view, self.std_dev) # Running flag running = True # Main loop. Run simulation until collision between Green Agent # and Fireball while running and not handlers.PF_COLLISION: try: # Generate the next tick in the simulation for each object next(p_generator) next(f_generator) # Render space on screen (if requested) if self.view: self.screen.fill((255, 255, 255)) self.space.debug_draw(self.options) pygame.display.flip() self.clock.tick(50) self.space.step(1 / 50.0) # Update the values for the Blender JSON file self.update_blender_values() # Increment the simulation tick self.tick += 1 # Increment ticks in agents self.patient.tick = self.tick self.fireball.tick = self.tick if video: next(save_screen) except: running = False if self.view: pygame.quit() pygame.display.quit() # Record whether Green Agent and Fireball collision occurred self.patient_fireball_collision = 1 if handlers.PF_COLLISION else 0 # Reset collision handler handlers.PF_COLLISION = [] handlers.AP_COLLISION = [] handlers.AF_COLLISION = [] if video: vid_from_img(filename)
#xn+1 - rxn(1-xn) import matplotlib.pyplot as plt import pygame import numpy from video import make_video pygame.init() width = int(500 * (16 / 9)) height = 500 main_surface = pygame.display.set_mode((width, height)) save_screen = make_video(main_surface, "hehe") arr = [] equ = [] rate = [] rae = 0 def solver(r, x, n, m): if n > 0: arr.append((r * x * (1 - x))) n -= 1 solver(r, (r * x * (1 - x)), n, m) else: #print(arr) for s in range(100): equ.append(r + 1) equ.append(arr[len(arr) - (s + 1)]) #print(equ)
def main(screenSize): ###globals for access global pointsLeftPlayer global pointsRightPlayer global time_elapsed #time since last frame global reward_p1 global reward_p2 global state_p1 global state_p2 training_modus = False ###initialize all the things pygame.init() screen = pygame.display.set_mode(screenSize) clock = pygame.time.Clock() ball = go.Ball(np.array([180, 152]), ballRadius) # paddle = go.Paddle(np.array([screenSize[0]-100, 152]),paddle_size) robot = go.RobotArm(np.array([-70, screenSize[1] / 2])) robot_r = go.RobotArm(np.array([screenSize[0] + 70, screenSize[1] / 2]), mirrored=True) video = False #record video of screen. Toggle ingame via "v" save_screen = make_video(screen) #initialize recording running = True ###game loop while running: time_elapsed = clock.tick(tickTime) #get time since last tick for event in pygame.event.get(): #get Event-Input if event.type == QUIT: #alt+F4 = Quit, closing window works as well running = False if event.type == KEYDOWN: if event.key == pygame.K_v: #toggle recording of video with "v" video = not video if event.key == pygame.K_r: # r: reset ball ball = reset_complete() ###keyboard input keys = pygame.key.get_pressed( ) #checking pressed keys, returns TRUE if pressed #if time_elapsed % 30 == 0: # ball = reset_p1() #Paddle # if keys[pygame.K_UP]: # paddle.accelerate(np.array([0, -1*paddle_speed])) # if keys[pygame.K_DOWN]: # paddle.accelerate(np.array([0,paddle_speed])) # if keys[pygame.K_LEFT]: # paddle.accelerate(np.array([-1*paddle_speed, 0])) # if keys[pygame.K_RIGHT]: # paddle.accelerate(np.array([paddle_speed,0])) if (training_modus == False): #robot arm left side: WASD if keys[pygame.K_d]: if robot.paddle_p[1] < screenSize[1] - 30: robot.U_a -= voltage_step if robot.U_a < 0: robot.U_a = 0 if keys[pygame.K_a]: if robot.paddle_p[1] > 30: robot.U_a += voltage_step if robot.U_a > 5: robot.U_a = 5 if keys[pygame.K_w]: if robot.paddle_p[1] > 30: robot.U_b += voltage_step if robot.U_b > 5: robot.U_b = 5 if keys[pygame.K_s]: if robot.paddle_p[1] < screenSize[1] - 30: robot.U_b -= voltage_step if robot.U_b < 0: robot.U_b = 0 #robot arm right side: Arrow Keys if keys[pygame.K_RIGHT]: robot_r.U_a -= voltage_step if robot_r.U_a < 0: robot_r.U_a = 0 if keys[pygame.K_LEFT]: robot_r.U_a += voltage_step if robot_r.U_a > 5: robot_r.U_a = 5 if keys[pygame.K_UP]: robot_r.U_b += voltage_step if robot_r.U_b > 5: robot_r.U_b = 5 if keys[pygame.K_DOWN]: robot_r.U_b -= voltage_step if robot_r.U_b < 0: robot_r.U_b = 0 else: next_action_p1 = np.argmax(agent1.get_next_action(state_p1)) next_action_p2 = np.argmax(agent2.get_next_action(state_p2)) enumToAction(robot, next_action_p1) enumToAction(robot_r, next_action_p2) if keys[pygame.K_q]: agent1.save_q_table('q_table_player1') agent2.save_q_table('q_table_player2') #start training if keys[pygame.K_t]: agent1 = rlAgent.Agent() agent2 = rlAgent.Agent() training_modus = True next_action_p1 = np.argmax(agent1.get_next_action(state_p1)) next_action_p2 = np.argmax(agent2.get_next_action(state_p2)) enumToAction(robot, next_action_p1) enumToAction(robot_r, next_action_p2) ###updates # paddle.update(screenSize, ball) ball.update(screenSize) robot.update(time_elapsed, ball) robot_r.update(time_elapsed, ball) reward_p1 = (calculate_distance_to_gate_p1(ball) * 0.001) - ( calculate_distance_player_to_ball(robot, ball) * 0.002) reward_p2 = (calculate_distance_to_gate_p2(ball) * 0.001) - ( calculate_distance_player_to_ball(robot_r, ball) * 0.002) ##check for goals if ball.hitRight: #Statt Abfrage ein pygame event erstellen, das auslöst bei Treffer pointsLeftPlayer += 1 ball = reset_p2() reward_p1 = 5 reward_p2 = -5 if ball.hitLeft: pointsRightPlayer += 1 ball = reset_p1() reward_p2 = 5 reward_p1 = -5 old_state_p1 = state_p1 old_state_p2 = state_p2 state_p1 = int( round(ball.position[0], 0) + round(ball.position[1], 0)) + int( round(calculate_distance_player_to_ball(robot, ball), 0)) state_p2 = int( round(ball.position[0], 0) + round(ball.position[1], 0)) + int( round(calculate_distance_player_to_ball(robot_r, ball), 0)) if (training_modus == True): agent1.update(old_state_p1, state_p1, next_action_p1, reward_p1) agent2.update(old_state_p2, state_p2, next_action_p2, reward_p2) ###render if render == True: screen.fill((0, 0, 0)) ball.render(screen) # paddle.render(screen) robot.render(screen) showText(screen, robot, ball) draw_goals(screen, screenSize) robot_r.render(screen) pygame.display.flip() if video == True: next(save_screen) pygame.quit()