def d(self, start, end, yank=True): 'Delete text from start up through end' if yank: self.y(start, end) # yank (copy, do not remove) lines to cut buffer self.lines[start:end+1] = [] # ed range is inclusive, unlike Python self.modified = True if self.lines[1:]: # retain empty line 0 # first line after deletes, or last line in buffer self.dot = min(start,self.nlines()) # nlines() if we del end of buf else: self.dot = 0 # new_mark needed because we can't remove items from dict as we iterate new_mark = dict() #new_mark is self.mark without marks at deleted lines Buffer.cut_buffer_mark = dict() for c in self.mark: if (start <= self.mark[c] <= end): # save marks from deleted lines Buffer.cut_buffer_mark[c] = self.mark[c]-start+1 else: # adjust marks below deleted lines markc = self.mark[c] nlines = (end-start) + 1 new_mark[c] = markc - nlines if markc >= end else markc self.mark = new_mark # origin, start, end are before deletion # destination == dot after deletion, first line following deleted lines view.update(Op.delete, buffer=self, origin=start, destination=self.dot, start=start, end=end)
def select_buf(bufname): 'Make buffer with given name the current buffer' global previous, current, buf previous = current current = bufname buf = buffers[current] view.update(Op.select, buffer=buf)
def reset_node(identifier: str): """ Reset all changes applied to a node :param identifier: the identifier of the node """ model.reset_node(identifier) view.update(model)
def create_buf(bufname): 'Create buffer with given name. Replace any existing buffer with same name' global previous, current, buf buf = buffer.Buffer(bufname) buffers[bufname] = buf # replace buffers[bufname] if it already exists previous = current current = bufname view.update(Op.create, buffer=buf)
def set_change(identifier: str, change: str, value): """ Apply a user change to the model :param identifier: the identifier of the node :param change: the changed attribute :param value: the desired value """ model.change(identifier, change, value) view.update(model)
def r(self, iline, filename): 'Read file contents into buffer after iline' if os.path.isfile(filename): strings = [] # in case readlines fails with open(filename, mode='r') as fd: # fd.readlines reads file into a list of strings, one per line strings = fd.readlines() # each string in lines ends with \n self.insert(iline+1, strings) # like append, below else: view.update(Op.select, buffer=self) # new buffer for new file
def add_line(line): 'Process one line without blocking in ed input mode' global command_mode, prompt line = line.lstrip() if line == '.': command_mode = True prompt = command_prompt view.update(Op.command) else: # Recall input() returns each line with final \n stripped off, # BUT buf.a requires \n at end of each line. buf.a(buf.dot, line + '\n') # Append new line after dot, advance dot. return
def insert(self, iline, lines, origin=0, column=1): """Insert lines (list of strings) before iline, update dot to last inserted line""" self.lines[iline:iline] = lines # sic, insert lines at this position nlines = len(lines) self.dot = iline + nlines - 1 self.modified = True # usually the right thing but ed.B .E override it. # adjust line numbers for marks below the insertion point for c in self.mark: if self.mark[c] >= iline: self.mark[c] += nlines # start and end of inserted text, end == destination == dot view.update(Op.insert, buffer=self, origin=origin, destination=self.dot, start=iline, end=self.dot, column=column)
def s(self, start, end, old, new, glbl): """Substitute new for old in lines from start up to end. When glbl is True, substitute all occurrences in each line, otherwise substitute only the first occurrence in each line.""" origin = self.dot for i in range(start,end+1): # ed range is inclusive, unlike Python if old in self.lines[i]: # test to see if we should advance dot self.y(i,i) # Cut buf only holds last line where subst, like GNU ed self.lines[i] = self.lines[i].replace(old,new, -1 if glbl else 1) self.dot = i self.modified = True # Update.end and .destination are last line actually changed view.update(Op.mutate, buffer=self, origin=origin, start=start, end=self.dot, destination=self.dot)
def DD(*args): 'Delete the named buffer, even if it has unsaved changes' global previous, current, buf _, _, bufname, _ = parse.arguments(args) name = bufname if bufname else current if not name in buffers: print('? buffer name') elif name == 'main': print("? Can't delete main buffer") else: delbuf = buffers[name] del buffers[name] if name == current: # pick a new current buffer keys = list(buffers.keys()) # always nonempty due to main select_buf(keys[0]) # reassigns current previous = current view.update(Op.remove, sourcebuf=delbuf, buffer=buf) print('%s, buffer deleted' % name)
def w(*args): """ Write current buffer contents to given file name, but not if file name is already used by another buffer. If no file name given, use buffer's current file name. If file name given and no current file name, assign given. """ _, _, fname, _ = parse.arguments(args) if fname: fbufnames = bufs_for_file(fname) if fname and fbufnames and current not in fbufnames: print('? buffer %s is already editing file %s' % (fbufnames[0], fname)) return filename = current_filename(fname) if filename: # if not, current_filename printed error msg buf.w(filename) view.update(Op.status, buffer=buf) print('%s, %d lines' % (filename, buf.nlines()))
def start(): Block.initialize(MAP_WIDTH, MAP_HEIGHT) view.start(SCREEN_WIDTH, SCREEN_HEIGHT) # gen obstacles Block.generate(Obstacle, 10) odor_types = [Food, Camp(2), Camp(2), Camp(2)] Block.set_odor_types(odor_types) rgb = [(192, 192, 192), (0, 255, 0), (255, 0, 0), (255, 255, 0), (0, 0, 255)] palettes = dict(zip([Obstacle] + odor_types, rgb)) view.set_palettes(palettes) for camp in Camp.get_camps(): Block.generate(Ant, camp.ant_number, camp) timer = USEREVENT + 1 view_timer = timer + 1 pygame.time.set_timer(timer, TIMER_ELAPSE) pygame.time.set_timer(view_timer, TIMER_ELAPSE) while True: for event in pygame.event.get(): if event.type == timer: Block.generate(Food, 10 - Food.get_food_number()) Item.items_act() Block.odors_spread() elif event.type == view_timer: view.fill_black() view.render_blocks(Block.get_blocks(), BLOCK_SIZE, MAP_BLOCK_X, MAP_BLOCK_Y) view.update() elif event.type == QUIT: pygame.quit() sys.exit()
def do_command(line): 'Process one line without blocking in ed command mode or input mode' global command_mode, prompt, D_count, q_count line = line.lstrip() if line and line[0] == '#': # comment, do nothing return items = parse.command(buf, line) if items[0] == 'ERROR': return # parse.command already printed error message else: tokens = tuple([ t for t in items if t != None ]) cmd_name, args = tokens[0], tokens[1:] if cmd_name in parse.complete_cmds: globals()[cmd_name](*args) # dict from name (str) to object (fcn) elif cmd_name in parse.input_cmds: command_mode = False prompt = input_prompt # Instead of using buf.a i c fcns we handle input mode cmds inline here # We add each line to buffer when user types RET at end-of-line, # *unlike* in Python API where we pass multiple input lines at once start, end, params, _ = parse.arguments(args) # can be int or None start, end = check.mk_range(buf, start, end) # int only if not (check.iline_ok0(buf, start) if cmd_name in 'ai' else check.range_ok(buf, start, end)): print('? invalid address') command_mode = True prompt = command_prompt # assign dot to prepare for input mode, where we a(ppend) each line elif cmd_name == 'a': buf.dot = start view.update(Op.input) # depends on buf.dot so can't be moved up elif cmd_name == 'i': #and start >0: NOT! can insert in empty file buf.dot = start - 1 if start > 0 else 0 # so we can a(ppend) instead of i(nsert) view.update(Op.input) # depends on buf.dot so can't be moved up elif cmd_name == 'c': #c(hange) command deletes changed lines first buf.d(start, end) # d updates buf.dot, calls update(Op.delete). buf.dot = start - 1 # supercede dot assigned in preceding view.update(Op.input) # queues Op.input after buf.d Op.delete else: print('? command not supported in input mode: %s' % cmd_name) else: print('? command not implemented: %s' % cmd_name) # special handling for commands that must be repeated to confirm D_count = 0 if cmd_name != 'D' else D_count q_count = 0 if cmd_name != 'q' else q_count return
DEBUG = False ##se le pasa el mapa como fichero de configuracion config = engine.GameConfig(cfg_file) ##la configuracion y la cantidad de jugadores game = engine.Game(config, len(bots)) ##Bots que ejecutan la IA del jugador y se comunican actors = [botplayer.BotPlayer(game, i, cmdline, debug=DEBUG) for i, cmdline in enumerate(bots)] for actor in actors: actor.initialize() view = view.GameView(game) round = 0 while True: game.pre_round() view.update() for actor in actors: actor.turn() view.update() game.post_round() print "########### ROUND %d SCORE:" % round, for i in range(len(bots)): print "P%d: %d" % (i, game.players[i].score), print time.sleep(1) round += 1 view.update()
config = engine.GameConfig(cfg_file) game = engine.Game(config, len(bots)) actors = [ botplayer.BotPlayer(game, i, cmdline, debug=DEBUG) for i, cmdline in enumerate(bots) ] for actor in actors: actor.initialize() view = view.GameView(game) round = 0 while True: game.pre_round() view.update(args.fps) for actor in actors: try: actor.turn() except botplayer.CommError as e: if not CONTINUE_ON_ERROR: raise else: print("CommError: " + str(e)) actor.close() view.update(args.fps) game.post_round() s = "ROUND {} SCORE: \n".format(round) for i in range(len(bots)): s += "{} (Robot-{}) : {} points \n".format(game.players[i].name, i,
def l(self, iline): 'Advance dot to iline and return it (so caller can print it)' prev_dot = self.dot self.dot = iline view.update(Op.locate, buffer=self,origin=prev_dot,destination=iline) return (self.lines[iline]).rstrip() # strip trailing \n
# f=open("modo.txt","w") # f.write(str(v)) # f.close() # modo.txt variables: # rounds = numero de rondas (-1 = infinito) # pausa = 1 para pausa, 0 para no. f = open('modo.txt','r') modo= eval(f.read()) f.close() round = 0 #while True: while round < modo['rounds'] or modo['rounds'] == -1: game.pre_round() view.update() for actor in actors: actor.turn() view.update() game.post_round() print "########### ROUND %d SCORE:" % round, for i in range(len(bots)): print "P%d: %d" % (i, game.players[i].score), print round += 1 if modo['pausa'] == 1: print "Pulsa intro para continuar\n" sys.stdin.read(1) view.update()
def update(self): for view in self.views: view.update() super(Scene, self).update()