Ejemplo n.º 1
0
    def __init__(self, rcg: ResourceConsumerGame,
                 callback_outgoing_queue_func):
        self.rcg = rcg
        self.callback_outgoing = callback_outgoing_queue_func

        self.input_handler = InputHandler()

        pygame.init()

        # set up window
        self.window_size = (1000, 750)
        self.clock = pygame.time.Clock()

        self.screen = pygame.display.set_mode(self.window_size)
        self.screen.fill((0, 100, 100))  # base colour
        pygame.display.set_caption("resource consumer screen")

        # set up surfaces
        self.bg_surface = pygame.Surface(self.window_size)
        self.machine_surface = pygame.Surface(
            self.window_size, pygame.SRCALPHA)  # per pixel alpha
        self.hud_surface = pygame.Surface(self.window_size,
                                          pygame.SRCALPHA)  # per pixel alpha
        self.selection_surface = pygame.Surface(
            self.window_size, pygame.SRCALPHA)  # per pixel alpha

        # set up GUI and placements
        self.gui = RCScreenGUI(self.rcg, self.set_selected_machine)
        self.selected_machine = None  # used for the gui to callback to
        self.selected_rotation = 0

        # set up selection
        self.selection = {"down": [None, None], "cur": [None, None]}

        # zoom and camera position limits and speeds
        self.tile_size_min = 10
        self.tile_size_max = 75
        self.offsets_max = (1000, 1000)  # (x, y) pairs or (h, v) pairs
        self.offsets_min = (-1000, -1000)  # (x, y) pairs or (h, v) pairs
        # can be changed to be smooth/have acceleration
        self.offset_move_speed = 10  # n pixels change per frame
        self.tile_size_zoom_speed = 2  # n pixels change per frame

        # set up base zoom and camera position
        self.tile_size = 50
        self.offsets = [0, 0]

        # run flag for main
        self.run = False

        self.background_draw_handler = BackgroundDrawHandler2(
            self.rcg.game_map.size, self.rcg.game_map.background_map,
            self.rcg.game_map.background_addition_map,
            (self.tile_size, self.tile_size))
        self.machine_draw_handler = MachineDrawHandler2(
            self.rcg.placed_objects, (self.tile_size, self.tile_size))
        self.selection_draw_handler = SelectionDrawHandler(
            (self.tile_size, self.tile_size))
        self.block_hologram_draw_handler = MachineHologramDrawHandler(
            (self.tile_size, self.tile_size))
Ejemplo n.º 2
0
def main():
    verbose = verbose_mode(sys.argv)
    input_handler = InputHandler()
    output_handler = OutputHandler("results.txt")

    [memory_blocks, references] = input_handler.parse_file(sys.argv[1])

    fifo = FIFO(copy.deepcopy(memory_blocks), copy.deepcopy(references))
    fifo_stats = fifo.run()
    fifo_stats_str = get_stats_str("FIFO", fifo_stats)

    otm = OTM(copy.deepcopy(memory_blocks), copy.deepcopy(references))
    otm_stats = otm.run()
    otm_stats_str = get_stats_str("OTM", otm_stats)

    lru = LRU(copy.deepcopy(memory_blocks), copy.deepcopy(references))
    lru_stats = lru.run()
    lru_stats_str = get_stats_str("LRU", lru_stats)

    output_handler.write_to_file(fifo_stats_str, otm_stats_str, lru_stats_str)

    if verbose:
        print(fifo_stats_str, end="")
        print(otm_stats_str, end="")
        print(lru_stats_str)
Ejemplo n.º 3
0
def main():
    inputHandler = InputHandler()
    #inputHandler.TicTacToe('./dataset/tic-tac-toe/tic-tac-toe.data')
    #inputHandler.ionosphere('./dataset/ionosphere/ionosphere.data')
    inputHandler.creditScreening('./dataset/credit-screening/crx.data')

    pass
    def connectionLoop(cls, clientSocket):
        """Create the loop that handles the connection and communication after
         connection is established

        Parameters:
        argument1 (socket): The cliente socket

        Returns:
        void

        """
        while True:
            try:
                ClientScreenPrinter.menu()
                requestMessage = InputHandler.handleOption(
                    InputHandler.getOption())
                encodedRequestMessage = str.encode(json.dumps(requestMessage))
                clientSocket.send(encodedRequestMessage)

                # object can be big depending on number of words!
                receivedObj = clientSocket.recv(50000)
                if not receivedObj:
                    ClientScreenPrinter.handleError()
                    raise Exception("Lost connection to server. Shutting down")

                else:
                    loadedData = json.loads(receivedObj)

                    ClientScreenPrinter.handleServerAnswer(
                        loadedData, requestMessage['numToAnalize'])
            except Exception as e:
                exit(0)
Ejemplo n.º 5
0
    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

        self.map1 = '../game_states/game1_cake.json'
        self.game_state1 = GameState(self.map1)
        self.ih1 = InputHandler(self.game_state1)
Ejemplo n.º 6
0
    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

        self.map_two_helmets = '../game_states/game_two_helmets.json'
        self.game_two_helmets = GameState(self.map_two_helmets)
        self.ih_two_helmets = InputHandler(self.game_two_helmets)
Ejemplo n.º 7
0
 def __init__(self) -> None:
     self.inputHandler = InputHandler()
     self.board = Board(size=Vector2(BOARD_WIDTH, BOARD_HEIGHT))
     self.brickHandler = BrickHandler(self.board)
     self.paddle = None
     self.balls = []
     self.powerUps = []
     self.activePowerUps = []
     self.score = 0
     self.lives = 5
     self.isRunning = True
Ejemplo n.º 8
0
class SceneFrame(QWidget):
    def __init__(self, frame, scene):
        super(SceneFrame, self).__init__(frame)

        self.setObjectName("sceneFrame_int")
        frame.layout().addWidget(self)
        # topLeft = frame.mapToParent(QPoint(0, 0))
        # self.viewport = QRect(topLeft.x(), topLeft.y(),
        #                      frame.width(), frame.height())
        self.frame = frame
        self.scene = scene
        self.setFocusPolicy(Qt.StrongFocus)
        self.scene.set_background_brush(QBrush(QColor(100, 100, 100)))
        self.inputHandler = InputHandler()
        self.viewport = QRect(0, 0, self.frame.width(), self.frame.height())
        return

    def get_scene(self):
        return self.scene

    def get_root_node(self):
        return self.scene.get_root_node()

    def get_input(self):
        return self.inputHandler

    def set_input(self, inputHandler):
        self.inputHandler = inputHandler

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setViewport(self.viewport)
        painter.setWindow(
            QRect(0, 0, self.scene.get_width(), self.scene.get_height()))
        painter.setViewTransformEnabled(True)
        self.scene.draw(painter)
        return

    def keyPressEvent(self, event):
        super(SceneFrame, self).keyPressEvent(event)
        key = event.key()
        self.inputHandler.on_key_pressed(key)

    def keyReleaseEvent(self, event):
        super(SceneFrame, self).keyPressEvent(event)
        key = event.key()
        self.inputHandler.on_key_released(key)

    def resizeEvent(self, event):
        # topLeft = self.frame.mapToParent(QPoint(0, 0))
        self.viewport = QRect(0, 0, self.frame.width(), self.frame.height())
        return
Ejemplo n.º 9
0
class Chat:
    def __init__(self, credentials, serverWrapper):
        clientStateInfo = ClientStateInfo(credentials, GENERAL_CHATROOM)
        self.messageUpdater = MessageUpdater(serverWrapper, clientStateInfo,
                                             self)
        self.inputHandler = InputHandler(serverWrapper, clientStateInfo, self)

    def run(self):
        self.messageUpdater.run()
        self.inputHandler.run()

    def quit(self):
        self.messageUpdater.quit()
        self.inputHandler.quit()
Ejemplo n.º 10
0
    def __init__(self, frame, scene):
        super(SceneFrame, self).__init__(frame)

        self.setObjectName("sceneFrame_int")
        frame.layout().addWidget(self)
        # topLeft = frame.mapToParent(QPoint(0, 0))
        # self.viewport = QRect(topLeft.x(), topLeft.y(),
        #                      frame.width(), frame.height())
        self.frame = frame
        self.scene = scene
        self.setFocusPolicy(Qt.StrongFocus)
        self.scene.set_background_brush(QBrush(QColor(100, 100, 100)))
        self.inputHandler = InputHandler()
        self.viewport = QRect(0, 0, self.frame.width(), self.frame.height())
        return
Ejemplo n.º 11
0
    def __init__(self, root):
        # Window Size Variables
        self.WIDTH, self.HEIGHT = (800, 600)
        self.root = root

        self.root.geometry(str(self.WIDTH) + "x" +
                           str(self.HEIGHT))  # Set Window Size
        self.root.resizable(False, False)  # Not Resizable

        # Setup the window canvas
        self.canvas = Canvas(root, height=self.HEIGHT, width=self.WIDTH)
        self.canvas.pack()

        # Shape Object Controller Initialiser
        self.objectController = ObjectController(self)

        # GUI Handler Initialiser
        self.guiController = GUIController(self, root)

        # Input Handler Initialiser
        self.inputHandler = InputHandler(self)
        root.bind('<Motion>', self.inputHandler.MouseMovement
                  )  # This sets up the Mouse Movement Event
        root.bind('<Button 1>', self.inputHandler.MouseButtonLeftDown
                  )  # This is Left Mouse Button Click Event bind
        root.bind('<Button 3>', self.inputHandler.MouseButtonRightDown
                  )  # This is Right Mouse Button Click Event bind

        self.Update()
Ejemplo n.º 12
0
class GS_Game(GameState):
    inputHandler = InputHandler()
    board = None
    shape = None
    movementTime = 0

    def __init__(self, display):
        GameState.__init__(self, display)
        self.board = Board()
        self.shape = Shape(self.board, self.randomShape())

    def handleEvent(self, event):
        self.inputHandler.handleEvent(event)

    def update(self):
        if self.inputHandler.isKeyDown(pygame.K_ESCAPE):
            self.isAlive = False
        if self.inputHandler.isKeyHit(pygame.K_w):
            self.shape.rotateCW()
        if self.inputHandler.isKeyHit(pygame.K_s):
            self.shape.move((0, 1))
        if self.inputHandler.isKeyHit(pygame.K_a):
            self.shape.move((-1, 0))
        if self.inputHandler.isKeyHit(pygame.K_d):
            self.shape.move((1, 0))
        if pygame.time.get_ticks() > self.movementTime:
            self.shape.move((0, 1))
            self.movementTime = pygame.time.get_ticks() + 200
        if self.shape.isPlaced:
            self.shape = Shape(self.board, self.randomShape())

    def draw(self):
        self.board.draw(self.display)
        self.shape.draw(self.display)

    def randomShape(self):
        randInt = random.randint(1, 7)
        if randInt == 1:
            return [['yellow', 'yellow'], ['yellow', 'yellow']]
        elif randInt == 2:
            return [['purple', 'purple', 'purple'], [None, 'purple', None],
                    [None, None, None]]
        elif randInt == 3:
            return [['red', 'red', None], [None, 'red', 'red'],
                    [None, None, None]]
        elif randInt == 4:
            return [[None, 'green', 'green'], ['green', 'green', None],
                    [None, None, None]]
        elif randInt == 5:
            return [[None, None, 'orange'], ['orange', 'orange', 'orange'],
                    [None, None, None]]
        elif randInt == 6:
            return [['blue', None, None], ['blue', 'blue', 'blue'],
                    [None, None, None]]
        elif randInt == 7:
            return [[None, None, None, None], ['cyan', 'cyan', 'cyan', 'cyan'],
                    [None, None, None, None], [None, None, None, None]]
Ejemplo n.º 13
0
    def __init__(self):
        InputHandler.__init__(self)

        base.disableMouse()
        props = WindowProperties()
        props.setCursorHidden(True)
        base.win.requestProperties(props)

        self.accept("w", self.beginWalk)
        self.accept("w-up", self.endWalk)
        self.accept("s", self.beginReverse)
        self.accept("s-up", self.endReverse)
        self.accept("a", self.beginTurnLeft)
        self.accept("a-up", self.endTurnLeft)
        self.accept("d", self.beginTurnRight)
        self.accept("d-up", self.endTurnRight)

        taskMgr.add(self.updateInput, "update input")
Ejemplo n.º 14
0
def main():
    pwn.context.log_level = "ERROR"

    def _handle_final_outputs(poll_res):
        if not poll_res:
            return
        outs = map(lambda poll_elem: poll_elem[0], poll_res)

        if any("out" in out for out in outs):
            handler.handle_procout(None, None, None)
        if any("err" in out for out in outs):
            handler.handle_stderr(None)

    p = ArgumentParser()
    p.add_argument("-init", help="Pass a file for initial commands")
    # randomization disabled by default
    p.add_argument("-rand", action="store_true",
                   help="to enable randomization")
    p.add_argument("-sock", action="store_true",                                  # no socket by default
                   help="if you want to communicate with the program via a socket. (Adjust in Constants.py)")
    p.add_argument("runargs", nargs=REMAINDER)

    parsed_args = p.parse_args()
    launch_args = LaunchArguments(parsed_args.runargs, parsed_args.rand)

    handler = InputHandler(
        launch_args, startupfile=parsed_args.init, inputsock=parsed_args.sock)

    try:
        handler.inputLoop()

    # for now, Ctrl + C exits. The issue is that the event might abort
    # a procedure right in the middle of it.
    except KeyboardInterrupt:
        handler.manager.quit()
        _handle_final_outputs(handler.inputPoll.poll(10))
        exit(1)

    except BaseException as e:
        print("oh noes, a bug! please copy everything and send it to haxkor")
        print(handler.manager.family())
        handler.manager.quit()  # otherwise launched children stay alive
        raise e
Ejemplo n.º 15
0
def run(trip_path="trips/cities-1.json"):
    input_handler = InputHandler()
    input_handler.read_input_file(trip_path)
    candidate_generator = CandidateGenerator(input_handler.requested_cities,
                                             input_handler.trip_days,
                                             input_handler.avg_city_stay)

    trip_candidates = candidate_generator.get_n_most_popular_candidates(10)

    for trip in trip_candidates:
        trip.calculate_trip_distances(
            input_handler.requested_cities, input_handler.starting_station,
            StationData.StationData.time_between_stations)
        trip.find_optimal_route()
        trip.calculate_route_score(input_handler.requested_cities,
                                   input_handler.all_travellers)

    winning_trips = get_top_n_trips(trip_candidates, 5)

    print("\n".join([str(t) for t in winning_trips]))
Ejemplo n.º 16
0
    def __init__(self):
        InputHandler.__init__(self)

        self.wasWalking = False
        self.wasReversing = False
        self.controller = None

        pygame.init()
        pygame.joystick.init()

        for i in range(pygame.joystick.get_count()):
            joy = pygame.joystick.Joystick(i)
            name = joy.get_name()

            if "Xbox 360" in name or "XBOX 360" in name:
                joy.init()
                self.controller = joy
                self.state = XboxControllerState(joy)

        taskMgr.add(self.updateInput, "update input")
Ejemplo n.º 17
0
def main():

	run = True
	FPS = 60
	clock = pygame.time.Clock()
	AssetLoader.load()
	gameWorld = GameWorld()
	renderer = Renderer(gameWorld)
	inputHandler = InputHandler(gameWorld)
	

	while run:

		clock.tick(FPS)

		inputHandler.update()
		gameWorld.update()
		renderer.redraw_window()

		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				run = False
Ejemplo n.º 18
0
    def __init__(self):
        super(Firestarter, self).__init__()

        self.miner = {}

        self.shutdown = False
        self.idlePause = False

        self.idleHandler = IdleHandler(self.onIdle, self.onActive)
        self.inputHandler = InputHandler(self.inputLogic)

        self.inputHandler.bind('q', 'shutdown')

        self.inputHandler.bind('g', 'spawn-nicehash-daggerhashimoto')
        self.inputHandler.bind('c', 'spawn-nicehash-cryptonight')
        self.inputHandler.bind('t', 'spawn-nicehash-lyra2rev2')
        self.inputHandler.bind('a', 'spawn-nicehash-equihash')

        self.inputHandler.bind('h', 'dump-nicehash-daggerhashimoto')
        self.inputHandler.bind('v', 'dump-nicehash-cryptonight')
        self.inputHandler.bind('y', 'dump-nicehash-lyra2rev2')
        self.inputHandler.bind('s', 'dump-nicehash-equihash')

        self.inputHandler.bind('j', 'terminate-nicehash-daggerhashimoto')
        self.inputHandler.bind('b', 'terminate-nicehash-cryptonight')
        self.inputHandler.bind('u', 'terminate-nicehash-lyra2rev2')
        self.inputHandler.bind('d', 'terminate-nicehash-equihash')

        self.inputHandler.bind('i', 'idlePause')

        #    self.inputHandler.bind('g', self.tryStart('nicehash-daggerhashimoto'))
        #    self.inputHandler.bind('h', self.miner['nicehash-daggerhashimoto'].dump)

        #    self.inputHandler.bind('c', self.tryStart('ob-test'))
        #    self.inputHandler.bind('v', self.miner['ob-test'].dump)

        self.inputHandler.start()
        self.idleHandler.start()
Ejemplo n.º 19
0
    def initScene(self):
        #Scene initialization
        self.scene = Scene(self)

        self.earth = self.scene.sys.earth.mod
        self.moon = self.scene.sys.moon.mod
        self.sun = self.scene.sys.sun.mod
        self.home = self.scene.home
        self.focus = self.scene.focus

        #camera manip and mode
        self.Camera = Camera(self)
        #mouse and keyboard inputs
        self.InputHandler = InputHandler(self)
        #Interface
        self.Interface = Interface(self)
Ejemplo n.º 20
0
    def __init__(self, game):
        super(GameFrame, self).__init__(None, title='Zoo', size=(765, 800))
        self.printer = Printer(self)

        self.game = game
        self.notifications = []
        self.game.printer = self.printer
        self.game.set_notifications(self.notifications)
        self.notificationsWindow = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_WORDWRAP)

        self.inputHandler = InputHandler(self)

        # arrange stuff
        box = wx.BoxSizer(orient=wx.VERTICAL)
        box.Add(self.printer, 15, flag=wx.ALL, border=5)
        box.Add(self.notificationsWindow, 3, flag=wx.ALL | wx.EXPAND, border=5)
        box.Add(self.inputHandler, -1, flag=wx.ALL | wx.EXPAND, border=5)

        self.update_loop()

        self.SetSizer(box)
        self.Center()
        self.Show()
Ejemplo n.º 21
0
class TestAttack(unittest.TestCase):

    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

        self.map1 = '../game_states/game1_cake.json'
        self.game_state1 = GameState(self.map1)
        self.ih1 = InputHandler(self.game_state1)

        self.map_capital_alias = '../game_states/game_capital_alias.json'
        self.game_state_capital_alias = GameState(self.map_capital_alias)
        self.ih_capital_alias = InputHandler(self.game_state_capital_alias)

    def tearDown(self) -> None:
        del self.game_state
        del self.ih

        del self.game_state1
        del self.ih1

        del self.game_state_capital_alias
        del self.ih_capital_alias

    def test_attack(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack")
        result_output = stdout.getvalue()
        expected_output = "I don't understand that command.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_regular_item(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack envelope")
        result_output = stdout.getvalue()
        expected_output = "Action \"attack\" is not allowed with the envelope.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_consumable_item(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack bandage")
        result_output = stdout.getvalue()
        expected_output = "Action \"attack\" is not allowed with the bandage.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_equipment_weapon(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack sword")
        result_output = stdout.getvalue()
        expected_output = "Action \"attack\" is not allowed with the sword.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_equipment_armour(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack helmet")
        result_output = stdout.getvalue()
        expected_output = "Action \"attack\" is not allowed with the helmet.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_direction(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack west")
        result_output = stdout.getvalue()
        expected_output = "This action is not allowed with the west.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_creature(self):
        self.ih.handle_user_input("go west")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack dragon")
        result_output = stdout.getvalue()
        expected_output = "You hit the green dragon for 1 damage! Green dragon has 59 HP left.\n" \
                          "Green dragon hit you for 10 damage! You have 90 HP left.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_inventory(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack inventory")
        result_output = stdout.getvalue()
        expected_output = "This action is not allowed with the inventory.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_key(self):
        self.ih.handle_user_input("take helmet")
        self.ih.handle_user_input("take sword")
        self.ih.handle_user_input("take chestplate")
        self.ih.handle_user_input("equip helmet")
        self.ih.handle_user_input("equip sword")
        self.ih.handle_user_input("equip chestplate")
        self.ih.handle_user_input("go west")
        self.ih.handle_user_input("attack dragon")
        self.ih.handle_user_input("attack dragon")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack key")
        result_output = stdout.getvalue()
        expected_output = "Action \"attack\" is not allowed with the key.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_key_ambiguous(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih1.handle_user_input("attack key")
        result_output = stdout.getvalue()
        expected_output = "There are 2 \"key\". You have to be more specific.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_door(self):
        self.ih.handle_user_input("go west")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("attack door")
        result_output = stdout.getvalue()
        expected_output = "Action \"attack\" is not allowed with the door.\n"
        self.assertEqual(expected_output, result_output)

    def test_attack_door_ambiguous(self):
        self.ih1.handle_user_input("go north")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih1.handle_user_input("attack door")
        result_output = stdout.getvalue()
        expected_output = "There are 2 \"door\". You have to be more specific.\n"
        self.assertEqual(expected_output, result_output)

    # TESTS ON DIFFERENT CASES

    # creature

    def test_alias_capital_regular_item(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih_capital_alias.handle_user_input("attack Green Dragon")
        result_output = stdout.getvalue()
        expected_output = "You hit the Green Dragon for 1 damage! " \
                          "Green Dragon has 49 HP left.\n" \
                          "Green Dragon hit you for 10 damage! " \
                          "You have 90 HP left.\n"
        self.assertEqual(expected_output, result_output)

    def test_alias_lower_regular_item(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih_capital_alias.handle_user_input("attack green dragon")
        result_output = stdout.getvalue()
        expected_output = "You hit the Green Dragon for 1 damage! " \
                          "Green Dragon has 49 HP left.\n" \
                          "Green Dragon hit you for 10 damage! " \
                          "You have 90 HP left.\n"
        self.assertEqual(expected_output, result_output)

    def test_alias_lower_capital_regular_item(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih_capital_alias.handle_user_input("attack green Dragon")
        result_output = stdout.getvalue()
        expected_output = "You hit the Green Dragon for 1 damage! " \
                          "Green Dragon has 49 HP left.\n" \
                          "Green Dragon hit you for 10 damage! " \
                          "You have 90 HP left.\n"
        self.assertEqual(expected_output, result_output)
Ejemplo n.º 22
0
class TestStatus(unittest.TestCase):

    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

    def tearDown(self) -> None:
        del self.game_state
        del self.ih

    def test_status(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("status")
        result_output = stdout.getvalue()
        expected_output = "----- HERO STATUS -----\n" \
                          "Health: 100 HP\n" \
                          "Attack Power: 1 ATK\n" \
                          "Weapon: nothing\n" \
                          "Head: nothing\n" \
                          "Chest: nothing\n" \
                          "Legs: nothing\n" \
                          "-----------------------\n"
        self.assertEqual(expected_output, result_output)

    def test_status_health(self):
        self.ih.handle_user_input("go west")
        self.ih.handle_user_input("attack dragon")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("status")
        result_output = stdout.getvalue()
        expected_output = "----- HERO STATUS -----\n" \
                          "Health: 90 HP\n" \
                          "Attack Power: 1 ATK\n" \
                          "Weapon: nothing\n" \
                          "Head: nothing\n" \
                          "Chest: nothing\n" \
                          "Legs: nothing\n" \
                          "-----------------------\n"
        self.assertEqual(expected_output, result_output)

    def test_status_weapon_slot(self):
        self.ih.handle_user_input("take sword")
        self.ih.handle_user_input("equip sword")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("status")
        result_output = stdout.getvalue()
        expected_output = "----- HERO STATUS -----\n" \
                          "Health: 100 HP\n" \
                          "Attack Power: 30 ATK\n" \
                          "Weapon: Sword made of pure silver with a straight " \
                          "double-edged blade and a grip for two-handed use 30 ATK\n" \
                          "Head: nothing\n" \
                          "Chest: nothing\n" \
                          "Legs: nothing\n" \
                          "-----------------------\n"
        self.assertEqual(expected_output, result_output)

    def test_status_head_slot(self):
        self.ih.handle_user_input("take helmet")
        self.ih.handle_user_input("equip helmet")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("status")
        result_output = stdout.getvalue()
        expected_output = "----- HERO STATUS -----\n" \
                          "Health: 100 HP\n" \
                          "Attack Power: 1 ATK\n" \
                          "Weapon: nothing\n" \
                          "Head: Gladiator helmet made of steel 2 DEF 12 Durability\n" \
                          "Chest: nothing\n" \
                          "Legs: nothing\n" \
                          "-----------------------\n"
        self.assertEqual(expected_output, result_output)

    def test_status_chest(self):
        self.ih.handle_user_input("take chestplate")
        self.ih.handle_user_input("equip chestplate")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("status")
        result_output = stdout.getvalue()
        expected_output = "----- HERO STATUS -----\n" \
                          "Health: 100 HP\n" \
                          "Attack Power: 1 ATK\n" \
                          "Weapon: nothing\n" \
                          "Head: nothing\n" \
                          "Chest: Steel chestplate armor 3 DEF 18 Durability\n" \
                          "Legs: nothing\n" \
                          "-----------------------\n"
        self.assertEqual(expected_output, result_output)
Ejemplo n.º 23
0
 def handle_question(self):
     answer = InputHandler.get_input(self.current_question.text + " ")
     self.validate_answer(answer)
Ejemplo n.º 24
0
 def __init__(self, credentials, serverWrapper):
     clientStateInfo = ClientStateInfo(credentials, GENERAL_CHATROOM)
     self.messageUpdater = MessageUpdater(serverWrapper, clientStateInfo,
                                          self)
     self.inputHandler = InputHandler(serverWrapper, clientStateInfo, self)
Ejemplo n.º 25
0
import evdev
import time
import asyncio
from EventHandler import EventHandler
from InputHandler import InputHandler
from ProgramHandler import ProgramHandler
import KeyPressHandler

from evdev.ecodes import *

device = InputHandler("/dev/input/by-path/platform-i8042-serio-0-event-kbd",
                      grabbed=True)
e = evdev.ecodes
uinput = evdev.UInput()


@device.eventHandler(KEY_A)
async def foo(event):
    ProgramHandler("cat /home/popcorn9499/iommuGroups.sh")

    if event.value == KeyPressHandler.KEY_STATE.KEY_DOWN:
        key = KeyPressHandler.KeyPress(keys=[KEY_LEFTCTRL, KEY_M])
        await key.keyPress(keyState=KeyPressHandler.KEY_STATE.KEY_TOGGLE,
                           pressDuration=0.1)


@device.eventHandler(KEY_B)
async def bar(event):
    print("This is bar's first handler")
    print(evdev.categorize(event))
Ejemplo n.º 26
0
class TestConsume(unittest.TestCase):
    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

        self.map1 = '../game_states/game1_cake.json'
        self.game_state1 = GameState(self.map1)
        self.ih1 = InputHandler(self.game_state1)

    def tearDown(self) -> None:
        del self.game_state
        del self.ih

        del self.game_state1
        del self.ih1

    def test_use_bottle_entrance_room(self):
        self.ih.handle_user_input("take bottle")

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("use bottle")
        result_output = stdout.getvalue()
        expected_output = "The unlabelled bottle reduced your HP by 75. Your current health is 25 HP.\n" \
                          "It was a poison.\n"
        self.assertEqual(expected_output, result_output)

    def test_use_bottle_arena_room(self):
        self.ih.handle_user_input("take bottle")
        self.ih.handle_user_input("go west")

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("use bottle")
        result_output = stdout.getvalue()
        expected_output = "The unlabelled bottle reduced your HP by 75. Your current health is 25 HP.\n" \
                          "It was a poison.\n"
        self.assertEqual(expected_output, result_output)

    def test_drink_bottle_entrance_room(self):
        self.ih.handle_user_input("take bottle")

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("drink bottle")
        result_output = stdout.getvalue()
        expected_output = "The unlabelled bottle reduced your HP by 75. Your current health is 25 HP.\n" \
                          "It was a poison.\n"
        self.assertEqual(expected_output, result_output)

    def test_drink_bottle_arena_room(self):
        self.ih.handle_user_input("take bottle")
        self.ih.handle_user_input("go west")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("drink bottle")
        result_output = stdout.getvalue()
        expected_output = "The unlabelled bottle reduced your HP by 75. Your current health is 25 HP.\n" \
                          "It was a poison.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(25, self.game_state.hero.health)

    def test_use_bandage_full_hp(self):
        self.ih.handle_user_input("take bandage")
        self.assertEqual(1, len(self.game_state.hero.inventory))
        self.assertEqual(100, self.game_state.hero.health)
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("use bandage")
        result_output = stdout.getvalue()
        expected_output = "Your health is already at 100 HP, you don't need healing.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(1, len(self.game_state.hero.inventory))
        self.assertEqual(100, self.game_state.hero.health)

    def test_use_bandage_after_poison(self):
        self.ih.handle_user_input("take bottle")
        self.assertEqual(1, len(self.game_state.hero.inventory))
        self.ih.handle_user_input("drink unlabelled bottle")
        self.assertEqual(0, len(self.game_state.hero.inventory))
        self.assertEqual(25, self.game_state.hero.health)

        self.ih.handle_user_input("take bandage")
        self.assertEqual(1, len(self.game_state.hero.inventory))
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("use bandage")
        result_output = stdout.getvalue()
        expected_output = "The bandage healed you by 25 HP. Your current health is 50 HP.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(50, self.game_state.hero.health)
        self.assertEqual(0, len(self.game_state.hero.inventory))

    def test_eat_cake(self):
        self.ih1.handle_user_input("take kitchen key")
        self.ih1.handle_user_input("go north")
        self.ih1.handle_user_input("unlock kitchen door")
        self.ih1.handle_user_input("go east")
        self.ih1.handle_user_input("take cake")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih1.handle_user_input("eat cake")
        result_output = stdout.getvalue()
        expected_output = "The cake reduced your HP by 15. Your current health is 85 HP.\n" \
                          "You found key. This key opens heavy metal door.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(85, self.game_state1.hero.health)
        hero_room: Room = self.game_state1.rooms[
            self.game_state1.hero.location]
        self.assertIn("#item_doorkey_exit", hero_room.items)
Ejemplo n.º 27
0
        y = y+1

    response = {}

    if(voice):
        response = wit.voice_query_auto(TOKEN)
    elif(usetext):
        response = wit.text_query(sys.argv[textpos], TOKEN)
    else:
        time.sleep(1)
        response = wit.text_query(raw_input(">> "), TOKEN)

    wit.close()
    time.sleep(0.1)

    inp = InputHandler(response)
    task = inp.getIntent()

    if(task == 'time_places'):
        handle = TimeHandler(inp.getValue())
        for x in handle.lookup():
            print(x)
    elif(task == 'weather_in'):
        handle = WeatherHandler(inp.getValue())
        for x in handle.printData():
            print(x)
    elif(task == 'check_time'):
        handle = TimeCheckHandler(inp.getValue())
        for x in handle.Result():
            print(x)
    elif(task == 'computer_power'):
Ejemplo n.º 28
0
matrix = [list(EMPTY_SPOT_VALUE * 3), list(EMPTY_SPOT_VALUE * 3), list(EMPTY_SPOT_VALUE * 3)]

terminal_handler = TerminalHandler()

winner = None
player_one = PlayerFactory.create_player('x', input("Please enter the first player's nickname: "))
player_two = PlayerFactory.create_player('o', input("Now the second player's nickname: "))
current_player = player_one


try:
    while not winner:
        terminal_handler.print_current_turn(current_player)
        terminal_handler.print_matrix(matrix)
        selected_indexes = InputHandler.get_player_input(matrix)

        if current_player.symbol == 'x':
            matrix[selected_indexes[0]][selected_indexes[1]] = 'x'
        else:
            matrix[selected_indexes[0]][selected_indexes[1]] = 'o'

        match_ended = MatrixHandler.match_ended(matrix, current_player.symbol)

        if match_ended:
            winner = current_player
        elif not match_ended and MatrixHandler.no_spots_left(matrix):
            break
        else:
            if current_player.symbol == 'x':
                current_player = player_two
Ejemplo n.º 29
0
def main():

    pygame.init()
    pygame.display.set_caption('Window')

    timerController = TimerController()
    inputHandler = InputHandler()

    fsms = FSMs(timerController, inputHandler.pressed,
                inputHandler.previouslyPressed)

    timeSinceRender = timePerFrameInms + 1

    view = View(size=(300, 300))

    surface = pygame.display.set_mode(view.size)

    clock = pygame.time.Clock()

    collisionHandler = CollisionHandler()

    geometries = [
        Geometry(pygame.Rect(100.0, 130.0, 100, 40)),
        Geometry(pygame.Rect(10.0, 70.0, 40, 40)),
        Geometry(pygame.Rect(0.0, 160.0, 300, 40)),
        Geometry(pygame.Rect(-40, 0, 40, 200)),
        Geometry(pygame.Rect(300, 0, 40, 200))
    ]

    entities = [
        Entity(entityType="player", pos=(100, 100)),
        Entity(entityType="yBox", pos=(50.0, 150.0))
    ]

    view.hook(lambda: entities[0].pos)

    #main game loop
    while True:
        timeSinceRender += clock.tick()
        #timeSinceRender is in milliseconds
        #print "timeSinceRender", timeSinceRender
        #counter = counter +1

        while timeSinceRender > timePerFrameInms:

            timeSinceRender -= timePerFrameInms

            checkQuit()

            #update logic
            inputHandler.updateKeyState()
            timerController.tick()

            #run fsm
            fsms(entities, inputHandler.pressed,
                 inputHandler.previouslyPressed)

            #find constraints (i.e l used in time integrator)
            collisionHandler(entities, geometries)

            #update world
            timeIntegrator(entities)

        drawScene(surface, view, entities, geometries)
Ejemplo n.º 30
0
class TestUnequip(unittest.TestCase):
    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

    def tearDown(self) -> None:
        del self.game_state
        del self.ih

    def test_unequip_no_target(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip")
        result_output = stdout.getvalue()
        expected_output = "I don't understand that command.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_helmet_not_in_inventory(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip helmet")
        result_output = stdout.getvalue()
        expected_output = "It is not equipped.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_helmet_in_inventory_not_equipped(self):
        self.ih.handle_user_input("take helmet")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip helmet")
        result_output = stdout.getvalue()
        expected_output = "It is not equipped.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_sword_not_in_inventory(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip sword")
        result_output = stdout.getvalue()
        expected_output = "It is not equipped.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_sword_in_inventory_not_equipped(self):
        self.ih.handle_user_input("take sword")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip sword")
        result_output = stdout.getvalue()
        expected_output = "It is not equipped.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_envelope_room(self):
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip envelope")
        result_output = stdout.getvalue()
        expected_output = "Action \"unequip\" is not allowed with the envelope.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_envelope_inv(self):
        self.ih.handle_user_input("take envelope")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip envelope")
        result_output = stdout.getvalue()
        expected_output = "Action \"unequip\" is not allowed with the envelope.\n"
        self.assertEqual(expected_output, result_output)

    def test_unequip_helmet_equipped(self):
        self.ih.handle_user_input("take helmet")
        self.ih.handle_user_input("equip helmet")
        hero = self.game_state.hero
        self.assertEqual(hero.head_slot, "#equipment_gladiator_helmet")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip helmet")
        result_output = stdout.getvalue()
        expected_output = "Item unequipped.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(hero.head_slot, None)

    def test_unequip_sword_equipped(self):
        self.ih.handle_user_input("take sword")
        self.ih.handle_user_input("equip sword")
        hero = self.game_state.hero
        self.assertEqual(hero.weapon_slot, "#equipment_silver_sword")
        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout):
            self.ih.handle_user_input("unequip sword")
        result_output = stdout.getvalue()
        expected_output = "Item unequipped.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(hero.weapon_slot, None)
Ejemplo n.º 31
0
class TestEnding(unittest.TestCase):
    def setUp(self) -> None:
        self.map0 = '../game_states/game0_repr.json'
        self.game_state = GameState(self.map0)
        self.ih = InputHandler(self.game_state)

        self.map1 = '../game_states/game1_cake.json'
        self.game_state1 = GameState(self.map1)
        self.ih1 = InputHandler(self.game_state1)

    def tearDown(self) -> None:
        del self.game_state
        del self.ih

        del self.game_state1
        del self.ih1

    # -- Good End --

    def test_game1_escape_good_end(self):
        self.ih1.handle_user_input("take kitchen key")
        self.ih1.handle_user_input("go north")
        self.ih1.handle_user_input("unlock kitchen door")
        self.ih1.handle_user_input("go east")
        self.ih1.handle_user_input("take cake")
        self.ih1.handle_user_input("eat cake")
        self.ih1.handle_user_input("take key")
        self.ih1.handle_user_input("unlock heavy metal door")

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout), self.assertRaises(
                SystemExit) as e:
            self.ih1.handle_user_input("go east")
        result_output = stdout.getvalue()
        expected_output = "Congratulations Hero!\nYou are free. Do anything you want, be who you want to be.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual('0', str(e.exception))

    def test_game0_escape_good_end(self):
        self.ih.handle_user_input("take sword")
        self.ih.handle_user_input("equip sword")
        self.ih.handle_user_input("go west")
        for i in range(2):
            self.ih.handle_user_input("attack dragon")
        self.ih.handle_user_input("take key")
        self.ih.handle_user_input("unlock door")

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout), self.assertRaises(
                SystemExit) as e:
            self.ih.handle_user_input("go north")
        result_output = stdout.getvalue()
        expected_output = "Congratulations Hero!\nYou are free. Do anything you want, be who you want to be.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual('0', str(e.exception))

    # -- Bad End --

    def test_hero_dead_bad_end(self):
        self.ih.handle_user_input("go west")
        for i in range(9):
            self.ih.handle_user_input("attack dragon")

        self.assertEqual(51,
                         self.game_state.creatures["#creature_dragon"].health)
        self.assertEqual(10, self.game_state.hero.health)

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout), self.assertRaises(
                SystemExit) as e:
            self.ih.handle_user_input("attack dragon")
        result_output = stdout.getvalue()
        expected_output = "You hit the green dragon for 1 damage! " \
                          "Green dragon has 50 HP left.\n" \
                          "Green dragon hit you for 10 damage! You have 0 HP left.\n" \
                          "GAME OVER. You were killed by green dragon. Better luck next time.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(50,
                         self.game_state.creatures["#creature_dragon"].health)
        self.assertEqual(0, self.game_state.hero.health)
        self.assertEqual('0', str(e.exception))

    def test_hero_dead_helmet_overkill_bad_end(self):
        self.ih.handle_user_input("take helmet")
        self.ih.handle_user_input("equip helmet")
        self.ih.handle_user_input("go west")
        for i in range(10):
            self.ih.handle_user_input("attack dragon")

        self.assertEqual(50,
                         self.game_state.creatures["#creature_dragon"].health)
        self.assertEqual(6, self.game_state.hero.health)

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout), self.assertRaises(
                SystemExit) as e:
            self.ih.handle_user_input("attack dragon")
        result_output = stdout.getvalue()
        expected_output = "You hit the green dragon for 1 damage! " \
                          "Green dragon has 49 HP left.\n" \
                          "Green dragon hit you for 10 damage! You have -4 HP left.\n" \
                          "GAME OVER. You were killed by green dragon. Better luck next time.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(49,
                         self.game_state.creatures["#creature_dragon"].health)

        self.assertEqual(-4, self.game_state.hero.health)

        self.assertEqual('0', str(e.exception))

    def test_hero_death_by_poison_bad_end(self):
        self.ih.handle_user_input("go west")
        for i in range(9):
            self.ih.handle_user_input("attack dragon")

        self.assertEqual(51,
                         self.game_state.creatures["#creature_dragon"].health)
        self.assertEqual(10, self.game_state.hero.health)

        self.ih.handle_user_input("go east")
        self.ih.handle_user_input("take unlabelled bottle")

        stdout = io.StringIO()
        with contextlib.redirect_stdout(stdout), self.assertRaises(
                SystemExit) as e:
            self.ih.handle_user_input("drink unlabelled bottle")
        result_output = stdout.getvalue()
        expected_output = "The unlabelled bottle reduced your HP by 75. Your current health is -65 HP.\n" \
                          "GAME OVER. You were killed by unlabelled bottle. Better luck next time.\n"
        self.assertEqual(expected_output, result_output)
        self.assertEqual(-65, self.game_state.hero.health)
        self.assertEqual('0', str(e.exception))