def setupPluginsSettings(self): """ Config of every enabled plugin """ config = self.config choices = [] choices.append(_("Exit")) plugins = config.options("plugins") plugins.sort() for plugin in list(plugins): self.loadPlugin(plugin) if hasattr(self.plugins[plugin], "setup"): choices.append("{0:25s} {1}".format(plugin, self.plugins[plugin].about)) else: plugins.remove(plugin) while True: print() console.writeln(" " + _("Plugins settings menu"), console.color("RB", False, "")) choice = console.menu(_("Plugins:"), choices, padding=1) if choice == choices[0]: break plugin = plugins[choices.index(choice) - 1] console.write(" " + _("Configuration of") + " ", console.color("GB", False, "")) console.writeln(plugin, console.color("GB", True, "")) self.plugins[plugin].setup() config.save()
def spawn_shell(command): """ Run a SHELL subprocess. """ cmd = shell_command if command: cmd += ' -c "' + command + '"' p = pexpect.spawn(str(cmd)) while True: try: c = state.console_state.keyb.get_char() except error.Break: # ignore ctrl+break in SHELL pass if c == '\b': # BACKSPACE p.send('\x7f') elif c != '': p.send(c) while True: try: c = p.read_nonblocking(1, timeout=0) except: c = '' if c == '' or c == '\n': break elif c == '\r': console.write_line() elif c == '\b': if state.console_state.col != 1: console.set_pos(state.console_state.row, state.console_state.col - 1) else: console.write(c) if c == '' and not p.isalive(): return
def edit(from_line, bytepos=None): """ Output program line to console and position cursor. """ if state.basic_state.protected: console.write(str(from_line)+'\r') raise error.RunError(error.IFC) # list line state.basic_state.bytecode.seek(state.basic_state.line_numbers[from_line]+1) _, output, textpos = tokenise.detokenise_line(state.basic_state.bytecode, bytepos) # no newline to avoid scrolling on line 24 console.list_line(str(output), newline=False) # find row, column position for textpos newlines, c = 0, 0 pos_row, pos_col = 0, 0 if not output: return for i, byte in enumerate(output): c += 1 if chr(byte) == '\n' or c > state.console_state.screen.mode.width: newlines += 1 c = 0 if i == textpos: pos_row, pos_col = newlines, c if textpos > i: pos_row, pos_col = newlines, c + 1 if bytepos: console.set_pos(state.console_state.row-newlines+pos_row, pos_col) else: console.set_pos(state.console_state.row-newlines, 1)
def edit(from_line, bytepos=None): """ Output program line to console and position cursor. """ if state.basic_state.protected: console.write(str(from_line) + '\r') raise error.RunError(error.IFC) # list line state.basic_state.bytecode.seek(state.basic_state.line_numbers[from_line] + 1) _, output, textpos = tokenise.detokenise_line(state.basic_state.bytecode, bytepos) # no newline to avoid scrolling on line 24 console.list_line(str(output), newline=False) # find row, column position for textpos newlines, c = 0, 0 pos_row, pos_col = 0, 0 for i, byte in enumerate(output): c += 1 if chr(byte) == '\n' or c > state.console_state.screen.mode.width: newlines += 1 c = 0 if i == textpos: pos_row, pos_col = newlines, c if textpos > i: pos_row, pos_col = newlines, c + 1 if bytepos: console.set_pos(state.console_state.row - newlines + pos_row, pos_col) else: console.set_pos(state.console_state.row - newlines, 1)
def setupPluginsSettings(self): """ Config of every enabled plugin """ config = self.config choices = [] choices.append(_("Exit")) plugins = config.options("plugins") plugins.sort() for plugin in list(plugins): self.loadPlugin(plugin) if hasattr(self.plugins[plugin], "setup"): choices.append("{0:25s} {1}".format( plugin, self.plugins[plugin].about)) else: plugins.remove(plugin) while True: print() console.writeln(" " + _("Plugins settings menu"), console.color("RB", False, "")) choice = console.menu(_("Plugins:"), choices, padding=1) if choice == choices[0]: break plugin = plugins[choices.index(choice) - 1] console.write(" " + _("Configuration of") + " ", console.color("GB", False, "")) console.writeln(plugin, console.color("GB", True, "")) self.plugins[plugin].setup() config.save()
def spawn_shell(command): """ Run a SHELL subprocess. """ cmd = shell_command if command: cmd += ' -c "' + command + '"' p = pexpect.spawn(str(cmd)) while True: try: c = state.console_state.keyb.get_char() except error.Break: # ignore ctrl+break in SHELL pass if c == '\b': # BACKSPACE p.send('\x7f') elif c != '': p.send(c) while True: try: c = p.read_nonblocking(1, timeout=0) except: c = '' if c == '' or c == '\n': break elif c == '\r': console.write_line() elif c == '\b': if state.console_state.col != 1: console.set_pos(state.console_state.row, state.console_state.col-1) else: console.write(c) if c == '' and not p.isalive(): return
def bluescreen(e): """ Display a modal exception message. """ state.console_state.screen.screen(0, 0, 0, 0, new_width=80) console.clear() console.init_mode() exc_type, exc_value, exc_traceback = sys.exc_info() # log the standard python error logging.error(''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))) # format the error more readably on the screen state.console_state.screen.set_border(4) state.console_state.screen.set_attr(0x70) console.write_line('EXCEPTION') state.console_state.screen.set_attr(15) if state.basic_state.run_mode: state.basic_state.bytecode.seek(-1, 1) program.edit(program.get_line_number(state.basic_state.bytecode.tell()), state.basic_state.bytecode.tell()) console.write_line('\n') else: state.basic_state.direct_line.seek(0) console.write_line(str(tokenise.detokenise_compound_statement(state.basic_state.direct_line)[0])+'\n') stack = traceback.extract_tb(exc_traceback) for s in stack[-4:]: stack_line = '{0}:{1}, {2}'.format( os.path.split(s[0])[-1], s[1], s[2]) stack_line_2 = ' {0}'.format(s[3]) state.console_state.screen.set_attr(15) console.write_line(stack_line) state.console_state.screen.set_attr(7) console.write_line(stack_line_2) exc_message = traceback.format_exception_only(exc_type, exc_value)[0] state.console_state.screen.set_attr(15) console.write('{0}:'.format(exc_type.__name__)) state.console_state.screen.set_attr(7) console.write_line(' {0}'.format(str(exc_value))) state.console_state.screen.set_attr(0x70) console.write_line( '\nThis is a bug in PC-BASIC.') state.console_state.screen.set_attr(7) console.write( 'Sorry about that. Please send the above messages to the bugs forum\nby e-mail to ') state.console_state.screen.set_attr(15) console.write( '*****@*****.**') state.console_state.screen.set_attr(7) console.write( ' or by filing a bug\nreport at ') state.console_state.screen.set_attr(15) console.write( 'https://github.com/robhagemans/pcbasic/issues') state.console_state.screen.set_attr(7) console.write_line( '. Please include') console.write_line('as much information as you can about what you were doing and how this happened.') console.write_line('Thank you!') state.console_state.screen.set_attr(7) flow.set_pointer(False)
def todo(console, text): global core_exec try: r = core_exec.do_string(text) print r #self.interpreter.scope['_'] = r console.write(str(r), "fg_blue") except Exception as e: console.write(str(e), "fg_red") #console.write("See console for error.", "fg_red")
def handle_break(e): """ Handle a Break event. """ # print ^C at current position if not state.basic_state.input_mode and not e.stop: console.write('^C') # if we're in a program, save pointer if state.basic_state.run_mode: console.write_error_message("Break", program.get_line_number(e.pos)) state.basic_state.stop = state.basic_state.bytecode.tell() else: console.write_error_message("Break", -1) state.basic_state.execute_mode = False state.basic_state.input_mode = False
def handle_break(self, e): """ Handle a Break event. """ # print ^C at current position if not state.basic_state.input_mode and not e.stop: console.write('^C') # if we're in a program, save pointer pos = -1 if state.basic_state.run_mode: pos = state.basic_state.bytecode.tell() state.basic_state.stop = pos console.write_error_message(e.message, program.get_line_number(pos)) state.basic_state.parse_mode = False state.basic_state.input_mode = False
def playRPS(player0, player1): # Return a random number if both players are ai if player0.difficulty != player.PlayerDifficulty.HUMAN and player1.difficulty != player.PlayerDifficulty.HUMAN: return random.choice([1, 0]) # Print alternatives console.write(console.coloredText("[1] Rock", console.BLUE)) console.write(console.coloredText("[2] Paper", console.GREEN)) console.write(console.coloredText("[3] Scissor", console.RED)) console.write(console.coloredText("[q] Quit", console.MAGENTA)) # Let players0 make their choice if player0.difficulty == player.PlayerDifficulty.HUMAN: choicePlayer0 = getChoice(player0) else: choicePlayer0 = random.choice([1, 2, 3]) # Let players0 make their choice if player1.difficulty == player.PlayerDifficulty.HUMAN: choicePlayer1 = getChoice(player1) else: choicePlayer1 = random.choice([1, 2, 3]) # Present choices player_choice(player0, choicePlayer0) player_choice(player1, choicePlayer1) # Return the result r = result(player0, player1, choicePlayer0, choicePlayer1) if r == 0.5: return playRPS(player0, player1) return r
def getChoice(player): done = False choiceNum = 1 while not done: choice = getpass.getpass(player.name + " please make a choice: ") if choice.lower() == "q": exit() try: choiceNum = int(choice) if choiceNum not in range(1, 4): console.write("Only numbers 1-3 are accepted") else: done = True except: console.write("Only numbers 1-3 are accepted") return choiceNum
def input_console(prompt, readvar, newline): """ Read a list of variables for INPUT. """ # readvar is a list of (name, indices) tuples # we return a list of (name, indices, values) tuples while True: console.write(prompt) line = console.wait_screenline(write_endl=newline) inputstream = InputTextFile(line) # read the values and group them and the separators values, seps = zip(*[inputstream.read_var(v) for v in readvar]) # last separator not empty: there were too many values or commas # if there are Nones: there were too few or empty values if (seps[-1] or None in values): # good old Redo! console.write_line('?Redo from start') else: return [r + [v] for r, v in zip(readvar, values)]
def input_console(prompt, readvar, newline): """ Read a list of variables for INPUT. """ # readvar is a list of (name, indices) tuples # we return a list of (name, indices, values) tuples while True: console.write(prompt) line = console.wait_screenline(write_endl=newline) inputstream = InputTextFile(line) # read the values and group them and the separators values, seps = zip(*[inputstream.read_var(v) for v in readvar]) # last separator not empty: there were too many values or commas # if there are Nones: there were too few or empty values if (seps[-1] or None in values): # good old Redo! console.write_line('?Redo from start') else: return [ r + [v] for r, v in zip(readvar, values) ]
def input_console(prompt, readvar, newline): """ Read a list of variables for INPUT. """ # readvar is a list of (name, indices) tuples # we return a list of (name, indices, values) tuples while True: console.write(prompt) line = console.wait_screenline(write_endl=newline) inputstream = InputTextFile(line) # read the values and group them and the separators values, seps = zip(*[inputstream.read_var(v) for v in readvar]) # last separator not empty: there were too many values or commas # earlier separators empty: there were too few values # empty values will be converted to zero by string_to_number # None means a conversion error occurred if (seps[-1] or '' in seps[:-1] or None in values): # good old Redo! console.write_line('?Redo from start') else: return [r + [v] for r, v in zip(readvar, values)]
def input_console(prompt, readvar, newline): """ Read a list of variables for INPUT. """ # readvar is a list of (name, indices) tuples # we return a list of (name, indices, values) tuples while True: console.write(prompt) line = console.wait_screenline(write_endl=newline) inputstream = InputTextFile(line) # read the values and group them and the separators values, seps = zip(*[inputstream.read_var(v) for v in readvar]) # last separator not empty: there were too many values or commas # earlier separators empty: there were too few values # empty values will be converted to zero by str_to_value_keep # Nene means a conversion error occurred if (seps[-1] or '' in seps[:-1] or None in values): # good old Redo! console.write_line('?Redo from start') else: return [r + [v] for r, v in zip(readvar, values)]
def setupPluginsEnable(self, plugin): """ Enable and setup plugin with all dependencies """ if hasattr(self.plugins[plugin], "setup"): console.write(" " + _("Configuration of") + " ", console.color("GB", False, "")) console.writeln(plugin, console.color("GB", True, "")) self.plugins[plugin].setup() loaded = [] for plugin in self.config.options("plugins"): if self.config.get("plugins", plugin) == "y": loaded.append(plugin) deps = self.findDeps(loaded) for plugin in deps: self.log.warn(_("Plugin {0} pulled in as dependency.").format(plugin)) self.config.set("plugins", plugin, "y") for plugin in deps: self.setupPluginsEnable(plugin) self.config.save()
def spawn_shell(command): """ Run a SHELL subprocess. """ global shell_output cmd = shell_command if command: cmd += ' /C "' + command + '"' p = subprocess.Popen( str(cmd).split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True ) outp = threading.Thread(target=process_stdout, args=(p, p.stdout)) outp.daemon = True outp.start() errp = threading.Thread(target=process_stdout, args=(p, p.stderr)) errp.daemon = True errp.start() word = "" while p.poll() == None or shell_output: if shell_output: lines, shell_output = shell_output.split("\r\n"), "" last = lines.pop() for line in lines: # progress visible - keep updating the backend # don't process anything but video events here backend.video.check_events() console.write_line(line) console.write(last) if p.poll() != None: # drain output then break continue try: c = state.console_state.keyb.get_char() except error.Break: pass if c in ("\r", "\n"): # shift the cursor left so that CMD.EXE's echo can overwrite # the command that's already there. Note that Wine's CMD.EXE # doesn't echo the command, so it's overwritten by the output... console.write("\x1D" * len(word)) p.stdin.write(word + "\r\n") word = "" elif c == "\b": # handle backspace if word: word = word[:-1] console.write("\x1D \x1D") elif c != "": # only send to pipe when enter is pressed # needed for Wine and to handle backspace properly word += c console.write(c) outp.join() errp.join()
def remove(self,args): console.write ("the following plugins will be removed:\n %s\n do you want to continue?[Y|n] " % (", ".join(args))) resp = string.lower(console.readln()) while not resp in ("y\n","n\n","\n"): console.write ("the following plugins will be removed:\n %s\n do you want to continue?[Y|n] " % (", ".join(args))) resp = string.lower(console.readln()) if resp == 'n\n': console.writeln ("Install aborted.") return None console.writeln ("") for arg in args: if not self.__dbManager.isPluginInstalled(arg): console.writeln("Plugin %s already not installed.\n" % (arg)) elif self.__dbManager.removePlugin(arg): console.writeln("Plugin %s removed.\n" % (arg)) else: console.writeln("Error while removing plugin %s.\n" % (arg))
def spawn_shell(command): """ Run a SHELL subprocess. """ global shell_output cmd = shell_command if command: cmd += ' /C "' + command + '"' p = subprocess.Popen(str(cmd).split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) outp = threading.Thread(target=process_stdout, args=(p, p.stdout)) outp.daemon = True outp.start() errp = threading.Thread(target=process_stdout, args=(p, p.stderr)) errp.daemon = True errp.start() word = '' while p.poll() is None or shell_output: if shell_output: lines, shell_output = shell_output.split('\r\n'), '' last = lines.pop() for line in lines: console.write_line(line) console.write(last) if p.poll() is not None: # drain output then break continue try: c = state.console_state.keyb.get_char() except error.Break: pass if c in ('\r', '\n'): # shift the cursor left so that CMD.EXE's echo can overwrite # the command that's already there. Note that Wine's CMD.EXE # doesn't echo the command, so it's overwritten by the output... console.write('\x1D' * len(word)) p.stdin.write(word + '\r\n') word = '' elif c == '\b': # handle backspace if word: word = word[:-1] console.write('\x1D \x1D') elif c != '': # only send to pipe when enter is pressed # needed for Wine and to handle backspace properly word += c console.write(c) outp.join() errp.join()
def setupPluginsEnable(self, plugin): """ Enable and setup plugin with all dependencies """ if hasattr(self.plugins[plugin], "setup"): console.write(" " + _("Configuration of") + " ", console.color("GB", False, "")) console.writeln(plugin, console.color("GB", True, "")) self.plugins[plugin].setup() loaded = [] for plugin in self.config.options("plugins"): if self.config.get("plugins", plugin) == "y": loaded.append(plugin) deps = self.findDeps(loaded) for plugin in deps: self.log.warn( _("Plugin {0} pulled in as dependency.").format(plugin)) self.config.set("plugins", plugin, "y") for plugin in deps: self.setupPluginsEnable(plugin) self.config.save()
def setupPlayers(self): # Read number of players choice = console.readInt( "How many players are participating in the tournament? (3 - 8)", console.CLEAR, 3, 8, [("q", "Quit", console.MAGENTA)] ) if choice == "q": quitProgram() playerCount = int(choice) # Setup player names playerNames = [] self.players = [] for i in range(playerCount): validName = False while not validName: name = console.read("What is the name of the " + ordinalName(i) + " player? (1-12 characters)", i == 0) if name.lower() == "q": quitProgram() if len(name) > 12: console.write("Name is too long. Please choose a shorter name") continue if len(name) < 1: console.write("Name cannot be empty. Please choose another name") continue if name not in playerNames: self.players.append(player.Player(name, player.PlayerDifficulty.HUMAN)) playerNames.append(name) validName = True else: console.write("Name " + name + " is already taken. Please choose a new name")
def auto_step(): """ Generate an AUTO line number and wait for input. """ numstr = str(state.basic_state.auto_linenum) console.write(numstr) if state.basic_state.auto_linenum in state.basic_state.line_numbers: console.write('*') line = bytearray(console.wait_screenline(from_start=True)) if line[:len(numstr)+1] == numstr+'*': line[len(numstr)] = ' ' else: console.write(' ') line = bytearray(console.wait_screenline(from_start=True)) # run or store it; don't clear lines or raise undefined line number state.basic_state.direct_line = tokenise.tokenise_line(line) c = util.peek(state.basic_state.direct_line) if c == '\0': # check for lines starting with numbers (6553 6) and empty lines empty, scanline = program.check_number_start(state.basic_state.direct_line) if not empty: program.store_line(state.basic_state.direct_line) reset.clear() state.basic_state.auto_linenum = scanline + state.basic_state.auto_increment elif c != '': # it is a command, go and execute state.basic_state.execute_mode = True
def auto_step(self): """ Generate an AUTO line number and wait for input. """ numstr = str(state.basic_state.auto_linenum) console.write(numstr) if state.basic_state.auto_linenum in state.basic_state.line_numbers: console.write('*') line = bytearray(console.wait_screenline(from_start=True)) if line[:len(numstr)+1] == numstr+'*': line[len(numstr)] = ' ' else: console.write(' ') line = bytearray(console.wait_screenline(from_start=True)) # run or store it; don't clear lines or raise undefined line number state.basic_state.direct_line = tokenise.tokenise_line(line) c = util.peek(state.basic_state.direct_line) if c == '\0': # check for lines starting with numbers (6553 6) and empty lines empty, scanline = program.check_number_start(state.basic_state.direct_line) if not empty: program.store_line(state.basic_state.direct_line) reset.clear() state.basic_state.auto_linenum = scanline + state.basic_state.auto_increment elif c != '': # it is a command, go and execute state.basic_state.parse_mode = True
def spawn_shell(command): """ Run a SHELL subprocess. """ global shell_output cmd = shell_command if command: cmd += ' /C "' + command + '"' p = subprocess.Popen( str(cmd).split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) outp = threading.Thread(target=process_stdout, args=(p, p.stdout)) outp.daemon = True outp.start() errp = threading.Thread(target=process_stdout, args=(p, p.stderr)) errp.daemon = True errp.start() word = '' while p.poll() is None or shell_output: if shell_output: lines, shell_output = shell_output.split('\r\n'), '' last = lines.pop() for line in lines: console.write_line(line) console.write(last) if p.poll() is not None: # drain output then break continue try: c = state.console_state.keyb.get_char() except error.Break: pass if c in ('\r', '\n'): # shift the cursor left so that CMD.EXE's echo can overwrite # the command that's already there. Note that Wine's CMD.EXE # doesn't echo the command, so it's overwritten by the output... console.write('\x1D' * len(word)) p.stdin.write(word + '\r\n') word = '' elif c == '\b': # handle backspace if word: word = word[:-1] console.write('\x1D \x1D') elif c != '': # only send to pipe when enter is pressed # needed for Wine and to handle backspace properly word += c console.write(c) outp.join() errp.join()
def write(self, s): """ Write string s to SCRN: """ # writes to SCRN files should *not* be echoed do_echo = self.is_master self._col = state.console_state.col # take column 80+overflow into account if state.console_state.overflow: self._col += 1 # only break lines at the start of a new string. width 255 means unlimited width s_width = 0 newline = False # find width of first line in s for c in str(s): if c in ('\r', '\n'): newline = True break if c == '\b': # for lpt1 and files, nonprinting chars are not counted in LPOS; but chr$(8) will take a byte out of the buffer s_width -= 1 elif ord(c) >= 32: # nonprinting characters including tabs are not counted for WIDTH s_width += 1 if (self.width != 255 and state.console_state.row != state.console_state.screen.mode.height and self.col != 1 and self.col - 1 + s_width > self.width and not newline): console.write_line(do_echo=do_echo) self._col = 1 cwidth = state.console_state.screen.mode.width for c in str(s): if self.width <= cwidth and self.col > self.width: console.write_line(do_echo=do_echo) self._col = 1 if self.col <= cwidth or self.width <= cwidth: console.write(c, do_echo=do_echo) if c in ('\n', '\r'): self._col = 1 else: self._col += 1
def write(self, s): """ Write string s to SCRN: """ # writes to SCRN files should *not* be echoed do_echo = self.is_master self._col = state.console_state.col # take column 80+overflow into account if state.console_state.overflow: self._col += 1 # only break lines at the start of a new string. width 255 means unlimited width s_width = 0 newline = False # find width of first line in s for c in str(s): if c in ('\r', '\n'): newline = True break if c == '\b': # for lpt1 and files, nonprinting chars are not counted in LPOS; but chr$(8) will take a byte out of the buffer s_width -= 1 elif ord(c) >= 32: # nonprinting characters including tabs are not counted for WIDTH s_width += 1 if (self.width != 255 and state.console_state.row != state.console_state.screen.mode.height and self.col != 1 and self.col-1 + s_width > self.width and not newline): console.write_line(do_echo=do_echo) self._col = 1 cwidth = state.console_state.screen.mode.width for c in str(s): if self.width <= cwidth and self.col > self.width: console.write_line(do_echo=do_echo) self._col = 1 if self.col <= cwidth or self.width <= cwidth: console.write(c, do_echo=do_echo) if c in ('\n', '\r'): self._col = 1 else: self._col += 1
def remove(self, args): console.write( "the following plugins will be removed:\n %s\n do you want to continue?[Y|n] " % (", ".join(args))) resp = string.lower(console.readln()) while not resp in ("y\n", "n\n", "\n"): console.write( "the following plugins will be removed:\n %s\n do you want to continue?[Y|n] " % (", ".join(args))) resp = string.lower(console.readln()) if resp == 'n\n': console.writeln("Install aborted.") return None console.writeln("") for arg in args: if not self.__dbManager.isPluginInstalled(arg): console.writeln("Plugin %s already not installed.\n" % (arg)) elif self.__dbManager.removePlugin(arg): console.writeln("Plugin %s removed.\n" % (arg)) else: console.writeln("Error while removing plugin %s.\n" % (arg))
def handleTie(player0, player1): console.write("") #console.clear() console.write("There was a tie between players " + player0.name + " and " + player1.name + ". This will be resolved with a game of Rock-paper-scissor") return rps.playRPS(player0, player1)
def startKO(self): # Randomize players in first bracket allPlayers = self.desc.players self.bracketsR0 = [] for i in range(4): i = random.choice(list(range(len(allPlayers)))) player0 = allPlayers[i] del allPlayers[i] i = random.choice(list(range(len(allPlayers)))) player1 = allPlayers[i] del allPlayers[i] self.bracketsR0.append(BracketKO(player0, player1)) # Show brackets console.clear() console.write("The brackets for the first round of Knockout are:") koDisp = display.KO_displayer(self.bracketsR0) koDisp.show() # Play first 4 games console.write("") for b in self.bracketsR0: # TODO(Filip): PLAY THE REAL GAME b.setResult(playGame(b.player0, b.player1)) # Handle tie if b.result == 0.5: b.setResult(handleTie(b.player0, b.player1)) # Setup 2 new brackets self.bracketsR1 = [] for i in range(2): # Determine which players won bracket0 = self.bracketsR0[i * 2] bracket1 = self.bracketsR0[i * 2 + 1] self.bracketsR1.append(createSubBracket(bracket0, bracket1)) # Show brackets console.clear() console.write("The brackets for the second round of Knockout are:") koDisp.add_bracket(self.bracketsR1) koDisp.show() # Play both games for b in self.bracketsR1: # TODO(Filip): PLAY THE REAL GAME b.setResult(playGame(b.player0, b.player1)) # Handle tie if b.result == 0.5: b.setResult(handleTie(b.player0, b.player1)) # Setup final brackets self.bracketFinal = createSubBracket(self.bracketsR1[0], self.bracketsR1[1]) # Show brackets console.clear() console.write("The bracket for the final round of Knockout is:") koDisp.add_bracket(self.bracketFinal) koDisp.show() # Play final # TODO(Filip): PLAY THE REAL GAME self.bracketFinal.setResult(playGame(self.bracketFinal.player0, self.bracketFinal.player1)) # Handle tie if self.bracketFinal.result == 0.5: self.bracketFinal.setResult(handleTie(self.bracketFinal.player0, self.bracketFinal.player1)) # Show final result brackets winner = self.bracketFinal.player0 if self.bracketFinal.result == 1 else self.bracketFinal.player1 console.clear() console.write("The winner is " + winner.name) koDisp.add_winner(winner) koDisp.show()
def playGame(player0, player1): result = -1 # Check if we should flip players to balance colors flip = True if player0.whiteCount > player1.whiteCount else False if flip: player0.blackCount += 1 player1.whiteCount += 1 else: player0.whiteCount += 1 player1.blackCount += 1 # Play AI vs AI game if player0.isAI() and player1.isAI(): return playAIvsAI(player0, player1) # Play player vs player if not player0.isAI() and not player1.isAI(): if flip: console.write("Playing game " + player1.name + " vs " + player0.name) result = startGame(0, 0) result = platformToTournamentResult(result) else: console.write("Playing game " + player0.name + " vs " + player1.name) result = startGame(0, 0) result = platformToTournamentResult(result) # Play player vs AI if not player0.isAI() and player1.isAI(): diffArg = getDifficultyName(player1.difficulty).lower() if flip: console.write("Playing game " + player1.name + " vs " + player0.name) result = startGame(1, diffArg) result = platformToTournamentResult(result) else: console.write("Playing game " + player0.name + " vs " + player1.name) result = startGame(2, diffArg) result = platformToTournamentResult(result) # Play AI vs player if player0.isAI() and not player1.isAI(): diffArg = getDifficultyName(player1.difficulty).lower() if flip: console.write("Playing game " + player1.name + " vs " + player0.name) result = startGame(2, diffArg) result = platformToTournamentResult(result) else: console.write("Playing game " + player0.name + " vs " + player1.name) result = startGame(1, diffArg) result = platformToTournamentResult(result) # There should not be another case! else: assert False, "\"SHOULD NEVER HAPPEN\"" # Quit program is result is -1 if result == -1: quitProgram() #console.write("Playing game: " + player0.name + " vs " + player1.name) return result
def synchronizeListWithRepository(self, list): Repository.synchronizeListWithRepository(self, list) console.write("update: " + list.repository + '\n') console.write("loading ") localRevision = int(list.getRevision()) if self.__pluginsXml == None: self.__getPluginsList() pluginsElement = self.__pluginsXml.getElementsByTagName("PLUGINS") remoteRevision = int(pluginsElement[0].getAttribute("revision")) console.write(". ") if localRevision == remoteRevision: console.write("local list already updated.\n") if localRevision > remoteRevision: raise error.FatalError("Local plugins list corrupted!!") if localRevision < remoteRevision: list.resetToEmptyListFile( ` remoteRevision `) console.write(". ") pluginElements = self.__pluginsXml.getElementsByTagName("PLUGIN") plugins = [plugin.firstChild.data for plugin in pluginElements] console.write(". ") for plugin in plugins: url = self.url + "/src/" + plugin + "/plugin.xml" pluginXml = xml.dom.minidom.parse(urllib.urlopen(url)) console.write(". ") element = pluginXml.getElementsByTagName("PLUGIN") pluginInfo = list.addPluginWithXml(element[0]) list.synchronizeListWithFileSystem() console.write("DONE.\n")
def install(self,args): for arg in args: (plugin,list) = self.__find(arg) if plugin == None: console.writeln("No plugin with this name is present in the plugin database.") return None myserverVersion = self.__versionConverter(config.MYSERVER_VERSION) minversion = self.__versionConverter(plugin.getMyServerMinVersion()) maxversion = self.__versionConverter(plugin.getMyServerMaxVersion()) if myserverVersion < minversion or myserverVersion > maxversion: console.writeln("Plugin incompatible with GNU MyServer installed version.") return None toInstall = [(plugin,list)] (result,errors) = self.__recursiveDependencesChecker(plugin) if len(errors) != 0: for (plugin,msg) in errors: console.writeln("Error while install %s: %s" % (plugin["name"][0]["value"],msg)) return None toInstall.extend(result) console.write ("the following plugins will be installed:\n %s\n do you want to continue?[Y|n] " % (", ".join(plugin["name"][0]["value"] for (plugin,list) in toInstall))) resp = string.lower(console.readln()) while not resp in ("y\n","n\n","\n"): console.write ("the following plugins will be installed:\n %s\n do you want to continue?[Y|n] " % (", ".join(plugin["name"][0]["value"] for (plugin,list) in toInstall))) resp = string.lower(console.readln()) if resp == 'n\n': console.writeln ("Install aborted.") return None downloadErrors = [] for (plugin,list) in toInstall: if self.__dbManager.isPluginInstalled(plugin["name"][0]["value"]): console.writeln ("plugin %s already installed." % (plugin["name"][0]["value"])) continue rep = self.__repManager.getRepository(list.repository) rep = rep(list.repository) if not rep.getPluginBinary(list,plugin): downloadErrors.append(plugin) if len(downloadErrors) != 0: console.writeln ("Errors retriving the follow plugins packages: %s" % (" ".join("%s-%s-%s.tar.gz" % (plugin["name"][0]["value"],plugin["version"][0]["value"],config.arch) for plugin in downloadErrors))) return None for (plugin,list) in toInstall: if self.__dbManager.isPluginInstalled(plugin["name"][0]["value"]): continue filename = config.MYSERVER_PLUGIN_DIR + "/%s-%s-%s.tar.gz" % (plugin["name"][0]["value"],plugin["version"][0]["value"],config.arch) import tarfile console.writeln("Exctracting plugin package..") try: tarf = tarfile.open(filename.encode("ascii"),"r|gz") tarf.extractall (config.MYSERVER_PLUGIN_DIR) except Exception: console.writeln("Error while exctracting plugin package!") return None import os os.remove(filename) console.writeln("plugin %s installed.\n" % (plugin["name"][0]["value"]))
def write_console(self, stream): ports, declarations, definitions = console.write(stream) self.ports.extend(ports) self.declarations.extend(declarations) self.definitions.extend(definitions)
def install(self, args): for arg in args: (plugin, list) = self.__find(arg) if plugin == None: console.writeln( "No plugin with this name is present in the plugin database." ) return None myserverVersion = self.__versionConverter(config.MYSERVER_VERSION) minversion = self.__versionConverter( plugin.getMyServerMinVersion()) maxversion = self.__versionConverter( plugin.getMyServerMaxVersion()) if myserverVersion < minversion or myserverVersion > maxversion: console.writeln( "Plugin incompatible with GNU MyServer installed version.") return None toInstall = [(plugin, list)] (result, errors) = self.__recursiveDependencesChecker(plugin) if len(errors) != 0: for (plugin, msg) in errors: console.writeln("Error while install %s: %s" % (plugin["name"][0]["value"], msg)) return None toInstall.extend(result) console.write( "the following plugins will be installed:\n %s\n do you want to continue?[Y|n] " % (", ".join(plugin["name"][0]["value"] for (plugin, list) in toInstall))) resp = string.lower(console.readln()) while not resp in ("y\n", "n\n", "\n"): console.write( "the following plugins will be installed:\n %s\n do you want to continue?[Y|n] " % (", ".join(plugin["name"][0]["value"] for (plugin, list) in toInstall))) resp = string.lower(console.readln()) if resp == 'n\n': console.writeln("Install aborted.") return None downloadErrors = [] for (plugin, list) in toInstall: if self.__dbManager.isPluginInstalled( plugin["name"][0]["value"]): console.writeln("plugin %s already installed." % (plugin["name"][0]["value"])) continue rep = self.__repManager.getRepository(list.repository) rep = rep(list.repository) if not rep.getPluginBinary(list, plugin): downloadErrors.append(plugin) if len(downloadErrors) != 0: console.writeln( "Errors retriving the follow plugins packages: %s" % (" ".join("%s-%s-%s.tar.gz" % (plugin["name"][0]["value"], plugin["version"][0]["value"], config.arch) for plugin in downloadErrors))) return None for (plugin, list) in toInstall: if self.__dbManager.isPluginInstalled( plugin["name"][0]["value"]): continue filename = config.MYSERVER_PLUGIN_DIR + "/%s-%s-%s.tar.gz" % ( plugin["name"][0]["value"], plugin["version"][0]["value"], config.arch) import tarfile console.writeln("Exctracting plugin package..") try: tarf = tarfile.open(filename.encode("ascii"), "r|gz") tarf.extractall(config.MYSERVER_PLUGIN_DIR) except Exception: console.writeln("Error while exctracting plugin package!") return None import os os.remove(filename) console.writeln("plugin %s installed.\n" % (plugin["name"][0]["value"]))
def synchronizeListWithRepository(self, list): Repository.synchronizeListWithRepository(self,list) console.write("update: "+ list.repository + '\n') console.write("loading ") localRevision = int(list.getRevision()) if self.__pluginsXml == None: self.__getPluginsList() pluginsElement = self.__pluginsXml.getElementsByTagName("PLUGINS") remoteRevision = int(pluginsElement[0].getAttribute("revision")) console.write(". ") if localRevision == remoteRevision: console.write("local list already updated.\n") if localRevision > remoteRevision: raise error.FatalError("Local plugins list corrupted!!") if localRevision < remoteRevision: list.resetToEmptyListFile(`remoteRevision`) console.write(". ") pluginElements = self.__pluginsXml.getElementsByTagName("PLUGIN") plugins = [plugin.firstChild.data for plugin in pluginElements] console.write(". ") for plugin in plugins: url = self.url + "/src/" + plugin + "/plugin.xml" pluginXml = xml.dom.minidom.parse(urllib.urlopen(url)) console.write(". ") element = pluginXml.getElementsByTagName("PLUGIN") pluginInfo = list.addPluginWithXml(element[0]) list.synchronizeListWithFileSystem() console.write("DONE.\n")