Example #1
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, app, testmode):
        self.app = app
        self.testmode = testmode
        self.paused = False
        self._tournament = None

        QtGui.QMainWindow.__init__(self)
        self.ui = MWClass()
        self.ui.setupUi(self)
        self.ui.nbattles_frame.hide()

        self.scene = Scene()
        view = self.ui.arenaview
        view.setScene(self.scene)
        self.scene.view = view
        view.show()

        self.start_game()

        self.debug_robot = None

        self.run_tournament(1)
        self.singleStep()

        self.ticktimer = self.startTimer(17)

        self.editors = []
        self._fdir = None

        self.setup_settings()

        # Call resize a bit later or else view will not resize properly
        self._initialresize = True
        QtCore.QTimer.singleShot(1, self.resizeEvent)

    def start_game(self):
        import game

        self.game = game.Game(self.testmode, self._tournament)
        self.game.w.v.scene = self.scene
        self.game.w.v.app = self.app
        self.game.w.v.rinfo = self.ui.rinfo
        self.game.w.v.setrend()
        self.game.load_robots()

        self.ui.countdown.display(conf.maxtime)

    def closeEvent(self, ev=None):
        self.killTimer(self.ticktimer)

        if len(self.game.procs) > 0:
            self.game.finish(False)
            stats.dbclose()

        doquit = True
        # Try to close any open editor windows
        for te in self.editors:
            if te.isVisible():
                te.close()

        # If any are still open, don't quit
        for te in self.editors:
            if te.isVisible():
                doquit = False

        if doquit:
            QtGui.qApp.quit()

    def startBattle(self):
        if self.paused:
            self.pauseBattle(False)

    def pauseBattle(self, ev):
        self.paused = ev
        if self.paused:
            self.ui.actionPause.setChecked(True)
            self.ui.actionStart_battle.setDisabled(False)
        else:
            self.ui.actionPause.setChecked(False)
            self.ui.actionStart_battle.setDisabled(True)

    def singleStep(self):
        self.pauseBattle(True)
        self.game.tick()
        if self.debug_robot is not None:
            self.update_debug_robot()

    def timerEvent(self, ev):
        if not self.paused:
            self.game.tick()
            if self.debug_robot is not None:
                self.update_debug_robot()

            if not self.game.rnd % 60:
                remaining = conf.maxtime - (self.game.rnd / 60)
                self.ui.countdown.display(remaining)

            if (self.game.rnd > 60 * conf.maxtime
                    or len(self.game.procs) <= 1):
                if not self.testmode:
                    self.battle_over()

    def battle_over(self):
        self.pauseBattle(True)
        self.game.finish()
        if self._supertournament_combos:
            if self._tournament_battles >= 1:
                self._tournament_battles -= 1
                self._supertournament_battles -= 1

            if self._tournament_battles:
                self.ui.nbattles.display(self._supertournament_battles)
                self.restart()
                self.paused = True
                self.startBattle()
            else:
                conf.robots = self._supertournament_combos.pop(0)
                self._tournament_battles = self._supertournament_nbattles
                self.ui.nbattles.display(self._supertournament_battles)
                self.restart()
                self.paused = True
                self.startBattle()

            if not self._supertournament_combos:
                self._supertournament_combos = None
                self._supertournament_battles = None
                self._supertournament_nbattles = None

        elif self._tournament:
            if self._tournament_battles >= 1:
                self._tournament_battles -= 1

            if self._tournament_battles:
                self.ui.nbattles.display(self._tournament_battles)
                self.restart()
                self.paused = True
                self.startBattle()
            else:
                self.ui.nbattles_frame.hide()
                self.sw = StatsWindow('Tournament Results')
                self.sw.tournament_results(self._tournament)
                self._tournament = None
                self.sw.show()

    def test(self):
        self.scene.r.set_rotation(self.rot)
        self.scene.r.set_position(self.pos)
        self.scene.r.set_turr_rot(self.turr_rot)

        self.rot += 1
        x, y = self.pos
        self.pos = x - 2, y + 1

        self.turr_rot -= 2

    def resizeEvent(self, ev=None):
        if self._initialresize:
            # Initial scaling comes out wrong for some reason. Fake it.
            scale = 0.66725
            self._initialresize = False
        else:
            frect = self.ui.arenaframe.frameRect()
            sx, sy = frect.width(), frect.height()
            minsize = min((sx, sy))
            scale = 0.85 * (minsize / 600.)

        trans = QtGui.QTransform()
        trans.scale(scale, scale)
        self.scene.view.setTransform(trans)

    def notImplementedYet(self):
        self.niy = NotImplementedYet()
        self.niy.show()

    def configure(self):
        self.sui = Settings()
        self.sui.show()

    def loadRobot(self, efdir=None):
        if efdir is not None:
            fdir = efdir
        elif self._fdir is None:
            fdir = QtCore.QString(os.path.abspath(conf.base_dir))
        else:
            fdir = self._fdir

        fp = QtGui.QFileDialog.getOpenFileName(self, 'Open file', fdir,
                                               'Text files (*.py)')
        if fp:
            # Check to see if the file is already open in an editor
            for ed in self.editors:
                if ed._filepath == fp:
                    # If it is not visible, show it
                    if not ed.isVisible():
                        ed.show()
                    # raise the window and get out
                    ed.activateWindow()
                    ed.raise_()
                    return

            te = TextEditor(self)
            self.editors.append(te)
            te.openfile(fp)
            te.show()

            if efdir is None:
                # Opening from Main Window. Remember directory.
                self._fdir = te._fdir

    def newRobot(self):
        te = TextEditor(self)
        self.editors.append(te)
        te.openfile()  # Open the template for a new robot
        te.show()

    def newBattle(self):
        self.com = BattleEditor(self)
        self.com.show()

    def newTournament(self):
        self.tournament = TournamentEditor(self)
        self.tournament.show()

    def run_tournament(self, nbattles, dt=None):
        if dt is None:
            import datetime
            dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self._tournament = dt
        self._tournament_battles = nbattles
        self._supertournament_battles = None
        self._supertournament_nbattles = None
        self._supertournament_combos = None
        self.ui.nbattles.display(nbattles)
        self.ui.nbattles_frame.show()
        self.restart()
        self.paused = True
        self.startBattle()

    def run_supertournament(self, nbattles):
        import datetime
        dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        from itertools import combinations
        combos = []
        nrobots = len(conf.robots)
        for n in range(2, nrobots + 1):
            combos.extend(combinations(conf.robots, n))
        self._tournament = dt
        self._tournament_battles = nbattles
        self._supertournament_nbattles = nbattles
        self._supertournament_battles = nbattles * len(combos)
        conf.robots = combos.pop(0)
        self._supertournament_combos = combos
        self.ui.nbattles.display(self._supertournament_battles)
        self.ui.nbattles_frame.show()
        self.restart()
        self.paused = True
        self.startBattle()

    def deleteLayoutItems(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.deleteLayoutItems(item.layout())

    def restart(self):
        if self._tournament is None:
            self.run_tournament(1)
            return

        rinfo = self.ui.rinfo

        for name, robot in self.game.w.robots.items():
            robot.v.kill()

        self.game.finish(False)
        import world
        world.Robot.nrobots = 0
        Robot.nrobots = 0

        self.scene.removeItem(self.scene.arenarect)
        self.deleteLayoutItems(rinfo)

        self.scene.add_arenarect()
        self.start_game()

        paused = self.paused
        self.singleStep()
        self.pauseBattle(paused)

    def help(self):
        QtGui.QDesktopServices().openUrl(QtCore.QUrl(conf.help_url))

    def about(self):
        AboutDialog(self.app).exec_()

    def setup_settings(self):
        self._fdir = conf.base_dir

    def enable_debug(self):
        if self.ui.actionEnableDebug.isChecked():
            self.game.enable_debug()
            self.ag = QtGui.QActionGroup(self.ui.menuDebug)
            self.ag.triggered.connect(self.choose_robot_debug)
            items = self.game.models.items()
            for robotname, model in items:
                ac = QtGui.QAction(robotname, self.ag)
                ac.setCheckable(True)
                self.ui.menuDebug.addAction(ac)
        else:
            self.game.disable_debug()
            for ac in self.ag.actions():
                self.ui.menuDebug.removeAction(ac)
            self.debug_robot = None

        self.singleStep()

    def choose_robot_debug(self):
        if self.debug_robot is not None:
            self.debug_robot_window.destroy()
            self.debug_robot_logfile.close()
        rname = self.ag.checkedAction().text()
        self.debug_robot = str(rname)
        self.debug_robot_window = RDebug(rname)
        self.debug_robot_window.show()
        logfilename = '%s.log' % rname
        logdir = os.path.join(conf.base_dir, conf.logdir)
        logfilepath = os.path.join(logdir, logfilename)
        logfile = open(logfilepath)
        self.debug_robot_logfile = logfile
        self.singleStep()

    def update_debug_robot(self):
        game = self.game
        model = game.models[self.debug_robot]
        body = model.body
        window = self.debug_robot_window

        tick = str(game.rnd)
        window.tick.setText(tick)

        health = max(int(model.health), 0)
        window.health.setValue(health)

        pos = body.position
        x, y = int(pos.x), int(pos.y)
        window.posx.setValue(x)
        window.posy.setValue(y)

        tur = str(model.get_turretangle())
        window.turret.setText(tur)

        pingtype = str(model._pingtype)
        pingangle = str(model._pingangle)
        pingdistance = str(model._pingdist)
        window.pingtype.setText(pingtype)
        window.pingangle.setText(pingangle)
        window.pingdistance.setText(pingdistance)

        gyro = str(model.gyro())
        window.gyro.setText(gyro)

        heat = int(model._cannonheat)
        window.cannonheat.setValue(heat)

        loading = str(model._cannonreload)
        window.cannonloading.setText(loading)

        pinged = str(model._pinged == game.rnd - 1)
        window.pinged.setText(pinged)

        for kind in [
                'FORCE',
                'TORQUE',
                'FIRE',
                'PING',
                'TURRET',
                'INACTIVE',
        ]:
            attr = 'c_%s' % kind
            attr = attr.lower()
            val = str(model._commands.get(kind, ''))
            getattr(window, attr).setText(val)

        while True:
            where = self.debug_robot_logfile.tell()
            line = self.debug_robot_logfile.readline()
            if not line:
                self.debug_robot_logfile.seek(where)
                break
            else:
                window.logarea.append(line.strip())

    def show_robot_stats(self):
        self.sw = StatsWindow('Robot Stats')
        self.sw.robot_stats()
        self.sw.show()

    def show_current_stats(self):
        self.sw = StatsWindow('Tournament Stats')
        self.sw.tournament_results(self._tournament)
        self.sw.show()

    def previous_tournaments(self):
        self.pt = TournamentStatsChooser()
        self.pt.show()
Example #2
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, app, testmode):
        self.app = app
        self.testmode = testmode
        self.paused = False
        self._tournament = None

        QtGui.QMainWindow.__init__(self)
        self.ui = MWClass()
        self.ui.setupUi(self)
        self.ui.nbattles_frame.hide()

        self.scene = Scene()
        view = self.ui.arenaview
        view.setScene(self.scene)
        self.scene.view = view
        view.show()

        self.start_game()

        self.debug_robot = None

        self.run_tournament(1)
        self.singleStep()

        self.ticktimer = self.startTimer(17)

        self.editors = []
        self._fdir = None

        self.setup_settings()

        # Call resize a bit later or else view will not resize properly
        self._initialresize = True
        QtCore.QTimer.singleShot(1, self.resizeEvent)

    def start_game(self):
        import game

        self.game = game.Game(self.testmode, self._tournament)
        self.game.w.v.scene = self.scene
        self.game.w.v.app = self.app
        self.game.w.v.rinfo = self.ui.rinfo
        self.game.w.v.setrend()
        self.game.load_robots()

        self.ui.countdown.display(conf.maxtime)

    def closeEvent(self, ev=None):
        self.killTimer(self.ticktimer)

        if len(self.game.procs) > 0:
            self.game.finish(False)
            stats.dbclose()

        doquit = True
        # Try to close any open editor windows
        for te in self.editors:
            if te.isVisible():
                te.close()

        # If any are still open, don't quit
        for te in self.editors:
            if te.isVisible():
                doquit = False

        if doquit:
            QtGui.qApp.quit()

    def startBattle(self):
        if self.paused:
            self.pauseBattle(False)

    def pauseBattle(self, ev):
        self.paused = ev
        if self.paused:
            self.ui.actionPause.setChecked(True)
            self.ui.actionStart_battle.setDisabled(False)
        else:
            self.ui.actionPause.setChecked(False)
            self.ui.actionStart_battle.setDisabled(True)

    def singleStep(self):
        self.pauseBattle(True)
        self.game.tick()
        if self.debug_robot is not None:
            self.update_debug_robot()

    def timerEvent(self, ev):
        if not self.paused:
            self.game.tick()
            if self.debug_robot is not None:
                self.update_debug_robot()

            if not self.game.rnd % 60:
                remaining = conf.maxtime - (self.game.rnd / 60)
                self.ui.countdown.display(remaining)

            if (self.game.rnd > 60 * conf.maxtime or
                    len(self.game.procs) <= 1):
                if not self.testmode:
                    self.battle_over()

    def battle_over(self):
        self.pauseBattle(True)
        self.game.finish()
        if self._supertournament_combos:
            if self._tournament_battles >= 1:
                self._tournament_battles -= 1
                self._supertournament_battles -= 1

            if self._tournament_battles:
                self.ui.nbattles.display(self._supertournament_battles)
                self.restart()
                self.paused = True
                self.startBattle()
            else:
                conf.robots = self._supertournament_combos.pop(0)
                self._tournament_battles = self._supertournament_nbattles
                self.ui.nbattles.display(self._supertournament_battles)
                self.restart()
                self.paused = True
                self.startBattle()

            if not self._supertournament_combos:
                self._supertournament_combos = None
                self._supertournament_battles = None
                self._supertournament_nbattles = None

        elif self._tournament:
            if self._tournament_battles >= 1:
                self._tournament_battles -= 1

            if self._tournament_battles:
                self.ui.nbattles.display(self._tournament_battles)
                self.restart()
                self.paused = True
                self.startBattle()
            else:
                self.ui.nbattles_frame.hide()
                self.sw = StatsWindow('Tournament Results')
                self.sw.tournament_results(self._tournament)
                self._tournament = None
                self.sw.show()

    def test(self):
        self.scene.r.set_rotation(self.rot)
        self.scene.r.set_position(self.pos)
        self.scene.r.set_turr_rot(self.turr_rot)

        self.rot += 1
        x, y = self.pos
        self.pos = x-2, y+1

        self.turr_rot -= 2

    def resizeEvent(self, ev=None):
        if self._initialresize:
            # Initial scaling comes out wrong for some reason. Fake it.
            scale = 0.66725
            self._initialresize = False
        else:
            frect = self.ui.arenaframe.frameRect()
            sx, sy = frect.width(), frect.height()
            minsize = min((sx, sy))
            scale = 0.85*(minsize/600.)

        trans = QtGui.QTransform()
        trans.scale(scale, scale)
        self.scene.view.setTransform(trans)

    def notImplementedYet(self):
        self.niy = NotImplementedYet()
        self.niy.show()

    def configure(self):
        self.sui = Settings()
        self.sui.show()

    def loadRobot(self, efdir=None):
        if efdir is not None:
            fdir = efdir
        elif self._fdir is None:
            fdir = QtCore.QString(os.path.abspath(conf.base_dir))
        else:
            fdir = self._fdir

        fp = QtGui.QFileDialog.getOpenFileName(self, 'Open file', fdir, 'Text files (*.py)')
        if fp:
            # Check to see if the file is already open in an editor
            for ed in self.editors:
                if ed._filepath == fp:
                    # If it is not visible, show it
                    if not ed.isVisible():
                        ed.show()
                    # raise the window and get out
                    ed.activateWindow()
                    ed.raise_()
                    return

            te = TextEditor(self)
            self.editors.append(te)
            te.openfile(fp)
            te.show()

            if efdir is None:
                # Opening from Main Window. Remember directory.
                self._fdir = te._fdir

    def newRobot(self):
        te = TextEditor(self)
        self.editors.append(te)
        te.openfile() # Open the template for a new robot
        te.show()

    def newBattle(self):
        self.com = BattleEditor(self)
        self.com.show()

    def newTournament(self):
        self.tournament = TournamentEditor(self)
        self.tournament.show()

    def run_tournament(self, nbattles, dt=None):
        if dt is None:
            import datetime
            dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self._tournament = dt
        self._tournament_battles = nbattles
        self._supertournament_battles = None
        self._supertournament_nbattles = None
        self._supertournament_combos = None
        self.ui.nbattles.display(nbattles)
        self.ui.nbattles_frame.show()
        self.restart()
        self.paused = True
        self.startBattle()

    def run_supertournament(self, nbattles):
        import datetime
        dt = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        from itertools import combinations
        combos = []
        nrobots = len(conf.robots)
        for n in range(2, nrobots+1):
            combos.extend(combinations(conf.robots, n))
        self._tournament = dt
        self._tournament_battles = nbattles
        self._supertournament_nbattles = nbattles
        self._supertournament_battles = nbattles * len(combos)
        conf.robots = combos.pop(0)
        self._supertournament_combos = combos
        self.ui.nbattles.display(self._supertournament_battles)
        self.ui.nbattles_frame.show()
        self.restart()
        self.paused = True
        self.startBattle()

    def deleteLayoutItems(self, layout):
        if layout is not None:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
                else:
                    self.deleteLayoutItems(item.layout())

    def restart(self):
        if self._tournament is None:
            self.run_tournament(1)
            return

        rinfo = self.ui.rinfo

        for name, robot in self.game.w.robots.items():
            robot.v.kill()

        self.game.finish(False)
        import world
        world.Robot.nrobots = 0
        Robot.nrobots = 0

        self.scene.removeItem(self.scene.arenarect)
        self.deleteLayoutItems(rinfo)

        self.scene.add_arenarect()
        self.start_game()

        paused = self.paused
        self.singleStep()
        self.pauseBattle(paused)

    def help(self):
        QtGui.QDesktopServices().openUrl(QtCore.QUrl(conf.help_url))

    def about(self):
        AboutDialog(self.app).exec_()

    def setup_settings(self):
        self._fdir = conf.base_dir

    def enable_debug(self):
        if self.ui.actionEnableDebug.isChecked():
            self.game.enable_debug()
            self.ag = QtGui.QActionGroup(self.ui.menuDebug)
            self.ag.triggered.connect(self.choose_robot_debug)
            items = self.game.models.items()
            for robotname, model in items:
                ac = QtGui.QAction(robotname, self.ag)
                ac.setCheckable(True)
                self.ui.menuDebug.addAction(ac)
        else:
            self.game.disable_debug()
            for ac in self.ag.actions():
                self.ui.menuDebug.removeAction(ac)
            self.debug_robot = None

        self.singleStep()

    def choose_robot_debug(self):
        if self.debug_robot is not None:
            self.debug_robot_window.destroy()
            self.debug_robot_logfile.close()
        rname = self.ag.checkedAction().text()
        self.debug_robot = str(rname)
        self.debug_robot_window = RDebug(rname)
        self.debug_robot_window.show()
        logfilename = '%s.log' % rname
        logdir = os.path.join(conf.base_dir, conf.logdir)
        logfilepath = os.path.join(logdir, logfilename)
        logfile = open(logfilepath)
        self.debug_robot_logfile = logfile
        self.singleStep()

    def update_debug_robot(self):
        game = self.game
        model = game.models[self.debug_robot]
        body = model.body
        window = self.debug_robot_window

        tick = str(game.rnd)
        window.tick.setText(tick)

        health = max(int(model.health), 0)
        window.health.setValue(health)

        pos = body.position
        x, y = int(pos.x), int(pos.y)
        window.posx.setValue(x)
        window.posy.setValue(y)

        tur = str(model.get_turretangle())
        window.turret.setText(tur)

        pingtype = str(model._pingtype)
        pingangle = str(model._pingangle)
        pingdistance = str(model._pingdist)
        window.pingtype.setText(pingtype)
        window.pingangle.setText(pingangle)
        window.pingdistance.setText(pingdistance)

        gyro = str(model.gyro())
        window.gyro.setText(gyro)

        heat = int(model._cannonheat)
        window.cannonheat.setValue(heat)

        loading = str(model._cannonreload)
        window.cannonloading.setText(loading)

        pinged = str(model._pinged == game.rnd - 1)
        window.pinged.setText(pinged)

        for kind in [
                'FORCE',
                'TORQUE',
                'FIRE',
                'PING',
                'TURRET',
                'INACTIVE',
                ]:
            attr = 'c_%s' % kind
            attr = attr.lower()
            val = str(model._commands.get(kind, ''))
            getattr(window, attr).setText(val)

        while True:
            where = self.debug_robot_logfile.tell()
            line = self.debug_robot_logfile.readline()
            if not line:
                self.debug_robot_logfile.seek(where)
                break
            else:
                window.logarea.append(line.strip())

    def show_robot_stats(self):
        self.sw = StatsWindow('Robot Stats')
        self.sw.robot_stats()
        self.sw.show()

    def show_current_stats(self):
        self.sw = StatsWindow('Tournament Stats')
        self.sw.tournament_results(self._tournament)
        self.sw.show()

    def previous_tournaments(self):
        self.pt = TournamentStatsChooser()
        self.pt.show()
Example #3
0
 def newTournament(self):
     self.tournament = TournamentEditor(self)
     self.tournament.show()
Example #4
0
 def newTournament(self):
     self.tournament = TournamentEditor(self)
     self.tournament.show()