Exemple #1
0
def main():
    # Create Problem
    polynomial = Polynomial(num_terms=5, num_dimensions=2)
    log.info(polynomial)

    # Define Search Range
    search_range = SearchRange()
    search_range.set_feasible_range(10000, 2)

    # Solvers
    # brute_force_solver = BruteForceSolver(search_range)
    genetic_algorithm_solver = GeneticAlgorithmSolver(search_range)

    gui = Gui(polynomial, search_range)
    # benchmark = Benchmark([brute_force_solver, genetic_algorithm_solver])
    benchmark = Benchmark([genetic_algorithm_solver])

    # Benchmark
    benchmark.evaluate(polynomial)

    # Visualize Solvers
    # gui.create_animation(brute_force_solver)
    animation = gui.create_animation(genetic_algorithm_solver)

    # Create Default Visual
    # gui.plot_problem()
    gui.show()
Exemple #2
0
 def setUp(self):
     from gui.gui import Gui
     self.gui = Gui()
     self.panel = self.gui.create(Panel)
     self.panel.rect = Rect(50, 80, 100, 120)
     self.panel.padding = Rect(2, 3, 5, 11)
     self.panel.margins = Rect(17, 23, 29, 37)
     self.panel.layout_dirty = False
     self.gui.world.layout_dirty = False
Exemple #3
0
    def __init__(self):
        self._detect = GPIODetect(self.gpio_detect)
        self._detect.setup()
        self._detect.detct()
        self._sysInfo.setcommCallback(self.get_system_info)
        # DBG("Welcome to Controller!")
        self._scannerble = ScannerBLE(self.scanner_comm, "hci0")

        self._gui = Gui(self.gui_comm)
        # 注册信号处理函数
        self._thread.signal.connect(self.update_ui)
        self._thread.start()
        self._gui.start_gui()
Exemple #4
0
def start_gui():
    board = GuiBoard(9, 9)
    strategy = Strategy()
    p1 = GuiHuman('x', board)
    p2 = Computer('0', board, strategy)
    game = GuiGame(p1, p2, board)
    root = tkinter.Tk()
    my_gui = Gui(root, game)
    root.mainloop()
Exemple #5
0
    def __init__(self):
        # register signal handler
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        # flag for activity before quit
        self.is_running = True
        self.is_sig = False

        # user's attributes
        self.nick = None
        self.ip = None
        self.port = None

        # create Hnefatafl
        self.hnef = Hnefatafl()

        # create client network
        self.net = Network(self)

        # create gui
        self.gui = Gui(self)
Exemple #6
0
def main():
    while True:
        gui = Gui()
        game = Game(gui)
        gui.player_bet.destroy()
        for widget in gui.player_info_frame.winfo_children():
            widget.destroy()
        new_round = messagebox.askquestion("New game?")
        if new_round == "no":
            gui.root.destroy()
            break
        else:
            gui.root.destroy()
    return
Exemple #7
0
def main():
    os.environ.setdefault("INFERENCE_SETTINGS_MODULE", "settings")
    arg_list = ["read", "test"]
    parser = argparse.ArgumentParser(prog="manage.py", description="Inference:\
            a tool to infer missing data from its context")
    parser.add_argument("-i", "--data", help="File name of the data file stored in data/",
            type=str, action="store", default=False)
    parser.add_argument("-u", "--upload", help="Add this to upload data through the gui",
            action="store_true")
    parser.add_argument("-t", "--test", help="Runs all tests. For develpment use only", 
            action="store_true")
    args = parser.parse_args()
    if not args.data and args.upload:
        # start gui uploader
        root = tk.Tk()
        root.title("Iference")
        root.geometry('500x500')
        gui = Gui(master=root)
        gui.mainloop()
    if args.data:
        # start some work with the data
        data = Data(args.data)
        data.load_data()
Exemple #8
0
def testNetwork(inputCount, hiddensCount, outputCount, patterns, initSetup=None, cycles=1000, learnRate=0.9, momentumRate=0.4, activationFn=fnSigmoid(1), stopEarly=False, gui=False, metadata=defaultMetadata):
    """ Tests a network based on the number of nodes provided and the test patterns.

    Does nothing if succeeds, else prints failure string.

    inputCount -- number of input nodes
    hiddensCount -- list of number of hidden nodes for respective layers
    outputCount -- number of output nodes
    initSetup -- initial node weights / biases (default None, random) e.g. ([[[input1hiddens], [input2hiddens] ...], [[hidden1outputs], [hidden2outputs] ...]], [[hidden1biases], [hidden2biases], ... [outputbiases]])
    patterns -- training patterns ([inputs], [expected outputs], [conditions], [failure string])
    cycles -- number of epochs to train for (default 10)
    learnRate -- rate of learning (default 0.9)
    momentumRate -- weight of previous deltas (default 0.4)
    activationFn -- activation function for neurons (default fnSigmoid(1))
    stopEarly -- stop when all patterns succeed (default False)
    gui -- boolean for gui testing (default False)
    metadata -- TestMetadata object (default None)
    """
    net = makeNetwork(inputCount, hiddensCount, outputCount, initSetup, activationFn)
    
    for cycle in range(1, cycles + 1):
        if gui:
            Gui.drawNetwork(net, title=metadata.testName)
        if net.train(patterns, learnRate, momentumRate, stopEarly):
            break
        
    # Testing
    for (inputStates, _, conds, failureString) in patterns:
        for (s, i) in zip(inputStates, net.getInputNodes()):
            i.setState(s)
        net.fireAll()
        print("Input " + str(inputStates) +", Output " + str(net.getOutputNodes()[0].state))
        for (out, cond) in zip(map(lambda o: o.state, net.getOutputNodes()), conds):
            if not testResult(cond(out), failureString):
                return
    print("Passed after {0} cycles".format(cycle))
Exemple #9
0
'''
BLACK-AND-WHITE
WinterSalmon
Main
'''

from gui.gui import Gui
from cli.cli import Cli

if __name__ == "__main__":
    # if pygame is not installed run game in commandline mode
    try:
        UI = Gui()
    except ImportError:
        UI = Cli()
    UI.init_screen()
    UI.game_screen()
    UI.credit_screen()
Exemple #10
0
def run_benchmark(root_folder, times, feasible_ranges, polynomial=None):
    if not os.path.exists(root_folder):
        log.info('Creating Folder')
        os.makedirs(root_folder)

    # Create Problem
    if not polynomial:
        polynomial = Polynomial(num_terms=5, num_dimensions=2)

    log.info(polynomial)

    for feasible_range in feasible_ranges:
        search_range = SearchRange()
        search_range.set_feasible_range(feasible_range, 2)
        folder = os.path.join(root_folder,
                              'feasible_range_{}'.format(feasible_range))
        solution_payload = {}

        if not os.path.exists(folder):
            os.mkdir(folder)

        for i in range(times):
            # Create Folder
            run_folder = os.path.join(folder, 'run_{}'.format(i))

            if not os.path.exists(run_folder):
                os.mkdir(run_folder)

                # Solvers
                brute_force_solver = BruteForceSolver(search_range)
                genetic_algorithm_solver = GeneticAlgorithmSolver(search_range)

                solvers = [brute_force_solver, genetic_algorithm_solver]

                # Benchmark
                benchmark = Benchmark(solvers)
                benchmark.evaluate(polynomial)

                # Add to Benchmark
                for solver in solvers:
                    metric = benchmark.get_metrics(solver._id)
                    add_to_benchmark_payload(solution_payload, solver, metric)

                # Save Animations
                gui = Gui(polynomial, search_range)
                genetic_animation = gui.create_animation(
                    genetic_algorithm_solver)
                genetic_animation.save(os.path.join(run_folder, 'genetic.gif'),
                                       writer='imagemagick',
                                       fps=30)

                brute_animation = gui.create_animation(brute_force_solver)
                brute_animation.save(os.path.join(run_folder, 'brute.gif'),
                                     writer='imagemagick',
                                     fps=30)

                # Save Problem
                figure, plot = gui.plot_problem()
                figure.savefig(os.path.join(run_folder, 'problem.png'))

                # Pickle benchmark && solvers && polynomial
                pickle_object(
                    genetic_algorithm_solver,
                    os.path.join(run_folder, 'genetic_solver.pickle'))
                pickle_object(brute_force_solver,
                              os.path.join(run_folder, 'brute_solver.pickle'))
                pickle_object(benchmark,
                              os.path.join(run_folder, 'brute_solver.pickle'))
                pickle_object(gui, os.path.join(run_folder, 'gui.pickle'))

                # Clear Matplotlib figures
                gui.close()

            pickle_object(solution_payload,
                          os.path.join(folder, 'benchmark.pickle'))
from gui.threadgui import ThreadGui
from camera.camera import Camera
from camera.threadcamera import ThreadCamera
from detector.detector import Detector
from detector.threaddetector import ThreadDetector
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

if __name__ == '__main__':

    camera = Camera()
    print(camera)

    app = QtGui.QApplication(sys.argv)
    window = Gui(camera)

    detector = Detector(camera, window)
    print(detector)

    t_cam = ThreadCamera(camera)
    t_cam.start()

    t_detector = ThreadDetector(detector)
    t_detector.start()

    window.setCamera(camera, t_cam)
    window.show()
    window.setDetector(detector, t_detector)
    window.show()
Exemple #12
0
def main(stdscr):
    from gui.gui import Gui
    log.init()
    Gui(stdscr)
Exemple #13
0
def main():

    ui = Gui()
    ui.mainloop()
from gui.threadgui import ThreadGui
from camera.camera import Camera
from camera.threadcamera import ThreadCamera
from detector.detector import Detector
from detector.threaddetector import ThreadDetector
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

if __name__ == '__main__':

    camera = Camera()
    print(camera)

    app = QtGui.QApplication(sys.argv)
    window = Gui(camera)

    detector = Detector(camera, window)
    print(detector)

    t_cam = ThreadCamera(camera)
    t_cam.start()

    t_detector = ThreadDetector(detector)
    t_detector.start()

    window.setCamera(camera, t_cam)
    window.show()
    window.setDetector(detector, t_detector)
    window.show()
Exemple #15
0
class Controller:

    _scannerble = None
    _gui = None
    conn = None
    array_full = []
    # 创建线程
    _thread = UIThread()
    _sysInfo = GetSysInfo()
    _detect = None

    def __init__(self):
        self._detect = GPIODetect(self.gpio_detect)
        self._detect.setup()
        self._detect.detct()
        self._sysInfo.setcommCallback(self.get_system_info)
        # DBG("Welcome to Controller!")
        self._scannerble = ScannerBLE(self.scanner_comm, "hci0")

        self._gui = Gui(self.gui_comm)
        # 注册信号处理函数
        self._thread.signal.connect(self.update_ui)
        self._thread.start()
        self._gui.start_gui()

    def beacon_comm(self, msg):
        # DBG("Welcome to beacon_comm!")
        if msg.get_type() is IntMessage.BEACON_DATA_ERROR:  # pass input error back to GUI
            self._gui.comm(IntMessage(IntMessage.ALERT_GUI, {'ALERT_TEXT': "Your input is not correct!",
                                                             'ALERT_DETAIL': msg.get_payload()['ERROR']}))

    def gui_comm(self, msg):
        if not isinstance(msg, IntMessage):
            raise Exception("Message has to be an IntMessage")
        msg_type = msg.get_type()
        # start different beacon standards
        if msg_type is IntMessage.START_SCAN_BLE:
            self._scannerble.scan()
        elif msg_type is IntMessage.STOP_SCAN_BLE:
            DBG('Stopped BLE Scan')
            self._scannerble.stop_scan()
        elif msg_type is IntMessage.GETSYSINFO:
            self._sysInfo.detct()
        elif msg_type is IntMessage.STOPGETSYSINFO:
            self._sysInfo.cleanup()
        elif msg_type is IntMessage.QUITAPP:
            self._sysInfo.cleanup()
            self._scannerble.stop_scan()
            self._detect.cleanup()

    @staticmethod
    def scanner_comm(msg):
        dic = {'type': int(msg.get_type()), 'pyload': str(msg.get_payload())}
        g_data_queue.put(json.dumps(dic))

    def update_ui(self, msg):
        dic = json.loads(msg)
        self._gui.comm(IntMessage(dic['type'],  eval(dic['pyload'])))

    @staticmethod
    def gpio_detect(msg):
        dic = {'type': msg, 'pyload': '{}'}
        # msg1 = IntMessage(IntMessage.SCANNED_IBEACON,
        #                   {'UUID': '111', 'MAJOR': '333', 'MINOR': '444', 'TX': '5555', 'RSSI': '6666',
        #                    'time': time.time()})
        # dic = {'type': int(msg1.get_type()), 'pyload': str(msg1.get_payload())}
        g_data_queue.put(json.dumps(dic))

    @staticmethod
    def get_system_info(msg):
        DBG('get_system_info')
        dic = {'type': int(msg.get_type()), 'pyload': str(msg.get_payload())}
        g_data_queue.put(json.dumps(dic))

    @staticmethod
    def dummy_fun(msg):
        DBG(msg)
Exemple #16
0
class Application:
    def __init__(self):
        # register signal handler
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)

        # flag for activity before quit
        self.is_running = True
        self.is_sig = False

        # user's attributes
        self.nick = None
        self.ip = None
        self.port = None

        # create Hnefatafl
        self.hnef = Hnefatafl()

        # create client network
        self.net = Network(self)

        # create gui
        self.gui = Gui(self)

    def _signal_handler(self, sig, frame):
        self.is_running = False
        self.is_sig = True
        self.gui.destroy()
        logger.info("Closing client with signal.")

    def run(self):
        # start network
        self.net.start()

        # start the application -- has to be last command,
        # because it runs, until the window is closed == everything else freezes
        self.gui.mainloop()

        # if windows was closed with button or cross, set flag in standard way
        self.is_running = False

        if not self.is_sig:
            logger.info("Closing client standard way.")

        # notify network thread, in order to end it
        with self.net.cv:
            self.net.cv.notify()
        # join Network thread
        self.net.join()

        # print statistics through lifetime
        self.net.pr_statistics()

    def hnef_connect(self, nick, ip, port):
        self.nick = nick
        self.ip = "127.0.0.1" if ip == "localhost" else ip
        self.port = int(port)

        # connect to server
        self.net.connect(self.nick, self.ip, self.port)

    def gui_connected(self):
        self.gui.make_connected()

    def gui_disconnected(self):
        self.gui.make_disconnected()

    def send_to_server(self, code, value=None):
        self.net.send_msg(code, value)

    def send_to_chat(self, msg, bot):
        self.gui.chat_msg_server(msg, bot, self.hnef.nick_opponent)

    def send_to_menu(self, msg):
        self.gui.set_state(msg)

    def is_in_game(self):
        # True, if somebody is on turn -- means game is on
        return self.hnef.on_turn is not None

    def start_game(self, turn, opn_name):
        # start new game in Hnefatafl class
        self.hnef.new_game(turn, opn_name)
        # switch frame in GUI, so user can play
        self.gui.new_game(self.nick, self.hnef.game_state, self.hnef.pf, self.hnef.allowed_squares)
        # tell player, who is on turn
        self.send_to_chat("'{}' is black and on turn.".format(self.nick if turn else opn_name), bot=True)

    def leave_game(self):
        self.send_to_server(protocol.CC_LEAV)
        self.hnef.quit_game()

    def reset_game(self, turn, nick_opn, pf):
        # reset game in Hnefatafl class
        self.hnef.reset_game(turn, nick_opn, pf)
        # not actually new game -- it has state like in received message from server
        self.gui.new_game(self.nick, self.hnef.game_state, self.hnef.pf, self.hnef.allowed_squares)

    def quit_game(self, result):
        # quit game after game-over
        self.hnef.quit_game()
        self.gui.quit_game(result)

    def handle_click(self, x_pos, y_pos):
        redraw = True

        # playfield have not been clicked
        if self.hnef.game_state == Click.THINKING:
            # find fields where player may move after click on stone
            self.hnef.find_placeable_fields(x_pos, y_pos)

            # set position, which is being moved from
            self.hnef.x_from = x_pos
            self.hnef.y_from = y_pos
            # change state to clicked
            self.hnef.game_state = Click.CLICKED

        # playfield have been clicked
        elif self.hnef.game_state == Click.CLICKED:
            # field without stone have been clicked -- make a move
            if self.hnef.is_field(x_pos, y_pos):
                # send move message to server
                move = self.compose_move_msg([self.hnef.x_from, self.hnef.y_from, x_pos, y_pos])
                self.send_to_server(protocol.CC_MOVE, value=move)

                # save also position which is being moved to and move after server's confirmation of valid move
                self.hnef.x_to = x_pos
                self.hnef.y_to = y_pos

                # playfield is updated and redrawn after server's MOVE_VALID message
                redraw = False

            # field with same stone have been clicked -- go back to thinking state
            elif self.hnef.is_same_stone(x_pos, y_pos):
                # find stones, which player can move with
                self.hnef.find_movables_stones()

                # reset position, which is being moved from
                self.hnef.x_from = None
                self.hnef.y_from = None
                # change state to thinking
                self.hnef.game_state = Click.THINKING

            # field with other stone have been clicked -- find allowed squares again
            else:
                # find stones, which player can move with
                self.hnef.find_movables_stones()
                # find fields where player may move after click on stone
                self.hnef.find_placeable_fields(x_pos, y_pos)

                # set position, which is being moved from
                self.hnef.x_from = x_pos
                self.hnef.y_from = y_pos

        # update playfield in gui
        if redraw:
            self.gui.pf_update(self.hnef.game_state, self.hnef.pf, self.hnef.allowed_squares)

    def move_self(self):
        # move chosen stone (after server confirmation -- so use cached values)
        self.hnef.move(self.hnef.x_from, self.hnef.y_from, self.hnef.x_to, self.hnef.y_to)
        # check captures of local player -- capturing white if local is black
        self.hnef.check_captures(self.hnef.is_surrounded_white if self.hnef.black else self.hnef.is_surrounded_black)
        # after move, player cannot move anything
        self.hnef.allowed_squares.clear()

        # update playfield in gui
        self.gui.pf_update(self.hnef.game_state, self.hnef.pf, self.hnef.allowed_squares)

    def move_opponent(self, x_from, y_from, x_to, y_to):
        # move opponent's piece
        self.hnef.move(x_from, y_from, x_to, y_to)
        # check captures of opponent player -- capturing black if local is black
        self.hnef.check_captures(self.hnef.is_surrounded_black if self.hnef.black else self.hnef.is_surrounded_white)
        # get pieces of player, who is on turn now
        self.hnef.find_movables_stones()

        # update playfield in gui
        self.gui.pf_update(self.hnef.game_state, self.hnef.pf, self.hnef.allowed_squares)

    def compose_move_msg(self, coordinates):
        move = ""

        for coor in coordinates:
            # if number has only one place, so append 0 at beginning according to protocol
            # else it is 10 with two places
            move += "0" + str(coor) if coor < 10 else str(coor)

        return move
Exemple #17
0
import PySimpleGUI as sg
import traceback
import sys

from common.handleconfig import HandleConfig
from gui.gui import Gui

Version = '4.6'

if len(sys.argv) <= 1:
    # normal start, run with a gui
    # cmd:python D:\Projects\ExcelToDatabase\main.py
    # exe:ExcelToDatabase.exe
    sg.ChangeLookAndFeel('dark')
    HandleConfig = HandleConfig()
    Gui = Gui()

    def exception_format():
        # format exception output
        return "".join(
            traceback.format_exception(sys.exc_info()[0],
                                       sys.exc_info()[1],
                                       sys.exc_info()[2],
                                       limit=-1))

    default_values = HandleConfig.get_defaults()
    window = sg.Window('ExcelToDatabase {0}'.format(Version),
                       Gui.generate_layout(),
                       location=(700, 50))

    while True:
Exemple #18
0
import sys
import argparse

from PyQt5.QtWidgets import QApplication
from gui.gui import Gui

app = QApplication(sys.argv)
app.setOrganizationDomain('rahmedov.com')
app.setObjectName('rahmedov')
app.setApplicationName('rahmedov')
app.setApplicationVersion('0.0.0')

parser = argparse.ArgumentParser(description='Home')
parser.add_argument('-r', '--root', type=str, default='', help='''Root Path''')

args = parser.parse_args()

g = Gui(root=args.root, parent=None)

g.show()
sys.exit(app.exec_())
Exemple #19
0
    await run_tk(root)


if __name__ == "__main__":
    data = Data([150, 41], [540, 386])
    # address = "A6C01837-C772-4ED8-9984-5A006FA27336"
    # address = "0880E3E7-E6A4-4367-A655-9C6E130303A9"
    address = "C0:98:E5:49:00:00"

    parser = argparse.ArgumentParser()
    parser.add_argument('--thread', action='store_true', default=False)
    parser.add_argument('--ble_debug', action='store_true', default=False)
    parser.add_argument('--gui_debug', action='store_true', default=False)
    args = parser.parse_args()

    root = Gui(data, args.gui_debug)
    ble_comm = BleComm(address)

    if not args.thread:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main_async(root, ble_comm, args.ble_debug))

    else:
        cv_client = CV_Detector(data)
        t1 = Thread(target=cv_client.run_cv)
        t1.setDaemon(True)
        t1.start()

        loop = asyncio.get_event_loop()
        loop.run_until_complete(main_async(root, ble_comm, args.ble_debug))
        t1.join()
import sys
from PyQt4 import QtGui
from gui.gui import Gui
from gui.threadgui import ThreadGui
from control.control import Control
from control.threadcontrol import ThreadControl
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

if __name__ == '__main__':

    control = Control()

    app = QtGui.QApplication(sys.argv)
    print 'app creada'
    window = Gui()
    window.setControl(control)
    window.show()
    print 'window'

    t1 = ThreadControl(control)
    t1.start()
    print 'threadcontrol'

    t2 = ThreadGui(window)
    t2.start()
    print 'threadgui'

    sys.exit(app.exec_())
Exemple #21
0
class PanelTest(unittest.TestCase):
    def setUp(self):
        from gui.gui import Gui
        self.gui = Gui()
        self.panel = self.gui.create(Panel)
        self.panel.rect = Rect(50, 80, 100, 120)
        self.panel.padding = Rect(2, 3, 5, 11)
        self.panel.margins = Rect(17, 23, 29, 37)
        self.panel.layout_dirty = False
        self.gui.world.layout_dirty = False

    def test_rect(self):
        self.assertEqual(Rect(50, 80, 100, 120), self.panel.rect)

        rect = Rect(11, 22, 33, 44)
        self.panel.rect = rect.as_tuple()
        self.assertEqual(rect, self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.rect = rect
        self.assertFalse(self.panel.layout_dirty)
        self.panel.rect = rect.as_tuple()
        self.assertFalse(self.panel.layout_dirty)

    def test_padding(self):
        self.assertEqual(Rect(2, 3, 5, 11), self.panel.padding)

        rect = Rect(11, 22, 33, 44)
        self.panel.padding = rect.as_tuple()
        self.assertEqual(rect, self.panel.padding)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.padding = rect
        self.assertFalse(self.panel.layout_dirty)

    def test_margins(self):
        self.assertEqual(Rect(17, 23, 29, 37), self.panel.margins)

        rect = Rect(11, 22, 33, 44)
        self.panel.margins = rect.as_tuple()
        self.assertEqual(rect, self.panel.margins)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.margins = rect
        self.assertFalse(self.panel.layout_dirty)

    def test_inner(self):
        self.assertEqual(Rect(52, 83, 93, 106), self.panel.rect_inner)

        rect = Rect(22, 33, 44, 55)
        self.panel.rect_inner = rect
        self.assertEqual(rect, self.panel.rect_inner)
        self.assertEqual(Rect(20, 30, 51, 69), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.rect_inner = rect
        self.assertFalse(self.panel.layout_dirty)

    def test_outer(self):
        self.assertEqual(Rect(33, 57, 146, 180), self.panel.rect_outer)

        rect = Rect(55, 66, 77, 88)
        self.panel.rect_outer = rect
        self.assertEqual(rect, self.panel.rect_outer)
        self.assertEqual(Rect(72, 89, 31, 28), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.rect_outer = rect
        self.assertFalse(self.panel.layout_dirty)

    def test_x(self):
        self.assertEqual(50, self.panel.x)
        self.panel.x = 127
        self.assertEqual(Rect(127, 80, 100, 120), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.x = 127
        self.assertFalse(self.panel.layout_dirty)

    def test_y(self):
        self.assertEqual(80, self.panel.y)
        self.panel.y = 127
        self.assertEqual(Rect(50, 127, 100, 120), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.y = 127
        self.assertFalse(self.panel.layout_dirty)

    def test_width(self):
        self.assertEqual(100, self.panel.width)
        self.panel.width = 127
        self.assertEqual(Rect(50, 80, 127, 120), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.width = 127
        self.assertFalse(self.panel.layout_dirty)

    def test_height(self):
        self.assertEqual(120, self.panel.height)
        self.panel.height = 127
        self.assertEqual(Rect(50, 80, 100, 127), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.height = 127
        self.assertFalse(self.panel.layout_dirty)

    def test_pos(self):
        self.assertEqual((50, 80), self.panel.pos)
        self.panel.pos = (127, 99)
        self.assertEqual(Rect(127, 99, 100, 120), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.pos = (127, 99)
        self.assertFalse(self.panel.layout_dirty)

    def test_size(self):
        self.assertEqual((100, 120), self.panel.size)
        self.panel.size = (127, 99)
        self.assertEqual(Rect(50, 80, 127, 99), self.panel.rect)
        self.assertTrue(self.panel.layout_dirty)

        self.panel.layout_dirty = False
        self.panel.size = (127, 99)
        self.assertFalse(self.panel.layout_dirty)

    def test_parent(self):
        self.assertIs(self.gui.world, self.panel.parent)
        self.panel.parent = self.gui.world
        self.assertFalse(self.panel.layout_dirty)

        parent = self.gui.create(Panel)
        self.assertTrue(self.gui.world.layout_dirty)
        self.gui.world.layout_dirty = False

        self.panel.parent = parent
        self.assertNotIn(self.panel, self.gui.world.children)
        self.assertIn(self.panel, parent.children)
        self.assertTrue(self.panel.layout_dirty)
        self.assertTrue(parent.layout_dirty)
        self.assertTrue(self.gui.world.layout_dirty)

    def test_request_layout(self):
        self.assertFalse(self.panel.layout_dirty)
        self.assertFalse(self.gui.world.layout_dirty)
        self.panel.request_layout()
        self.assertTrue(self.panel.layout_dirty)
        self.assertTrue(self.gui.world.layout_dirty)
Exemple #22
0
from gui.gui import Gui

if __name__ == '__main__':
    app = Gui()
    app.mainloop()
Exemple #23
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--p0-agent",
        type=str,
        choices=['static', 'rule', 'random', 'alphasheep', 'user'],
        required=True)
    parser.add_argument(
        "--alphasheep-checkpoint",
        help="Checkpoint for AlphaSheep, if --p0-agent=alphasheep.",
        required=False)
    parser.add_argument(
        "--agent-config",
        help="YAML file, containing agent specifications for AlphaSheep.",
        required=False)
    args = parser.parse_args()
    agent_choice = args.p0_agent
    as_checkpoint_path = args.alphasheep_checkpoint
    as_config_path = args.agent_config
    if agent_choice == "alphasheep" and (not as_checkpoint_path
                                         or not as_config_path):
        raise ValueError(
            "Need to specify --alphasheep-checkpoint and --agent-config if --p0_agent=alphasheep."
        )

    # Init logging and adjust log levels for some classes.
    init_logging()
    logger = get_named_logger("{}.main".format(
        os.path.splitext(os.path.basename(__file__))[0]))
    get_class_logger(GameController).setLevel(
        logging.DEBUG)  # Log every single card.
    get_class_logger(Gui).setLevel(logging.DEBUG)  # Log mouse clicks.
    get_class_logger(RuleBasedAgent).setLevel(
        logging.DEBUG)  # Log decisions by the rule-based players.

    # Create the agent for Player 0.
    if agent_choice == "alphasheep":

        # Load config. We ignore the "training" and "experiment" sections, but we need "agent_config".
        logger.info(f'Loading config from "{as_config_path}"...')
        config = load_config(as_config_path)
        get_class_logger(DQNAgent).setLevel(logging.DEBUG)  # Log Q-values.
        alphasheep_agent = DQNAgent(0, config=config, training=False)
        alphasheep_agent.load_weights(as_checkpoint_path)
        p0 = Player("0-AlphaSheep", agent=alphasheep_agent)
    elif agent_choice == "user":
        p0 = Player("0-User", agent=GUIAgent(0))
    elif agent_choice == "rule":
        p0 = Player("0-Hans", agent=RuleBasedAgent(0))
    elif agent_choice == "static":
        p0 = Player("0-Static", agent=StaticPolicyAgent(0))
    else:
        p0 = Player("0-RandomGuy", agent=RandomCardAgent(0))

    # Players 1-3 are RuleBasedAgents.
    players = [
        p0,
        Player("1-Zenzi", agent=RuleBasedAgent(1)),
        Player("2-Franz", agent=RuleBasedAgent(2)),
        Player("3-Andal", agent=RuleBasedAgent(3))
    ]

    # Rig the game so Player 0 has the cards to play a Herz-Solo.
    # Also, force them to play it.
    game_mode = GameMode(GameContract.suit_solo,
                         trump_suit=Suit.herz,
                         declaring_player_id=0)
    controller = GameController(players,
                                dealing_behavior=DealWinnableHand(game_mode),
                                forced_game_mode=game_mode)

    # The GUI initializes PyGame and registers on events provided by the controller. Everything single-threaded.
    #
    # The controller runs the game as usual. Whenever the GUI receives an event, it can block execution, so the controller must wait
    # for the GUI to return control. Until then, it can draw stuff and wait for user input (mouse clicks, card choices, ...).
    logger.info("Starting GUI.")
    with Gui(controller.game_state) as gui:
        # Run an endless loop of single games.
        logger.info("Starting game loop...")
        try:
            while True:
                controller.run_game()
        except UserQuitGameException:  # Closing the window or pressing [Esc]
            logger.info("User quit game.")

    logger.info("Shutdown.")
Exemple #24
0
import sys
from PyQt4 import QtGui
from gui.gui import Gui
from gui.threadgui import ThreadGui
from camera.camera import Camera
from camera.threadcamera import ThreadCamera
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

if __name__ == '__main__':

    camera = Camera()
    print(camera)
    app = QtGui.QApplication(sys.argv)
    window = Gui()
    window.setCamera(camera)
    window.show()

    t1 = ThreadCamera(camera)
    t1.start()

    t2 = ThreadGui(window)
    t2.start()

    sys.exit(app.exec_())
Exemple #25
0
    parser.add_argument("-s",
                        "--speed",
                        type=float,
                        help="simulation speed, default = 1",
                        default=1)
    parser.add_argument("--fps",
                        help="frames per second, default=30",
                        type=int,
                        default=30)
    args = parser.parse_args()
    pygame.init()
    speed = args.speed
    fps = args.fps
    parameters = SimulationParameters()
    world = World(parameters.options["world_pixel_size"],
                  parameters.options["world_nrof_tiles"])
    creature_manager = CreatureManager(parameters.options["nrof_creatures"],
                                       world)
    statistics = Statistics(creature_manager)
    clock = pygame.time.Clock()
    gui = Gui(1000, 600, creature_manager, world, clock, statistics, speed)
    main_loop()
    #cProfile.run("main_loop()")
"""
TODO: Implement Pause function
TODO: Implement Neural Network Viewer
TODO: Partial Screen udpates
TODO: Collect all variables/constants and make them be changeable by parameter or a file
TODO: Creature vision viewer
TODO: Something about the borders
"""