def timer(timeleft, func, params): ''' 计时函数,统计一个函数运行时间并监控其是否超时 params: timeleft - 剩余时间 func - 待执行函数 params - 函数参数 returns: (函数返回值, 执行用时) ''' # 初始化执行线程 thread = Thread(target=ReturnThread, args=(func, params)) # 运行并计时 thread.start() t1 = pf() thread.join(timeleft) t2 = pf() # 若超时则报错,否则返回消耗时间 if thread.is_alive(): raise TimeOut() # 返回函数结果或抛出异常 if isinstance(ReturnThread.result, Exception): raise ReturnThread.result return ReturnThread.result, t2 - t1
def speed_test(dl): start = pf() for i, batch in enumerate(dl): _ = batch[0] print(f'{name}: {pf() - start}') start = pf() if i == 3: break
def play(stat, storage): me = stat['now']['me'] heading = me['direction'] # 键盘控制 if human_control.control == 'key': # 时间控制 now = pf() if now - human_control.old_timer < human_control.delay: sleep(human_control.old_timer + human_control.delay - now) human_control.old_timer = pf() else: human_control.old_timer = now # 读取并清空按键缓冲 res = '' if human_control.op is not None: op = (human_control.op - heading + 4) % 4 res = ' R L'[op] human_control.op = None return res # 鼠标控制 else: x, y = me['x'], me['y'] tx, ty = human_control.pos # 等待输入 while not human_control.mouse_holding or ( x, y) == human_control.pos: sleep(0.1) if human_control.control == 'key': # 中途改用键盘控制 return human_control.play(stat, storage) # 判断方向 if heading == 0: if tx - x > abs(y - ty) or ty == y: return return 'LR'[ty > y] elif heading == 2: if x - tx > abs(y - ty) or ty == y: return return 'LR'[ty < y] elif heading == 1: if ty - y > abs(x - tx) or tx == x: return return 'LR'[tx < x] elif heading == 3: if y - ty > abs(x - tx) or tx == x: return return 'LR'[tx > x]
def play(stat, storage): # 时间控制 now = pf() if now - human_control.old_timer < human_control.delay: sleep(human_control.old_timer + human_control.delay - now) human_control.old_timer = pf() else: human_control.old_timer = now # 读取并清空按键缓冲 res = '' if human_control.op is not None: op = (human_control.op - stat['now']['me']['direction'] + 4) % 4 res = ' R L'[op] human_control.op = None return res
def load_match_result(self, res): '''加载对局记录''' self.match_result = res self.frame_seq = res['log'] self.curr_frame = 0 self.playing_status = 0 self.button1['text'] = '播放' self.old_timer = pf() self._load_screen() self._update_screen() self.button1['state'] = ACTIVE
def riron4syuume(): global Method_getZ, boundary_condition, size_of_Isingmodel, Method_getC Method_getZ = 'eachstate' boundary_condition = 'open' size_of_Isingmodel = 2 Method_getC = 'getZ' for mc in ['eachstate']: #['eachstate','eachlayer','eachspin']: for size in [2, 3, 4]: if mc == 'eachstate' and size > 5: continue for bc in ['open']: #,'periodic']: size_of_Isingmodel = size start_time = pf() plot(lambda x: get_C(x) / size**2, 1, 3, 0.1, show=0) print('method:', mc, 'bc:', bc, 'size:', size, pf() - start_time, 'sec for calculation') plt.legend([2, 3, 4], fontsize=18) # plt.savefig('./figure/CT_{}_{}_{}.eps'.format(mc,bc,size)) # plt.savefig('./figure/CT_{}_{}_{}.png'.format(mc,bc,size)) plt.show() plt.savefig('./figure/CT_eachstate_open_2to4.pdf') plt.savefig('./figure/CT_eachstate_open_2to4.eps')
def start(self): '''启动进程''' self.t_start = pf() self.timeout = self.get_timeout() self.process.start() try: now = datetime.now() self.match.status = 1 self.match.run_datetime = now self.match.timeout_datetime = now + timedelta(seconds=self.timeout) self.match.save() except: pass
def update(self): '''实时更新显示,实现逐帧播放效果''' if self.playing_status <= 0: return curr_time = pf() if curr_time - self.old_timer >= 0.1: self.old_timer = curr_time self.curr_frame += 1 self._update_screen() # 一次循环播放结束 if self.curr_frame == len(self.frame_seq) - 1: self.playing_status = -1 self.button1['text'] = '重置'
def timer(timeleft, func, params): ''' 计时函数,统计一个函数运行时间并监控其是否超时 params: timeleft - 剩余时间 func - 待执行函数 params - 函数参数 returns: (函数返回值, 执行用时) ''' # 运行并计时 t1 = pf() res = func(*params) t2 = pf() # 若超时则报错,否则返回消耗时间 if t2 - t1 >= timeleft: raise TimeOut() # 返回函数结果 return res, t2 - t1
def update(self): '''实时更新显示,实现逐帧播放效果''' if self.playing_status <= 0: return curr_time = pf() if curr_time - self.old_timer >= FRAME_STEP: self.old_timer = curr_time self.frame_index += 1 self._update_screen(self.frame_seq[self.frame_index]) self.scroll_update() # 一次循环播放结束 if self.frame_index == len(self.frame_seq) - 1: self.playing_status = 0 self.button1['text'] = '重置'
def get_courses_sch(url, form, session=None): ''' Returns a list of HTML bs4 tags containing table rows, each of which is a course offering (returned by POSTing form) Recursively follows next links ''' t1 = pf() if session is None: session = requests.Session() r = session.post(url, data=form) courses = BeautifulSoup(r.text, 'html.parser') result = courses.find('div', attrs={ 'class': 'result' }).text.strip().replace('\r', '').replace('\n', '').replace(' ', '').lower() if '0coursescorrespondtoyoursearchcriteria' in result: return [] courses_sch = [ x for x in courses.find_all('tr') if 'class' not in x.attrs or 'results-header' not in x.attrs['class'] ] if courses.find(is_next_tag) is None: return courses_sch form = get_form2() t2 = pf() sleep(max(1 - (t2 - t2), 0)) r = session.post( 'https://web30.uottawa.ca/v3/SITS/timetable/SearchResults.aspx', data=form) return courses_sch + get_courses_sch( 'https://web30.uottawa.ca/v3/SITS/timetable/SearchResults.aspx', form, session)
def unit_monitor(type, name, data, error_logger=None): ''' 比赛维护进程 每个监控进程维护一个比赛进程 监控数据库获取其维护比赛的状态,并进行中止等操作 ''' # 初始化 setup_django() from django.conf import settings from time import perf_counter as pf, sleep from match_sys import models from . import helpers from .factory import Factory # 重定向错误输出 if error_logger: import sys sys.stdout = sys.stderr = queue_io(error_logger) # 运行比赛进程 match_dir = os.path.join(settings.PAIRMATCH_DIR, name) os.makedirs(match_dir, exist_ok=1) if type == None: # 扩展区域 pass else: # 默认type=='match'一对一比赛 AI_type, params = data match_process = Factory(AI_type, name, params, error_logger) match_process.start() # 循环监测运行状态与数据库 cycle = 0 while 1: # 检查运行状况 now = pf() if not match_process.check_active(now): break # 检查数据库注册条目 cycle += 1 if cycle >= settings.MONITOR_DB_CHECK_CYCLE: cycle -= settings.MONITOR_DB_CHECK_CYCLE match_process.reload_match() if match_process.match.status == -1: # 外部中止 match_process.timeout = -1 sleep(settings.MONITOR_CYCLE) # 待机
def load_match_result(self, log, init=True): '''读取比赛记录''' self.match_result = log['result'] # 初始化场景、时间轴 if init: self._setup_grid(log['size']) self._setup_players(log['players']) self.frame_seq = log['log'] self.frame_index = 0 self.playing_status = 0 self.button1['text'] = '播放' self.old_timer = pf() # 在包含不同画面时启用播放按钮 if len(self.frame_seq) > 1: self.button1['state'] = ACTIVE else: self.button1['state'] = DISABLED # 渲染第一帧 self._update_screen(self.frame_seq[0])
def train(model, data_loader, epoch, optimizer, criterion, DEVICE): start = pf() model.train() model = model.to(DEVICE) n_correct = [] losses = [] for batch_idx, (data, target) in enumerate(data_loader): data, target = Variable(data), Variable(target) data = data.float() data = data.to(DEVICE) target = target.to(DEVICE) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() pred = output.data.max(1, keepdim=True)[1] n_correct.append(pred.eq(target.data.view_as(pred)).cpu().sum().item()) losses.append(loss.item()) latest_losses = losses[-50:] latest_correct = n_correct[-50:] running_loss = sum(latest_losses) / len(latest_losses) running_acc = sum(latest_correct) / (len(latest_correct) * data_loader.batch_size) printProgressBar( batch_idx + 1, len(data_loader), prefix=f'Epoch: {epoch+1}', suffix= f'Running Loss:{running_loss:.5f}, Running Acc:{running_acc:.5f}, Time: {pf()-start:.1f}', length=50)
def train(model, data_loader, epoch, optimizer, criterion, DEVICE): start = pf() model.train() model = model.to(DEVICE) n_correct = torch.FloatTensor([]).to(DEVICE) losses = torch.FloatTensor([]).to(DEVICE) for batch_idx, (data, target) in enumerate(data_loader): data = data.to(DEVICE) target = target.to(DEVICE) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() pred = output.data.max(1, keepdim=True)[1] corr = pred.eq(target.data.view_as(pred)).sum() n_correct = torch.cat((n_correct, corr.unsqueeze(dim=0).float())) losses = torch.cat((losses, loss.unsqueeze(dim=0).float())) latest_losses = losses[-50:] latest_correct = n_correct[-50:] running_loss = latest_losses.sum() / len(latest_losses) running_acc = latest_correct.sum() / (len(latest_correct) * data_loader.batch_size) printProgressBar( batch_idx + 1, len(data_loader), prefix=f'Epoch: {epoch+1}', suffix= f'Running Loss:{running_loss:.5f}, Running Acc:{running_acc:.5f}, Time: {pf()-start:.1f}', length=50)
import numpy as np import cv2 import matplotlib.pyplot as plt from time import perf_counter as pf # im = cv2.imread('sudokus.jpg') # plt.imshow(im) # plt.show() # exit() t = pf() # im = cv2.imread('sudokus.jpg')[350:1400, 600:1650] im = cv2.imread('sudokus.jpg')[1330:2450, 470:1635] im = cv2.resize(im, (500, 500)) imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(imgray, 155, 255, 0) contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) for c in contours: ar = cv2.contourArea(c) if ar<200000 and ar>180000: cv2.drawContours(im, [c], 0, (128, 255, 0), 1) a = np.array(c) aminx, aminy = np.argmin(a[..., 0]), np.argmin(a[..., 1]) amaxx, amaxy = np.argmax(a[..., 0]), np.argmax(a[..., 1]) cv2.circle(im, tuple(a[aminx, 0]), 5, (0,0,255), 3) cv2.circle(im, tuple(a[aminy, 0]), 5, (0,0,255), 3)
Bul = Bulbul(freq, time, 10) Spa = Sparrow(freq, time, 10) Spax = SparrowExpA(freq, time, 10) Zil = Zilpzalp(freq, time, 10) models = [Bul, Spa, Spax, Zil] test_img = torch.randn(batch_size, 1, freq, time) target = torch.Tensor(np.array([0] * batch_size)).long() DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu' print(DEVICE) test_img = test_img.to(DEVICE) target = target.to(DEVICE) criterion = nn.CrossEntropyLoss() for model in models: model = model.to(DEVICE) optimizer = optim.Adam(model.parameters(), lr=0.001) start = pf() optimizer.zero_grad() output = model(test_img) loss = criterion(output, target) loss.backward() optimizer.step() print(model.__name__, ': ', (pf() - start), ' s')
def worker(id, net, data_queue, save=False): EPS_START = 0.9 EPS_END = 0.2 EPS_DECAY = 5000 class player1: def load(self, stat, storage): storage['field_size'] = 0 if 'tensor' in storage: del storage['tensor'] def play(self, stat, storage): tensor, field_size = getFeatureMap(stat) reward = field_size - storage['field_size'] if 'tensor' in storage: data_queue.put( (storage['tensor'], storage['action'], tensor, reward)) storage['tensor'] = tensor storage['field_size'] = field_size if 'steps_done' in storage: storage['steps_done'] += 1 else: storage['steps_done'] = 1 #print(tensor.shape) sample = random.random() eps_threshold = EPS_END + (EPS_START - EPS_END) * \ math.exp(-1. * storage['steps_done'] / EPS_DECAY) #print('EPS: ', storage['steps_done'], eps_threshold) choices = ['l', 's', 'r'] if sample > eps_threshold: #print('Using Net') with torch.no_grad(): res = net(tensor).max(1)[1] ret = choices[res] else: ret = random.choice(['l', 'r', 's']) storage['action'] = ret #print(ret) return ret def summary(self, result, stat, storage): tensor, field_size = getFeatureMap(stat) eps_threshold = EPS_END + (EPS_START - EPS_END) * \ math.exp(-1. * storage['steps_done'] / EPS_DECAY) if id == 0: print('EPS: ', storage['steps_done'], eps_threshold, "Size: ", tensor[0][0].sum()) if result[0] is not None and result[1] >= 0: if result[0] == stat['log'][0]['me']['id'] - 1: reward = 0 else: reward = -0 data_queue.put( (storage['tensor'], storage['action'], None, reward)) class player2: def load(self, stat, storage): return p2.load(stat, storage) def play(self, stat, storage): return "r" return p2.play(stat, storage) gameCnt = 1 while True: t1 = pf() res = match((player1(), player2())) t2 = pf() if id == 0: print("Time: ", t2 - t1) print(gameCnt, ' Match Done') if save: save_match_log(res, 'saves/' + str(gameCnt % 100) + '.zlog') gameCnt += 1 if 'DEBUG_TRACEBACK' in dir(match): print(match.DEBUG_TRACEBACK) exit()
def update(self, frame_delta): """Create new frames. Args: frame_delta: time interval between two frames. Returns: """ # Save self.database.append([c.copy() for c in self.cells]) # New frame self.frame_count += 1 if self.frame_count == Consts["MAX_FRAME"]: # Time's up self.check_point(self.cells[0].radius <= self.cells[1].radius, self.cells[0].radius >= self.cells[1].radius, "MAX_FRAME") return # Update recorders self.update_recorders() for cell in self.cells: if not cell.dead: cell.move(frame_delta) # Detect collisions collisions = [] for i in range(len(self.cells)): if self.cells[i].dead: continue for j in range(i + 1, len(self.cells)): if not self.cells[j].dead and self.cells[i].collide( self.cells[j]): if self.cells[i].collide_group == None == self.cells[ j].collide_group: self.cells[i].collide_group = self.cells[ j].collide_group = len(collisions) collisions.append([i, j]) elif self.cells[i].collide_group != None == self.cells[ j].collide_group: collisions[self.cells[i].collide_group].append(j) self.cells[j].collide_group = self.cells[ i].collide_group elif self.cells[i].collide_group == None != self.cells[ j].collide_group: collisions[self.cells[j].collide_group].append(i) self.cells[i].collide_group = self.cells[ j].collide_group elif self.cells[i].collide_group != self.cells[ j].collide_group: tmp = self.cells[j].collide_group collisions[ self.cells[i].collide_group] += collisions[tmp] for ele in collisions[tmp]: self.cells[ele].collide_group = self.cells[ i].collide_group collisions[tmp] = [] # Run absorbs for collision in collisions: if collision != []: self.absorb(collision) # If we just killed the player, Game over if self.check_point(self.cells[0].dead, self.cells[1].dead, "PLAYER_DEAD"): return # Eject! allcells = [cell for cell in self.cells if not cell.dead] self.cells_count = len(allcells) theta = [None, None] flag = [False, False] # TODO: only one player # for i in 0, 1: try: ti = pf() # theta[i] = self.player[i].strategy([c.copy() for c in allcells]) theta[0] = self.player[0].strategy([c.copy() for c in allcells]) tf = pf() self.timer[0] -= tf - ti except Exception as e: logging.error(traceback.format_exc()) flag[0] = e if self.check_point(flag[0], flag[1], "RUNTIME_ERROR"): return if self.check_point(not isinstance(theta[0], (int, float, type(None))), not isinstance(theta[1], (int, float, type(None))), "INVALID_RETURN_VALUE"): return if self.check_point(self.timer[0] < 0, self.timer[1] < 0, "TIMEOUT"): return self.eject(self.cells[0], theta[0]) self.eject(self.cells[1], theta[1])
while run: for event in pg.event.get(): if event.type == pg.QUIT: run = False elif event.type == pg.MOUSEBUTTONDOWN: drag = True start = pg.mouse.get_pos() elif event.type == pg.MOUSEBUTTONUP: drag = False elif drag and event.type == pg.MOUSEMOTION: end = pg.mouse.get_pos() if not drag: start = end fps = pf() alpha += -radians((start[0] - end[0]) / speed) beta += radians((start[1] - end[1]) / speed) if alpha > 2*pi or alpha < -2*pi: alpha = 0 if beta > 2*pi or beta < -2*pi: beta = 0 draw(alpha, beta) fps = round(1/(pf()-fps)) avg_fps.append(fps) count += 1 print(f"FPS: {fps}")
if __name__ == "__main__": ''' 用法: python3 this.py 分组名 [晋级人数(默认8)] ''' # 导入必要库 from multiprocessing import Process, Queue, cpu_count from sqlite3 import connect from time import perf_counter as pf from random import shuffle, randrange from platform import system # 初始化环境 if 'init': t_start = pf() # 常量参数 MATCH_PARAMS = (51, 101, 2000, 30) # k, h, turn, time ROUNDS = 10 # 比赛局数(单向) MAX_TASKS = cpu_count() - 2 # 最大子进程数 TIMEOUT = (MATCH_PARAMS[3] * 2 + 5) * ROUNDS * 2 # 超时限制 try: MAX_PROMOTION = int(sys.argv[2]) # 晋级人数 except: MAX_PROMOTION = 8 # 组别 TEAM = sys.argv[1] # TEAM = 'AI' LOG_FORMAT = TEAM + "/log/%s-%s(%d).zlog" AI_PATH = os.path.abspath(TEAM)
WIDTH = k * 2 HEIGHT = h init_field(k, h) # 随机色块 for x in range(WIDTH): for y in range(HEIGHT): if randrange(2) == 1: FIELDS[x][y] = 1 print('generate done') print(count_score()) for y in range(20): res = '' for x in range(150): res += '+' if FIELDS[x][y] == 1 else ' ' print(res) PLAYERS[0].field_border = [0, WIDTH - 1, 0, HEIGHT - 1] t1 = pf() PLAYERS[0].check_field_fill() t2 = pf() print(t2 - t1) print(count_score()) for y in range(20): res = '' for x in range(150): res += '+' if FIELDS[x][y] == 1 else ' ' print(res)
file.write("\n".join([f"v {p[0]} {p[1]} {p[2]}" for p in points.values()]) + "\n" + "\n".join(faces.values()) + "\n") with open("test.obj", "w+") as f: seed = 1281134870109837483 randomness = Random(seed) noise = OpenSimplex(seed=seed) chunks = {} radius = 1 if len(sys.argv) < 2 else int(sys.argv[1]) print(f"Generating {(radius*2)**2} chunks...") start = pf() for x in range(-radius, radius): for z in range(-radius, radius): chunks[x, z] = noisy_chunk(noise, randomness, x, z) print( f"Done generating chunks. ({(pf() - start):02.02f} seconds for {len(chunks)} chunks)" ) print("Adding ore pockets...") start = pf() chunks = make_ore_pockets(chunks, randomness, noise) print(f"Ore pockets made! ({(pf()-start):02.02f} seconds)") print("Generating + carving perlin worms...")
# "0 8 0 9 6 0 0 1 0", # "4 0 0 0 0 0 0 5 7", # "0 0 8 0 0 0 4 7 1", # "0 0 0 6 0 3 0 0 0", # "2 5 9 0 0 0 8 0 0", # "7 4 0 0 0 0 0 0 5", # "0 2 0 0 1 8 0 6 0", # "0 0 5 4 7 0 3 2 9" ] # hardest sudoku = [ "3 0 0 0 0 0 0 0 0", "0 0 5 0 0 9 0 0 0", "2 0 0 5 0 4 0 0 0", "0 2 0 0 0 0 7 0 0", "1 6 0 0 0 0 0 5 8", "7 0 4 3 1 0 6 0 0", "0 0 0 8 9 0 1 0 0", "0 0 0 0 6 7 0 8 0", "0 0 0 0 0 5 4 3 7" ] grid = " ".join(sudoku) print(grid) n = 1 t = pf() for _ in range(n): output = subprocess.run([r'.\sudoku_solver'], input=grid, stdout=subprocess.PIPE, universal_newlines=True).stdout[1:90] t = pf() - t print(f"\nTime taken for {n} solve(s): {t} seconds.") print(output)
def load(*args): human_control.old_timer = pf()
def update(self, frame_delta): """Create new frames. Args: frame_delta: Time interval between two frames. Returns: """ # Save self.database.append([c.copy() for c in self.cells]) # New frame self.frame_count += 1 if self.frame_count == Consts["MAX_FRAME"]: # Time's up self.check_point(self.cells[0].radius <= self.cells[1].radius, self.cells[0].radius >= self.cells[1].radius, "MAX_FRAME") return # Update recorders self.update_recorders() for cell in self.cells: if not cell.dead: cell.move(frame_delta) # Detect collisions collisions = [] for i in range(len(self.cells)): if self.cells[i].dead: continue for j in range(i + 1, len(self.cells)): if not self.cells[j].dead and self.cells[i].collide( self.cells[j]): if self.cells[i].collide_group == None == self.cells[ j].collide_group: self.cells[i].collide_group = self.cells[ j].collide_group = len(collisions) collisions.append([i, j]) elif self.cells[i].collide_group != None == self.cells[ j].collide_group: collisions[self.cells[i].collide_group].append(j) self.cells[j].collide_group = self.cells[ i].collide_group elif self.cells[i].collide_group == None != self.cells[ j].collide_group: collisions[self.cells[j].collide_group].append(i) self.cells[i].collide_group = self.cells[ j].collide_group elif self.cells[i].collide_group != self.cells[ j].collide_group: collisions[self.cells[i].collide_group] += collisions[ self.cells[j].collide_group] for ele in collisions[self.cells[j].collide_group]: self.cells[ele].collide_group = self.cells[ i].collide_group collisions[self.cells[j].collide_group] = [] # Run absorbs for collision in collisions: if collision != []: self.absorb(collision) # If we just killed the player, Game over if self.check_point(self.cells[0].dead, self.cells[1].dead, "PLAYER_DEAD"): return # Eject! allcells = [cell for cell in self.cells if not cell.dead] self.cells_count = len(allcells) theta0 = theta1 = None flag0 = flag1 = False if self.timer[0] > 0: try: ti = pf() theta0 = self.player0.strategy([c.copy() for c in allcells]) tf = pf() self.timer[0] -= tf - ti except Exception as e: logging.error(traceback.format_exc()) flag0 = e if self.timer[1] > 0: try: ti = pf() theta1 = self.player1.strategy([c.copy() for c in allcells]) tf = pf() self.timer[1] -= tf - ti except Exception as e: logging.error(traceback.format_exc()) flag1 = e if isinstance(theta0, (int, float, type(None))): if self.timer[0] >= 0: self.eject(self.cells[0], theta0) else: flag0 = True if isinstance(theta1, (int, float, type(None))): if self.timer[1] >= 0: self.eject(self.cells[1], theta1) else: flag1 = True self.check_point(flag0, flag1, "RUNTIME_ERROR")
def solve_cube(colors): t = pf() s = color_to_str(colors) sol = kc.solve(s) return sol, pf() - t
#%% Loop BLERs = np.full(num_runs, -1, dtype=float) BERs = np.full(num_runs, -1, dtype=float) # Socket connection sock = SocketConnection() tt.tester_default_setup(sock) tt.tester_set_capturetime(10e-6 + num_runs * (expected_duration), sock) # Seed the RNG np.random.seed(SEED) #%% Generate some waves st = pf() data = np.random.binomial(1, 0.5, (num_runs, wirt.DATA_SIZE)).astype(np.uint8) IQ_data_full = np.empty((num_runs, encoder.num_samples_per_package), np.complex) for i in range(num_runs): encoded = encoder.encode(data[i]) IQ_data_full[i] = encoded print("Generation/modulation took {:.2f} ms".format(1000 * (pf() - st))) #%% Transmit to tester st = pf() # Convert to waveform
def null_timer(timeleft, func, params): t1 = pf() res = func(*params) t2 = pf() return res, t2 - t1
def parse_match(funcs): ''' 读入双方AI函数,执行一次比赛 params: funcs - 函数列表 returns: 胜利玩家id, 终局原因编号 [, 额外描述] 终局原因 : 0 - 撞墙 1 - 纸带碰撞 2 - 侧碰 3 - 正碰,结算得分 4 - 领地内互相碰撞 -1 - AI函数报错 -2 - 超时 -3 - 回合数耗尽,结算得分 ''' t1, t2, action = 0, 0, None # 在字典提前初始化计时变量、存放操作结果变量,去除新建变量耗时因素 # 建立双方存储空间 storages = [{'size': (WIDTH, HEIGHT), 'log': []} for i in range(2)] # 执行游戏逻辑 for i in range(MAX_TURNS): for plr_index in (0, 1): # 获取当前玩家、AI、游戏信息、存储空间 plr = PLAYERS[plr_index] func = funcs[plr_index] params = get_params(plr_index) storage = storages[plr_index] # 执行AI返回操作符号 try: t1 = pf() action = func(params, storage) t2 = pf() except Exception as e: # AI函数报错 return (1 - plr_index, -1, e) TURNS[plr_index] -= 1 # 判断是否超时 TIMES[plr_index] -= (t2 - t1) if TIMES[plr_index] < 0: return (1 - plr_index, -2) # 根据操作符转向 if isinstance(action, str) and len(action) > 0: op = action[0].upper() if op == 'L': plr.turn_left() elif op == 'R': plr.turn_right() # 前进并更新结果,若终局则返回结果 res = plr.forward() if res: return res # 记录log storages[plr_index]['log'].append(get_params(plr_index)) storages[1 - plr_index]['log'].append(get_params(1 - plr_index)) LOG_PUBLIC.append(get_params()) # 回合数耗尽 return (None, -3)