示例#1
0
	def game_round(self,position):
		# set round speed and guess
		speed = 1./(1+position)
		guess = -1
		stop = False
		
		# turn on GPIO pins
		for i in pinList[position:]:
			GPIO.setup(i, GPIO.OUT)
			GPIO.output(i, GPIO.HIGH)
		
		# turn on correct guesses
		for i in pinList[0:position]:
			GPIO.output(i, GPIO.LOW)
			
		#start kbhit 
		kb = KBHit()
		
		# start loop
		while True:
			for i in pinList[position:]:
				GPIO.output(i, GPIO.LOW)
				
				# check keypress
				if kb.kbhit():
					c = kb.getch()
					if ord(c) != 27:
						stop = True
						guess = pinList.index(i)-1
						break
				time.sleep(speed)
			# check keypress
			if stop:
				break
				
			pinList.reverse()
			for i in pinList[0:len(pinList)-position]:
				GPIO.output(i,GPIO.HIGH)
				if kb.kbhit():
					c = kb.getch()
					if ord(c) != 27:
						stop = True
						guess = len(pinList)-(pinList.index(i)+1)
						pinList.reverse()
				time.sleep(speed)
			if stop:
				break
			pinList.reverse()
		# check results
		print guess
		print position
		return (guess == position)
示例#2
0
    def game_round(self, position):
        # set round speed and guess
        speed = 1. / (1 + position)
        guess = -1
        stop = False

        # turn on GPIO pins
        for i in pinList[position:]:
            GPIO.setup(i, GPIO.OUT)
            GPIO.output(i, GPIO.HIGH)

        # turn on correct guesses
        for i in pinList[0:position]:
            GPIO.output(i, GPIO.LOW)

        #start kbhit
        kb = KBHit()

        # start loop
        while True:
            for i in pinList[position:]:
                GPIO.output(i, GPIO.LOW)

                # check keypress
                if kb.kbhit():
                    c = kb.getch()
                    if ord(c) != 27:
                        stop = True
                        guess = pinList.index(i) - 1
                        break
                time.sleep(speed)
            # check keypress
            if stop:
                break

            pinList.reverse()
            for i in pinList[0:len(pinList) - position]:
                GPIO.output(i, GPIO.HIGH)
                if kb.kbhit():
                    c = kb.getch()
                    if ord(c) != 27:
                        stop = True
                        guess = len(pinList) - (pinList.index(i) + 1)
                        pinList.reverse()
                time.sleep(speed)
            if stop:
                break
            pinList.reverse()
        # check results
        print guess
        print position
        return (guess == position)
示例#3
0
    def run(self):
        """Run the CPU."""
        self._running = True
        old_time = time()
        kb = KBHit()
        while self._running:
            # trigger timer interrupt every second (approx)
            new_time = time()
            if new_time - old_time > 1:
                self.interrupt(TIMER_INTERRUPT)
                old_time = new_time

            # trigger keyboard interrupt on keypress
            if kb.kbhit():
                c = kb.getch()
                if ord(c[0]) == 27:  # ESC
                    self._running = False
                    break
                self.ram_write(KEY_BUFFER, ord(c[0]))
                self.interrupt(KEYBOARD_INTERRUPT)

            self.check_interrupts()

            # process instruction at program counter
            self.IR = self.ram_read(self.PC)
            if self.IR & ALU_MASK:
                self.alu(ALU[self.IR], self.OP_A, self.OP_B)
            else:
                OPCODES[self.IR](self)

            # adjust program counter if necessary
            if not self.IR & 0b10000:
                self.PC += (1 + (self.IR >> 6))

        kb.set_normal_term()
    def main(self):   
        kb = KBHit()  # needed for windows to handle keyboard interrupt         
        print('Hit ESC to exit')             
        try:
            #time.sleep(1)
            #self.request_port_mapping()
            time.sleep(0.5)
            self.set_pin_mode(13, AsipClient.OUTPUT)
            time.sleep(0.5)
            self.set_pin_mode(2, AsipClient.INPUT_PULLUP)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write("Exception: caught {} in setting pin mode".format(e))

        while True:        
            if kb.kbhit():
                c = kb.getch()                
                if ord(c) == 27: # ESC
                    kb.set_normal_term() 
                    break 
            try:
                self.digital_write(13, 1)
                time.sleep(1.25)
                self.digital_write(13, 0)
                time.sleep(1.25)
            except Exception as e:
                sys.stdout.write("Exception: caught {} in digital_write".format(e))
示例#5
0
    def main(self):
        if os.name == 'nt':
            kb = KBHit()  # needed for windows to handle keyboard interrupt
            sys.stdout.write('Hit ESC to exit\n')
        try:
            time.sleep(0.5)
            self.asip.set_pin_mode(13, self.asip.OUTPUT)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write("Exception caught while setting pin mode: {}\n".format(e))
            self.thread_killer()
            sys.exit(1)

        while True:        
            if os.name == 'nt':
                if kb.kbhit():
                    c = kb.getch()
                    if ord(c) == 27:  # ESC
                        kb.set_normal_term()
                        break
            try:
                self.asip.digital_write(13, self.asip.HIGH)
                time.sleep(1.25)
                self.asip.digital_write(13, self.asip.LOW)
                time.sleep(1.25)
            except (KeyboardInterrupt, Exception) as e:
                sys.stdout.write("Caught exception in main loop: {}\n".format(e))
                self.thread_killer()
                sys.exit()
示例#6
0
    def main(self):
        kb = KBHit()  # needed for windows to handle keyboard interrupt
        print('Hit ESC to exit')
        try:
            #time.sleep(1)
            #self.request_port_mapping()
            time.sleep(0.5)
            self.set_pin_mode(13, AsipClient.OUTPUT)
            time.sleep(0.5)
            self.set_pin_mode(2, AsipClient.INPUT_PULLUP)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write(
                "Exception: caught {} in setting pin mode".format(e))

        while True:
            if kb.kbhit():
                c = kb.getch()
                if ord(c) == 27:  # ESC
                    kb.set_normal_term()
                    break
            try:
                self.digital_write(13, 1)
                time.sleep(1.25)
                self.digital_write(13, 0)
                time.sleep(1.25)
            except Exception as e:
                sys.stdout.write(
                    "Exception: caught {} in digital_write".format(e))
示例#7
0
    def main(self):
        if os.name == 'nt':
            kb = KBHit()  # needed for windows to handle keyboard interrupt
            sys.stdout.write('Hit ESC to exit\n')
        try:
            time.sleep(0.5)
            self.asip.set_pin_mode(13, self.asip.OUTPUT)
            time.sleep(0.5)
        except Exception as e:
            sys.stdout.write(
                "Exception caught while setting pin mode: {}\n".format(e))
            self.thread_killer()
            sys.exit(1)

        while True:
            if os.name == 'nt':
                if kb.kbhit():
                    c = kb.getch()
                    if ord(c) == 27:  # ESC
                        kb.set_normal_term()
                        break
            try:
                self.asip.digital_write(13, self.asip.HIGH)
                time.sleep(1.25)
                self.asip.digital_write(13, self.asip.LOW)
                time.sleep(1.25)
            except (KeyboardInterrupt, Exception) as e:
                sys.stdout.write(
                    "Caught exception in main loop: {}\n".format(e))
                self.thread_killer()
                sys.exit()
示例#8
0
def waitForInput(running_flag, threads):
    kb = KBHit()
    while True:
        if kb.kbhit():
            c = kb.getch()
            if ord(c) == 27:  # ESC
                break
        e.sleep(0.1)
    kb.set_normal_term()

    socket.stop()
示例#9
0
def talker():
    lista_threads= []
    pub = rospy.Publisher('ipcam', String)
    rospy.init_node('ipcam', anonymous=True)
    #rate = rospy.Rate(10) # 10hz
    kbhit = KBHit()
    print "Press i to move up the camera\n" \
      "Press k to move down the camera\n" \
      "Press j to move right the camera\n" \
      "Press l to move left the camera\n" \
      "Press q to home position the camera\n" \
      "Press s to get another snapshot\n" \
      "Press v to get video\n\n"
    try:
        while not rospy.is_shutdown():
            if kbhit.kbhit():
                print "Press i to move up the camera\n" \
                  "Press k to move down the camera\n" \
                  "Press j to move right the camera\n" \
                  "Press l to move left the camera\n" \
                  "Press q to home position the camera\n" \
                  "Press s to get another snapshot\n" \
                  "Press v to get video\n\n"
                char = kbhit.getch()

                if char == 's':
                    thread=threading.Thread(target=getImage, args=(False,))
                    thread.start()
                    time.sleep(1)
                    lista_threads.append(thread)
                elif char == 'v':
                    thread=threading.Thread(target=getImage, args=(True,))
                    thread.start()
                    time.sleep(1)
                    lista_threads.append(thread)

                else:
                    rospy.loginfo(char)
                    pub.publish(char)
                char = ""
            time.sleep(1)

    except KeyboardInterrupt:

        for each in lista_threads:
            while each.isAlive():
                pass
示例#10
0
class GameLoop():
    def __init__(self):

        self.cross_platform = CrossplatformFunctions()
        self.cross_platform.resize_screen()

        self.keyboard = KBHit()

        self.space = DeepSpace()
        self.blue_racer = BlueRacer(39, 60, '#', self.space)

        self.loop = asyncio.get_event_loop()
        self.loop.run_until_complete(self.start())

    @asyncio.coroutine
    def start(self):
        while True:
            self.frame()
            yield from asyncio.sleep(FPS)

    def frame(self):
        #self.blue_racer.move(randint(-1, 1), randint(-1, 1))
        if self.keyboard.kbhit():
            self.blue_racer_move()
        self.print_space()

    def blue_racer_move(self):
        key = self.keyboard.getch()
        if ord(key) == 51:
            self.blue_racer.move(0, 1)
        elif ord(key) == 49:
            self.blue_racer.move(0, -1)

    def print_space(self):
        self.cross_platform.clear_screen()
        s = ''
        for row in self.space.visible_space:
            r = ''.join(row) + '\n'
            s += r
        print(s)
        print('x: ', self.blue_racer.x, len(self.space.visible_space))
        print('y: ', self.blue_racer.y)
示例#11
0
def main():
    # Import the utilities helper module
    import argparse
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
    import utilities

    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--proportional_gain",
                        type=float,
                        help="proportional gain used in control loop",
                        default=2.0)
    args = utilities.parseConnectionArguments(parser)

    # Create connection to the device and get the router
    with utilities.DeviceConnection.createTcpConnection(args) as router:

        with utilities.DeviceConnection.createUdpConnection(
                args) as router_real_time:

            kbhit = KBHit()
            example = GripperLowLevelExample(router, router_real_time,
                                             args.proportional_gain)
            print(
                "Press keys '0' to '9' to change gripper position. Press ESC to quit."
            )
            while True:
                if kbhit.kbhit():
                    ch = kbhit.getch()
                    if ord(ch) == 27:
                        break
                    elif ch >= '0' and ch <= '9':
                        target_position = (float(ch) + 1) * 10.0
                        print("Going to position %i" % (target_position))
                        example.Goto(target_position)
                        print("Target reached")
            time.sleep(0.2)
            example.Cleanup()
示例#12
0
def console_run(program_file: str,
                autorun_file: Optional[str] = None,
                init_str: str = ''):
    vm = Virtual8080()
    vm.io = AltairWithTerminal()
    with open(program_file, 'rb') as pf:
        program = pf.read()
    vm.load(program)

    if autorun_file is not None:
        init_buffer = init_str
        with open(autorun_file, 'r') as af:
            for line in af.readlines():
                init_buffer += line.replace('\n', '\r')
        vm.io.input_buffer = init_buffer.encode(encoding='ascii')

    kb = KBHit()
    try:
        vm.halted = False
        while not vm.halted:
            ch = vm.io.output_char
            if ch != -1 and ch != 13:
                print(bytes([ch]).decode(encoding='ascii'), end='', flush=True)
            vm.io.output_char = -1
            if kb.kbhit():
                ch = ord(kb.getch())
                if ch == 10:
                    vm.io.input_buffer += bytes([13, 0])
                elif ch == 27:
                    # Break on ESC
                    vm.io.input_buffer += bytes([3])
                else:
                    vm.io.input_buffer += bytes([ch])
            vm.step()
    finally:
        kb.set_normal_term()
示例#13
0
prevLoss = 0.0
maxModel = None
stop = False
for args in itertools.product(nb_hiddens, drop1s, drop2s, drop3s, nb_filters, nb_pools, nb_rows, nb_columns):
    print("Model: ", args)
    hist, model = get_model_and_score(X_train, Y_train, *args)
    # most recent loss hist.history["loss"][-1]
    r, rmse, _ = assess_model(model, X_validate, Y_validate)
    print("Model r: ", r)
    print("Model rmse: ", rmse)
    if abs(r[0]) > prevLoss:
        prevLoss = abs(r[0])
        maxModel = model
    while kb.kbhit():
        try:
            if "q" in kb.getch():
                print("quiting due to user pressing q")
                stop = True
        except UnicodeDecodeError:
            pass

    if stop:
        break

del X_train

X_test = np.array(X_test)
Y_test_norm = np.array(list(map(normalize_bpm, Y_test)))

r, rmse, preds = assess_model(maxModel, X_test, Y_test_norm)
predicted_bpm = np.array(list(map(unnormalize_bpm, preds)))
示例#14
0
class Hotkey:
    def __init__(self, keys: str, mode: str = 'hotkey', window=None):
        self.mode = mode
        self.window = window
        self.shot_job = None
        self.battle_job = self.visit_room_job = self.cork_shop_job = self.monitor_job = Job(
        )
        self.kb = KBHit()
        self.positions = [Position(_id) for _id in range(1, 10)]
        self.keys = [
            f'z+{i}'
            for i in (list(range(1, 10)) if mode == 'hotkey' else []) +
            list(keys)
        ]
        self.add_hotkey()

    def __user_command(self, key):
        while self.kb.kbhit():
            self.kb.getch()
        if '1' <= key <= '9':
            self.positions[int(key) - 1].record(self.monitor_job.is_alive())
        elif self.monitor_job.is_alive():
            pass
        else:
            self.__call(key)

    def __call(self, key: str):
        method_name = f'_Hotkey__cmd_{key}'
        getattr(self, method_name)()

    def __cmd_r(self):
        if self.process_idle():
            self.battle_job = Job(target=battle, args=(fake_window, ))
            self.battle_job.start()
        elif self.battle_job.is_pausing():
            self.battle_job.resume()

    def __cmd_v(self):
        if self.process_idle():
            self.visit_room_job = Job(target=visit_friend_room,
                                      args=(fake_window, ))
            self.visit_room_job.start()
        elif self.visit_room_job.is_pausing():
            self.visit_room_job.resume()

    def __cmd_e(self):
        if self.process_idle():
            self.cork_shop_job = Job(target=cork_shop_exchange,
                                     args=(fake_window, ))
            self.cork_shop_job.start()
        elif self.cork_shop_job.is_pausing():
            self.cork_shop_job.resume()

    def __cmd_i(self):
        kirafan.screenshot()

    def __cmd_s(self):
        if self.mode == 'gui':
            if self.window['_button_Start_'].GetText() == 'Stop':
                self.window.write_event_value('_button_Start_', None)
            elif self.window['_button_Visit Room_'].GetText() == 'Stop Visit':
                self.window.write_event_value('_button_Visit Room_', None)
            elif self.window['_button_Cork Shop_'].GetText(
            ) == 'Stop Exchange':
                self.window.write_event_value('_button_Cork Shop_', None)
        elif not self.process_idle():
            logger.info('press stop now!, Please wait for a while')
            self.safe_exit()

    def __cmd_l(self):
        uData.reload()
        adb.reload()
        kirafan.reload()
        logger.info('kirafan-bot: reload configuration finish')
        logger.info(f'kirafan-bot: region = {list(kirafan.region)}')
        logger.info(f'kirafan-bot: adb use = {uData.setting["adb"]["use"]}')
        logger.info(
            f'kirafan-bot: quest setting = \x1b[41m{kirafan.quest_name}\x1b[0m'
        )

    def __cmd_k(self):
        uData.adb_mode_switch()
        adb.reload()
        kirafan.adb_mode_switch()
        logger.info(f'kirafan-bot: region = {list(kirafan.region)}')
        logger.info(
            f'kirafan-bot: adb use = \x1b[35m{uData.setting["adb"]["use"]}\x1b[0m'
        )
        tuple_files = kirafan.miss_icon_files()
        if tuple_files:
            print('miss icon files:')
            for tuple_file in tuple_files:
                print(f'  {tuple_file[1]}')
            print('you can press hotkey "z+c" to add a miss icon file')

    def __cmd_m(self):
        if not self.monitor_job.is_alive():
            self.monitor_job = Job(target=monitor_mode)
            self.monitor_job.start()

    def __cmd_p(self):
        for position in self.positions:
            print(position, end='')

    def __cmd_t(self):
        print('')
        adb.set_update_cv2_IM_cache_flag()
        kirafan.objects_found_all_print()
        kirafan.icons_found_all_print()
        print('')

    def __cmd_c(self):
        if self.shot_job and self.shot_job.is_alive():
            return

        tuple_files = kirafan.miss_icon_files()
        if tuple_files:
            print('miss icon files:')
            for i, tuple_file in enumerate(tuple_files):
                print(f'  {i}.{tuple_file[0]}')

            sleep(0.1)
            if self.kb.kbhit():
                self.kb.getch()

            number = input('select a number which you want to save icon: ')
            if number.isnumeric() and 0 <= int(number) < len(tuple_files):
                self.shot_job = Job(target=self.tutorial_screenshot,
                                    args=[tuple_files[int(number)]])
                self.shot_job.start()
            else:
                print('invaild input:', number)
        else:
            print('No miss icon file')

    def __cmd_o(self):
        kirafan.stop_once = not kirafan.stop_once
        logger.info(
            f'({str(kirafan.stop_once):>5}) kirafan-bot stop after current battle is completed'
        )

    def __cmd_x(self):
        old = uData.setting['game_region'][:2]
        new = game_region()
        if old != new:
            uData.save_location(*new)
            self.__cmd_l()

    def add_hotkey(self):
        for key in self.keys:
            keyboard.add_hotkey(key, self.__user_command, args=[key[-1]])

    def remove_all_hotkey(self):
        for key in self.keys:
            keyboard.remove_hotkey(key)

    def tutorial_screenshot(self, tuple_f: Tuple[str, str]):
        """
        tuple_f = (fname, fpath)
        """
        print(f'Missing {tuple_f[0]} picture')
        print(
            f'move mouse to the {tuple_f[0]} top left corner, then press hotkey "z+3"'
        )
        keyboard.wait('z+3')
        print(
            f'move mouse to the {tuple_f[0]} bottom right corner, then press hotkey "z+4"'
        )
        keyboard.wait('z+4')
        Shot(tuple_f[0], tuple_f[1], self.positions[2].coord,
             self.positions[3].coord).screenshot()

    def wait(self, hotkey: str):
        return keyboard.wait(hotkey)

    def process_idle(self) -> bool:
        return not (self.battle_job.is_alive()
                    or self.visit_room_job.is_alive()
                    or self.cork_shop_job.is_alive())

    def safe_exit(self):
        if self.battle_job.is_alive():
            self.battle_job.stop()
            self.battle_job.join()
        if self.monitor_job.is_alive():
            self.monitor_job.stop()
            self.monitor_job.join()
        if self.visit_room_job.is_alive():
            self.visit_room_job.stop()
            self.visit_room_job.join()
        if self.cork_shop_job.is_alive():
            self.cork_shop_job.stop()
            self.cork_shop_job.join()

        sleep(0.1)
        while self.kb.kbhit():
            self.kb.getch()
        print('goodbye!')
示例#15
0
def main():
    # Decorative purpose.
    init()
    # Nope, this is not the real otog.cf password XD.
    mydb = mysql.connector.connect(
        host="localhost",
        user="******",
        passwd="00000000",
        # Original for otog.cf was :
        # passwd='0000',
        database="OTOG",
    )

    myCursor = mydb.cursor(buffered=True)

    # for keybord interupt.
    print(ogogi + "Grader started. Waiting for submission...")
    kb = KBHit()

    while True:
        # Looking for keyboard interupt.
        if kb.kbhit():
            if kb.getch() == ":":
                # Do functions.
                print(ogogi + "Keyboard interupted. Entering command mode.")
                kb.set_normal_term()

                # Command mode
                while True:
                    cmd, args = cmdMode.run()
                    # Shutdown signal
                    if cmd == abb.INCMD["SHUTDOWN"]:
                        # Good-bye message
                        print(ogogi + "Bye")
                        exit(0)
                    elif cmd == abb.INCMD["RELOAD"]:
                        # Reload modules in args
                        for e in args:
                            if e == "grader":
                                print(
                                    abb.error
                                    + "'grader' itself cannot be reloaded. Please restart the program manually."
                                )
                            try:
                                importlib.reload(importlib.import_module(e))
                            except:
                                print(abb.error + "'" + e + "' cannot be reloaded.")
                    elif cmd == abb.INCMD["EXIT"]:
                        break

                kb.set_kbhit_term()
                print(ogogi + "Command mode exited. Continue waiting for submission.")

        myCursor.execute("SELECT * FROM Result WHERE status = 0 ORDER BY time")
        submission = myCursor.fetchone()
        if submission != None:
            print(abb.bold + Fore.GREEN + "\t--> recieved.\n" + Style.RESET_ALL)
            print(
                str(datetime.datetime.now().strftime("[ %d/%m/%y %H:%M:%S ]"))
                + " -----------------------------"
            )

            myCursor.execute(
                "SELECT * FROM Problem WHERE id_Prob = " + str(submission[3])
            )
            probInfo = myCursor.fetchone()

            # Submit result
            sql = "UPDATE Result SET result = %s, score = %s, timeuse = %s, status = 1, errmsg = %s WHERE idResult = %s"
            val = onRecieved(submission, probInfo, mydb)
            myCursor.execute(sql, val)
            print("---------------------------------------------------")
            print("\n" + ogogi + "Finished grading session. Waiting for the next one.")

        mydb.commit()
        time.sleep(config.gradingInterval)
示例#16
0
class GraspExecuter(object):
    def __init__(self):

        self._moveit_wrapper = MoveitWrapper()
        self._moveit_wrapper.init_moveit_commander()
        rospy.init_node('grasp_player')
        self._moveit_wrapper.setup()

        self._kin = boris_kinematics(root_link="left_arm_base_link")
        self._boris = BorisRobot(moveit_wrapper=self._moveit_wrapper)

        self._scene = self._moveit_wrapper.scene()
        self._planning_frame = self._moveit_wrapper.robot().get_planning_frame(
        )

        self._tf_buffer = tf2_ros.Buffer()
        self._listener = tf2_ros.TransformListener(self._tf_buffer)
        self._br = tf.TransformBroadcaster()

        self._scene.remove_world_object("table")
        self.add_table()

        self._solution = None
        self._grasp_waypoints = []
        self._pre_grasp_plan = None
        self._pre_grasp_plan2 = None
        self._grasp_arm_joint_path = None
        self._grasp_hand_joint_path = None

        self._post_grasp_plan = None

        self._grasp_service_client = GraspServiceClient()

        self._boris.set_control_mode(mode="joint_impedance",
                                     limb_name="left_arm")

        self._arm_traj_generator = MinJerkTrajHelper()
        self._hand_traj_generator = MinJerkTrajHelper()
        self._pre_grasp_traj_generator = MinJerkTrajHelper()
        self._post_grasp_traj_generator = MinJerkTrajHelper()

        self._scan_waypoints = np.load(
            "/home/earruda/Projects/boris_ws/src/boris-robot/boris_tools/scripts/scan_waypoints2.npy"
        )

        self._kbhit = KBHit()

    def scan_object(self):

        command = "rosservice call /grasp_service/acquire_cloud"
        self._boris.set_vel_accel_scaling("left_arm", 0.45, 0.45)
        for waypoint in self._scan_waypoints:

            # goto
            self._boris.goto_with_moveit("left_arm", waypoint)
            # scan
            process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
            output, error = process.communicate()
            print output

            if rospy.is_shutdown():
                break

        self._boris.set_vel_accel_scaling("left_arm", 0.25, 0.25)

    def remove_collision_object(self, name):

        self._scene.remove_world_object(name)
        rospy.sleep(0.5)

    def add_table(self):
        self.remove_collision_object("table")

        p = geometry_msgs.msg.PoseStamped()
        p.header.frame_id = self._planning_frame
        p.pose.position.x = 0.55
        p.pose.position.y = 0
        p.pose.position.z = -0.37  #-0.34
        p.pose.orientation.w = 1.0
        self._scene.add_box("table", p, (0.87, 1.77, 0.04))
        rospy.sleep(2)

    def add_object_guard(self, grasp_solution):
        self.remove_collision_object("guard")

        # print "Got solution: ", grasp_solution
        cloud_centroid = grasp_solution['cloud_centroid']
        min_pt = grasp_solution['cloud_min_pt']
        max_pt = grasp_solution['cloud_max_pt']

        p = geometry_msgs.msg.PoseStamped()
        p.header.frame_id = self._planning_frame
        p.pose.position.x = cloud_centroid[0]
        p.pose.position.y = cloud_centroid[1]
        p.pose.position.z = cloud_centroid[2]
        p.pose.orientation.w = 1.0
        self._scene.add_box("guard", p,
                            (max_pt[0] - min_pt[0], max_pt[1] - min_pt[1],
                             max_pt[2] - min_pt[2]))

        rospy.sleep(0.1)

    def get_solution(self):
        self._solution = self._grasp_service_client.get_grasp_solution()

        self.add_table()
        self.add_object_guard(self._solution)

        self._grasp_waypoints = solution2carthesian_path(
            self._solution, self._tf_buffer)

        group = self._moveit_wrapper.get_group("left_hand_arm")
        group.set_goal_joint_tolerance(0.001)  # default 0.0001
        group.set_goal_position_tolerance(0.01)  # default 0.0001
        group.set_goal_orientation_tolerance(0.001)  # default 0.001

        #self._grasp_waypoints[0].position.z += 0.15
        dx = self._grasp_waypoints[1].position.x - self._grasp_waypoints[
            0].position.x
        dy = self._grasp_waypoints[1].position.y - self._grasp_waypoints[
            0].position.y
        dz = self._grasp_waypoints[1].position.z - self._grasp_waypoints[
            0].position.z
        dir_vec = np.array([dx, dy, dz])
        dist = np.linalg.norm(dir_vec)
        dir_vec /= dist
        dir_vec *= 0.0  #0.05
        target = geometry_msgs.msg.Pose()

        for n_tries in range(50):
            rand_offset_x = np.random.randn() * np.sqrt(0.0001)
            rand_offset_y = np.random.randn() * np.sqrt(0.0001)
            rand_offset_z = np.maximum(
                0.15 + np.random.randn() * np.sqrt(0.0001), 0.10)
            target.position.x = self._grasp_waypoints[0].position.x - dir_vec[
                0] + rand_offset_x
            target.position.y = self._grasp_waypoints[0].position.y - dir_vec[
                1] + rand_offset_y

            print rand_offset_x, rand_offset_y, rand_offset_z
            target.position.z = self._grasp_waypoints[
                0].position.z + rand_offset_z
            target.orientation = self._grasp_waypoints[0].orientation

            self._pre_grasp_plan = self._boris.get_moveit_cartesian_plan(
                "left_hand_arm", target)

            is_executable = len(
                self._pre_grasp_plan.joint_trajectory.points) > 0

            if is_executable:
                break

        # if is_executablediag_add:
        #     # current_angles = self._boris.angles("left_arm")

        #     # joint_positions = self._pre_grasp_plan.joint_trajectory.points[-1].positions
        #     # self._moveit_wrapper.set_start_state("left_hand_arm", self._boris.joint_names("left_arm"), joint_positions)
        #     # rospy.sleep(1.0)
        #     self._grasp_arm_joint_path, fraction = self._boris.compute_cartesian_path_moveit("left_hand_arm",self._grasp_waypoints[:3])
        #     # Set back to current
        #     # self._moveit_wrapper.set_start_state("left_hand_arm", self._boris.joint_names("left_arm"), current_angles)
        #     is_executable = fraction >= 0.85

        if is_executable:

            self._pre_grasp_pose = msg2Transform3(self._grasp_waypoints[0])

            print "Hand joints %d ", len(
                self._pre_grasp_plan.joint_trajectory.points)
            self._pre_grasp_traj_generator.set_waypoints(
                self._pre_grasp_plan.joint_trajectory)

            rospy.loginfo(
                "Pre grasp plan length %d" %
                (len(self._pre_grasp_plan.joint_trajectory.points), ))
            rospy.loginfo("Pre grasp plan total time %f" %
                          (self._pre_grasp_plan.joint_trajectory.points[-1].
                           time_from_start.to_sec(), ))

        # state = self._moveit_wrapper.robot().get_current_state()

        # print "Robot state"
        # print state

        #group = self._moveit_wrapper.get_group("left_hand_arm")

        return is_executable

    def update_step(self, step, time_steps, incr):
        step = step + incr

        if step >= len(time_steps):
            step = len(time_steps) - 1
        elif step < 0:
            step = 0

        return step

    def goto_pregrasp(self):

        self._boris.execute_moveit_plan("left_hand_arm", self._pre_grasp_plan)

    def plan_grasp(self):

        self.remove_collision_object("guard")
        self.remove_collision_object("table")
        # self._pre_grasp_plan2, fraction2 = self._boris.compute_cartesian_path_moveit("left_hand_arm",[self._grasp_waypoints[:1]])
        self._grasp_arm_joint_path, fraction = self._boris.compute_cartesian_path_moveit(
            "left_hand_arm",
            self._grasp_waypoints[:3],
            eef_step=0.01,
            jump_threshold=50.0)
        # Set back to current
        # self._moveit_wrapper.set_start_state("left_hand_arm", self._boris.joint_names("left_arm"), current_angles)
        is_executable = fraction >= 0.95

        ## try to plan final goal in case cartesian path
        if not is_executable:
            rospy.logwarn(
                "Failed to plan cartesian path passing through all waypoints. Trying last one only."
            )
            self._grasp_arm_joint_path = self._boris.get_moveit_cartesian_plan(
                "left_hand_arm", self._grasp_waypoints[2])
            is_executable = len(
                self._grasp_arm_joint_path.joint_trajectory.points) > 0

        if not is_executable:

            rospy.logwarn(
                "Grasp not executable, maybe try again or try new grasp")

        else:

            self._grasp_arm_joint_path = self._grasp_arm_joint_path.joint_trajectory

            self._arm_traj_generator.set_waypoints(self._grasp_arm_joint_path)

            rospy.loginfo("Grasp path length %d" %
                          (len(self._grasp_arm_joint_path.points), ))
            rospy.loginfo("Grasp path total time %f" %
                          (self._grasp_arm_joint_path.points[-1].
                           time_from_start.to_sec(), ))

            total_time = self._grasp_arm_joint_path.points[
                -1].time_from_start.to_sec()
            self._grasp_hand_joint_path = solution2hand_joint_path(
                self._solution, self._boris, total_time)
            print "Trajectory hand ", len(
                self._solution['joint_trajectory'][0])
            self._hand_traj_generator.set_waypoints(
                self._grasp_hand_joint_path)
            rospy.loginfo("Hand path length %d" %
                          (len(self._grasp_hand_joint_path.points), ))
            rospy.loginfo("Hand path total time %f" %
                          (self._grasp_hand_joint_path.points[-1].
                           time_from_start.to_sec(), ))

        return is_executable

    def plan_post_grasp(self):

        self.remove_collision_object("guard")
        self.remove_collision_object("table")
        self._grasp_waypoints[3].position.z += 0.08
        self._post_grasp_plan = self._boris.get_moveit_cartesian_plan(
            "left_hand_arm", self._grasp_waypoints[3])
        # Set back to current
        # self._moveit_wrapper.set_start_state("left_hand_arm", self._boris.joint_names("left_arm"), current_angles)
        is_executable = len(self._post_grasp_plan.joint_trajectory.points) > 0
        if not is_executable:

            rospy.logwarn(
                "Grasp not executable, maybe try again or try new grasp")

        else:

            self._post_grasp_plan = self._post_grasp_plan.joint_trajectory

            self._post_grasp_traj_generator.set_waypoints(
                self._post_grasp_plan)

            rospy.loginfo("Grasp path length %d" %
                          (len(self._post_grasp_plan.points), ))
            rospy.loginfo(
                "Grasp path total time %f" %
                (self._post_grasp_plan.points[-1].time_from_start.to_sec(), ))

        return is_executable

    def execute_pre_grasp(self):

        rospy.loginfo("Pre Grasp Execution!!")
        key = None
        time_steps = np.linspace(0.0, 1.0, 600)
        step = 0

        def exec_step(step):

            joint_goal = self._pre_grasp_traj_generator.get_point_t(
                time_steps[step])

            print "CurrArmState:", self._boris.angles('left_arm')
            print "ArmGoal[%.2f]: " % (
                time_steps[step], ), joint_goal.time_from_start.to_sec(
                ), " step=", step, " pos: ", joint_goal.positions
            cmd = self._boris.cmd_joint_angles(angles=joint_goal.positions,
                                               execute=True)
            # self._boris.goto_joint_angles('left_hand',hand_goal.positions)

        loop_rate = rospy.Rate(30.0)
        play_forward = False
        play_backward = False
        while not rospy.is_shutdown() and key != 'q':

            if self._kbhit.kbhit():
                key = self._kbhit.getch()

            if key == '.':

                rospy.loginfo("Step %d" % (step, ))
                step = self.update_step(step, time_steps, 1)
                exec_step(step)

            if key == ',':

                step = self.update_step(step, time_steps, -1)
                exec_step(step)

                rospy.loginfo("Step %d" % (step, ))

            if key == ']':
                play_forward = True
                play_backward = False
                rospy.loginfo("Playing forward")
            elif key == '[':
                play_forward = False
                play_backward = True
                rospy.loginfo("Playing backward")
            elif key == 'p' and (play_forward or play_backward):
                play_forward = False
                play_backward = False
                rospy.loginfo("Halt open loop playing")

            if play_forward:
                step = self.update_step(step, time_steps, 1)
                exec_step(step)
                rospy.loginfo("Step %d" % (step, ))
            elif play_backward:
                step = self.update_step(step, time_steps, -1)
                exec_step(step)
                rospy.loginfo("Step %d" % (step, ))

            loop_rate.sleep()
        rospy.loginfo("Leaving Pre Grasp Execution!!")

    def execute_grasp(self):

        rospy.loginfo("Grasp Execution!!")
        key = None

        rospy.loginfo("Grasp path length %d" %
                      (len(self._grasp_arm_joint_path.points), ))
        rospy.loginfo(
            "Grasp path total time %f" %
            (self._grasp_arm_joint_path.points[-1].time_from_start.to_sec(), ))
        time_steps = np.linspace(0.0, 1.0, 300)
        time_steps_arm = np.linspace(0.0, 1.0, 100)
        step = 0
        step_arm = 0

        def step_grasp(step, arm_step):

            joint_goal = self._arm_traj_generator.get_point_t(
                time_steps_arm[arm_step])
            hand_goal = self._hand_traj_generator.get_point_t(time_steps[step])

            print "HandGoal: ", hand_goal.time_from_start.to_sec(
            ), " step=", step, " pos: ", hand_goal.positions
            print "CurrArmState:", self._boris.angles('left_arm')
            print "ArmGoal: ", hand_goal.time_from_start.to_sec(
            ), " step=", step, " pos: ", joint_goal.positions
            cmd = self._boris.cmd_joint_angles(angles=joint_goal.positions,
                                               execute=True)
            self._boris.goto_joint_angles('left_hand', hand_goal.positions,
                                          hand_goal.time_from_start.to_sec())

        loop_rate = rospy.Rate(30.0)
        play_forward = False
        play_backward = False
        while not rospy.is_shutdown() and key != 'q':

            key = None
            if self._kbhit.kbhit():
                key = self._kbhit.getch()

            if key == '.':
                step = self.update_step(step, time_steps, 1)
                step_arm = self.update_step(step_arm, time_steps_arm, 1)
                rospy.loginfo("Step %d" % (step, ))

                step_grasp(step, step_arm)

            if key == ',':

                step = self.update_step(step, time_steps, -1)
                step_arm = self.update_step(step_arm, time_steps_arm, -1)
                rospy.loginfo("Step %d" % (step, ))

                step_grasp(step, step_arm)

            wrench = self._boris.wrench()
            force = np.array([
                wrench.wrench.force.x, wrench.wrench.force.y,
                wrench.wrench.force.z
            ])

            # If force is larger than 5 we stop
            force_norm = np.linalg.norm(force)

            if force_norm >= 15.0:
                key = '['
                rospy.logwarn("External forces too high %.3f" % (force_norm, ))
            # else:
            #     rospy.loginfo("External forces %.3f"%(force_norm,))

            if key == ']':
                play_forward = True
                play_backward = False
                rospy.loginfo("Playing forward")
            elif key == '[':
                play_forward = False
                play_backward = True
                rospy.loginfo("Playing backward")
            elif key == 'p' and (play_forward or play_backward):
                play_forward = False
                play_backward = False
                rospy.loginfo("Halt open loop playing")
            elif key == 'c':
                self._boris.goto_joint_angles('left_hand', [1.0], 0.01)
            elif key == 'o':
                self._boris.goto_joint_angles('left_hand', [0.0], 0.01)

            if play_forward:
                step = self.update_step(step, time_steps, 1)
                step_arm = self.update_step(step_arm, time_steps_arm, 1)
                step_grasp(step, step_arm)
                rospy.loginfo("Step %d" % (step, ))
            elif play_backward:
                step = self.update_step(step, time_steps, -1)
                step_arm = self.update_step(step_arm, time_steps_arm, -1)
                step_grasp(step, step_arm)
                rospy.loginfo("Step %d" % (step, ))

            loop_rate.sleep()
        rospy.loginfo("Leaving Grasp Execution!!")

    def step_execution(self, step, time_steps, trajectory_generator,
                       command_func):

        joint_goal = trajectory_generator.get_point_t(time_steps[step])
        command_func(joint_goal.positions)

    def execute_post_grasp(self):

        rospy.loginfo("Post Grasp Execution!!")
        key = None
        time_steps = np.linspace(0.0, 1.0, 200)
        #time_steps_arm = np.linspace(0.0,1.0,100)
        step = 0

        loop_rate = rospy.Rate(30.0)
        play_forward = False
        play_backward = False
        while not rospy.is_shutdown() and key != 'q':

            key = None
            if self._kbhit.kbhit():
                key = self._kbhit.getch()

            if key == '.':
                step = self.update_step(step, time_steps, 1)
                rospy.loginfo("Step %d" % (step, ))

                self.step_execution(step, time_steps,
                                    self._post_grasp_traj_generator,
                                    self._boris.cmd_joint_angles)

            if key == ',':

                step = self.update_step(step, time_steps, -1)
                rospy.loginfo("Step %d" % (step, ))

                self.step_execution(step, time_steps,
                                    self._post_grasp_traj_generator,
                                    self._boris.cmd_joint_angles)

            if key == ']':
                play_forward = True
                play_backward = False
                rospy.loginfo("Playing forward")
            elif key == '[':
                play_forward = False
                play_backward = True
                rospy.loginfo("Playing backward")
            elif key == 'p' and (play_forward or play_backward):
                play_forward = False
                play_backward = False
                rospy.loginfo("Halt open loop playing")

            if play_forward:
                step = self.update_step(step, time_steps, 1)
                self.step_execution(step, time_steps,
                                    self._post_grasp_traj_generator,
                                    self._boris.cmd_joint_angles)
                rospy.loginfo("Step %d" % (step, ))
            elif play_backward:
                step = self.update_step(step, time_steps, -1)
                self.step_execution(step, time_steps,
                                    self._post_grasp_traj_generator,
                                    self._boris.cmd_joint_angles)

                rospy.loginfo("Step %d" % (step, ))

            loop_rate.sleep()

        rospy.loginfo("Leaving Post Grasp Execution!!")

    def run(self):

        rospy.loginfo("Running!!")

        loop_rate = rospy.Rate(30)
        has_solution = False
        has_plan = False
        has_post_grasp_plan = False
        while not rospy.is_shutdown():

            key = self._kbhit.getch()

            if key == "0":

                has_solution = self.get_solution()
                rospy.loginfo("Queried solution %s" % (has_solution, ))

            elif key == "1" and has_solution:
                #self.goto_pregrasp()
                self.execute_pre_grasp()
            elif key == "2" and has_solution:
                if has_plan:
                    self.execute_grasp()
                else:
                    rospy.logwarn(
                        "No grasp plan has been generated. Press 9 to attempt to generate one."
                    )
            elif key == "3" and has_solution:
                if has_post_grasp_plan:
                    self.execute_post_grasp()
                else:
                    rospy.logwarn(
                        "No post-grasp plan has been generated. Press 8 to attempt to generate one."
                    )
            elif key == "9":
                has_plan = self.plan_grasp()
            elif key == "8":
                has_post_grasp_plan = self.plan_post_grasp()
            elif key == "r":
                self.remove_collision_object("table")
                self.remove_collision_object("guard")
            elif key == "t":
                self.add_table()
            elif key == "g" and has_solution:
                self.add_object_guard(self._solution)
            elif key == "e":
                self.remove_collision_object("guard")
            elif key == "s":
                self.scan_object()
            elif not has_solution:

                rospy.logwarn("No grasp solution. Press 0.")

            loop_rate.sleep()
示例#17
0
pub_port = "5555"
sub_port = "5556"
topic = "10001"
topicfilter = "10001"
context = zmq.Context()

pub_socket = context.socket(zmq.PUB)
pub_socket.bind("tcp://*:%s" % pub_port)
sub_socket = context.socket(zmq.SUB)
sub_socket.connect("tcp://localhost:%s" % sub_port)
sub_socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

while True:
    while not mode_toggle:
        print "Receiving:"
        if kb.getch() == 'r':
            msg = sub_socket.recv()
            print 'B: ' + msg
            time.sleep(1)
            mode_toggle = not mode_toggle
            break
        if kb.getch() == 'q':
            mode_toggle = not mode_toggle
            break

    while mode_toggle:
        print "Sending:"
        if kb.getch() == 'z':
            message = raw_input('>: ')
            pub_socket.send("%s %s" % (topic, message))
            mode_toggle = not mode_toggle
示例#18
0
    developer_mode = False

fruits = []
snake = create_snake(width, height)
create_apple(width, height, fruits, snake)
direction = (1, 0)
print(field_to_text(width, height, snake, fruits) + '\n')

p = time.time()
kb = KBHit()
while True:
    c = time.time()
    time_delta = 0.001 if developer_mode else 0.1
    if c - p < time_delta:
        time.sleep(time_delta - (c - p))
    p = time.time()

    if kb.kbhit():
        c = kb.getch()
        if ord(c) == 27:  # ESC
            break
        elif ord(c) in directions_codes:
            direction = directions_codes[ord(c)]
        elif developer_mode:
            direction = (0, 0)
        if not update_screen(width, height, snake, fruits, direction):
            break
    elif not developer_mode:
        if not update_screen(width, height, snake, fruits, direction):
            break
    def run(self):
        kb = KBHit()      
        selectedData = []
        dataToAverage = []        
        print('Hit ESC to exit')
        while True:
            if kb.kbhit():
                c = kb.getch()                
                if ord(c) == 27: # ESC
                    kb.set_normal_term() 
                    print "Quitting!"
                    os._exit(0)   
            now = time.time()
            due = now - self.parent.offset
            search_from = self.parent.index - 1
            if search_from == - 1:
                search_from = self.parent.buffer_size - 1
            timestamp = 0
            nextTimestamp = 0
            self.waitForNewData = 0.5
            self.parent.mutex.acquire()

            lastjvalue = 0

            dataArray = []

            for theid in range(self.parent.channel_count):

                data = self.parent.outbuffers[int(theid)][self.parent.index]
                
                for i in range(search_from, search_from - self.parent.buffer_size, -1):
                    j = i if i >= 0 else i + self.parent.buffer_size
                    timestamp = self.parent.timestamp_buffer[j]
                    if timestamp is not None and timestamp <= due:
                        data = self.parent.outbuffers[int(theid)][j]
                        lastjvalue = j
                        if(j<self.parent.buffer_size-2):
                            nextTimestamp = self.parent.timestamp_buffer[j+1]
                        else:
                            nextTimestamp = self.parent.timestamp_buffer[0]
                        break
                if data is not None:                                
                    dataArray.append(data)
            
            #print "data array: ", dataArray     
                         
                
            for f in config.streams:
                stream = f['stream'] 
                if len(dataArray) > stream:  
                    #print "stream = ", stream,  dataArray[stream]                             
                    if 'scale' in f:
                        dataArray[stream] = self.format.scale(dataArray[stream], f['scale'])                  
                    if 'type' in f and f['type'] == int: 
                        #msgString += str(int(dataArray[stream]))
                        selectedData.append(int(dataArray[stream]))                      
                    else:   
                         #msgString += str(dataArray[stream]) 
                         selectedData.append(dataArray[stream]) 
 
                    if len(selectedData) == len(config.streams) :  
                        self.sendMessage(selectedData)                                                                 
                        selectedData = []          

            if timestamp is not None and nextTimestamp is not None:
                waitTime = nextTimestamp - timestamp
                if waitTime > 0:
                    time.sleep(waitTime)
                else:
                    print "timing out waiting for new data - time < 0"
                    time.sleep(self.waitForNewData)
            else:
                print "timing out waiting for new data - time or nextTime is None"
                time.sleep(self.waitForNewData)
            self.parent.mutex.release()
示例#20
0
## Main Control Loop ##
#######################

kb = KBHit()

waypoint_speed = 0.0

while not abort_flag:
    # If there is a goal pending, set it on the arm and clear the flag
    arm.update()
    arm.send()

    t = time()
    char = None
    if kb.kbhit():
        char = kb.getch()

    if char == '.':
        waypoint_speed += 0.1
        if waypoint_speed > 1.0:
            waypoint_speed = 1.0
    elif char == ',':
        waypoint_speed -= 0.1
        if waypoint_speed < -1.0:
            waypoint_speed = -1.0

    # Check for quit
    if char is not None and ord(char) == 27:  # Esc
        abort_flag = True
        break
示例#21
0
def main():
    random.seed(time.time())

    # Initialise colorama
    init()

    # Clear screen
    print(chr(27) + '[2j')
    print('\033c')
    print('\x1bc')

    # Get terminal size
    (ncols, nlines) = shutil.get_terminal_size()

    # Initialise screen
    screen = Window(0, 1, ncols, nlines - 1, f"{config.bkgd} ")

    # Initialise keyboard
    kb = KBHit()

    # Create and draw the paddle
    paddle = Paddle(((ncols - 1) - config.paddle["dim"][0]) // 2, nlines - 4,
                    screen)

    last_update = 0
    start = time.time()
    score = 0
    lives = 3
    curr_level = 1

    # List to store shooters
    shooters = [None, None]
    while curr_level <= 3:
        # Create and draw bricks
        boss = None
        if curr_level == 1:
            bricks, powerups = levels.level_one(screen)
        elif curr_level == 2:
            bricks, powerups = levels.level_two(screen)
        elif curr_level == 3:
            bricks, powerups = levels.level_three(screen)
            boss = Boss(ncols // 2, 5, screen)
        else:
            sys.exit()

        if lives == 0:
            break

        while lives:
            # Reset paddle location
            paddle.x = ((ncols - 1) - config.paddle["dim"][0]) // 2
            paddle.powerup = None

            # Create and draw the ball
            balls = [
                Ball(random.randrange(paddle.x, paddle.x + paddle.width),
                     nlines - 5, list(config.ball["speed"]), 1, screen)
            ]

            # List to store bullets
            bullets = []
            shoot_paddle = [0]

            # List to store bombs
            bombs = []

            tick = 0
            while len(balls):
                if (time.time() - last_update > config.tick_interval):
                    tick += 1
                    for i in range(ncols):
                        print(f"{Cursor.POS(1+i, 1)}{Back.BLACK} ", end='')

                    statusline = f"{Cursor.POS(1, 1)}Level: {curr_level}   "
                    statusline += f"Score: {score}   "
                    statusline += f"Time: {int(time.time() - start)}   "
                    statusline += f"Lives: {lives}   "
                    statusline += f"Shoot Paddle: {int(shoot_paddle[0] * config.tick_interval)}   "
                    if boss:
                        statusline += "Boss Health: ["
                        for i in range(0, boss.health, 10):
                            statusline += "•"
                        for i in range(0, 100 - boss.health, 10):
                            statusline += " "
                        statusline += "]"
                    print(statusline, end='')

                    last_update = time.time()

                    change_level = False
                    direction = 0
                    if kb.kbhit():
                        c = kb.getch()
                        if ord(c) == 27:
                            sys.exit(0)

                        if c == 'a':
                            direction = -1
                        elif c == 'd':
                            direction = 1
                        elif c == ' ':
                            # Activate balls
                            for ball in balls:
                                ball.paused = False
                        elif c == '1' or c == '2' or c == '3':
                            curr_level = int(c) if curr_level != 3 else 4
                            change_level = True
                            break

                    # Create new bullets if needed
                    shoot_paddle[0] = max(0, shoot_paddle[0] - 1)
                    if shoot_paddle[0] and shoot_paddle[0] % config.bullet[
                            "rate"] == 0:
                        bullets.append(
                            Bullet(max(paddle.x, 0), paddle.y,
                                   config.bullet["speed"], screen))
                        bullets.append(
                            Bullet(
                                min(paddle.x + paddle.width,
                                    screen.get_screen_size()[1] - 1), paddle.y,
                                config.bullet["speed"], screen))

                    # Create bomb if needed
                    if boss and tick % config.bomb["rate"] == 0:
                        bombs.append(
                            Bomb(boss.x + 5, boss.y + 3, config.bomb["speed"],
                                 screen))

                    # Create shooters if needed
                    if shoot_paddle[0] and not shooters[0]:
                        shooters[0] = Object(paddle.x, paddle.y - 1, 1, 1,
                                             config.paddle["color"], screen)
                    if shoot_paddle[0] and not shooters[1]:
                        shooters[1] = Object(paddle.x + paddle.width - 1,
                                             paddle.y - 1, 1, 1,
                                             config.paddle["color"], screen)

                    # Create brick layer on boss level if health is 50
                    if boss and boss.health == 80 and not boss.done[0]:
                        bricks.append([])
                        brick_count = screen.get_screen_size()[1] // \
                            (config.brick["dim"][0] + 5)
                        for i in range(brick_count):
                            bricks[1].append(
                                Brick(i * (config.brick["dim"][0] + 5), 9, 1,
                                      screen))
                        boss.done[0] = True

                    # Create brick layer on boss level if health is 20
                    if boss and boss.health == 20 and not boss.done[1]:
                        brick_count = screen.get_screen_size()[1] // \
                            (config.brick["dim"][0] + 5)
                        bricks.append([])
                        for i in range(brick_count):
                            bricks[2].append(
                                Brick(i * (config.brick["dim"][0] + 5), 13, 1,
                                      screen))
                        boss.done[1] = True

                    # Clear screen
                    screen.clear()

                    # Move the paddle
                    paddle.move(direction, balls)

                    # Move the powerups
                    to_delete = []
                    for powerup in powerups:
                        object = None
                        if powerup.type == "paddle":
                            object = paddle
                        elif powerup.type == "ball":
                            object = balls
                        else:
                            object = shoot_paddle

                        if not powerup.move(paddle, object, tick):
                            to_delete.append(powerup)

                    powerups = [
                        powerup for powerup in powerups
                        if powerup not in to_delete
                    ]

                    # Move the ball
                    to_delete = []
                    for ball in balls:
                        delete, d_score = ball.move(bricks, paddle, boss)
                        if not delete:
                            to_delete.append(ball)

                        score += d_score

                    balls = [ball for ball in balls if ball not in to_delete]

                    # Delete shooters if powerup is over
                    if shoot_paddle[0] == 0:
                        shooters = [None, None]

                    # Move the bullets
                    to_delete = []
                    for bullet in bullets:
                        delete, d_score = bullet.move(bricks)
                        if not delete:
                            to_delete.append(bullet)

                        score += d_score

                    bullets = [
                        bullet for bullet in bullets if bullet not in to_delete
                    ]

                    # Move the bombs
                    to_delete = []
                    lose_life = False
                    for bomb in bombs:
                        delete, lose_life = bomb.move(paddle)
                        if not delete:
                            to_delete.append(bomb)
                        if lose_life:
                            break

                    if lose_life:
                        break

                    bombs = [bomb for bomb in bombs if bomb not in to_delete]

                    # Move the boss
                    if boss:
                        boss.move(paddle.x + paddle.width // 2)

                    # Move the shooter
                    if shooters[0]:
                        shooters[0].x = paddle.x
                    if shooters[1]:
                        shooters[1].x = paddle.x + paddle.width - 1

                    # Update bricks
                    for layer in bricks:
                        for brick in layer:
                            brick.rainbow(tick)
                            # Don't move bricks on boss level
                            if curr_level < 3:
                                brick.move(tick)
                            if brick.y + brick.height > paddle.y:
                                sys.exit()
                            brick.update()

                    # Update paddle
                    paddle.update()

                    # Update shooters
                    for shooter in shooters:
                        if shooter:
                            shooter.update()

                    # Update powerups
                    for powerup in powerups:
                        powerup.update()

                    # Update ball
                    for ball in balls:
                        ball.update()

                    # Update bullets
                    for bullet in bullets:
                        bullet.update()

                    # Update bombs
                    for bomb in bombs:
                        bomb.update()

                    # Boss update
                    if boss:
                        boss.update()

                    screen.draw()

                    # Check if all breackable bricks are broken on non boss levels
                    if curr_level < 3:
                        change_level = True
                        for layer in bricks:
                            for brick in layer:
                                if brick._strength != 4:
                                    change_level = False
                                    break
                            if not change_level:
                                break
                    else:
                        if boss.health <= 0:
                            change_level = True

                    if change_level:
                        curr_level += 1
                        break

            if change_level:
                break

            lives -= 1
示例#22
0
                        nb_epoch=10,
                        verbose=1,
                        validation_data=(X_val, Y_val),
                        callbacks=[early_stopping])

    # most recent loss hist.history["loss"][-1]
    r, rmse, _ = learnLib.assess_2dmodel(model, X_val, Y_val)
    models[args] = r, rmse
    print("Model r: ", r)
    print("Model rmse: ", rmse)
    if rmse < prevLoss:
        prevLoss = rmse
        maxModel = model
    while kb.kbhit():
        try:
            if "q" in kb.getch():
                print("quiting due to user pressing q")
                stop = True
        except UnicodeDecodeError:
            pass

    if stop:
        break

del X_val

X_test, Y_test = ns.getTestData()

X_test = X_test[:, :, :, 0:50]
Y_test = repeat_n_times(Y_test, repeat_cnt)
示例#23
0
class Game:
    """
    The actual game and rendering related functions
    """

    _refresh_time = 1 / FRAME_RATE

    # DECLARING EVERYTHING
    def __init__(self):
        coloroma_init(autoreset=False)
        self.__score = 0
        self.__last_level_score = 0
        self.__ticks = 0
        self.__level_ticks = 0
        self.__level = 1
        self.__lives_used = 0
        self.__paddle = Paddle()
        self.__bricks_broken = 0
        self.__balls = [Ball(paddle=self.__paddle)]
        self.__cnt_active_balls = 0
        self.__cnt_active_bricks = 100
        self.__game_status = GAME_END
        self.__powerups = []
        self.__kb = KBHit()
        self.__explode_ids = [x for x in range(8, 14)]
        self.__explode_nbrs_ids = [7, 14, 28, 29, 30, 31, 32, 33]
        self.__brick_structure_y_fall = 0
        self.__fall_bricks = 0
        self.__bullets = []
        self.__ufo = Ufo()
        self.__ufo_bombs = []
        self.__ufo_bricks = []
        self.__map_position_to_bricks = []

        clear_terminal_screen()
        self._draw_bricks()
        self._loop()

    # DRAW THE OBJECT IN GIVEN RANGE
    def _draw_obj(self, coord, obj):
        y1 = 0
        for y in range(coord[1], coord[1] + coord[3]):
            x1 = 0
            for x in range(coord[0], coord[0] + coord[2]):
                # (x, y) wrt frame (x1, y1) wrt obj
                if 0 <= x < FRAME_WIDTH and 0 <= y < FRAME_HEIGHT:
                    self.__frame[y][x] = obj[y1][x1]
                x1 += 1
            y1 += 1

    # TOP INFO BAR
    def _top_info_print(self):
        s = f"SCORE:{self.__score}       "[:13]
        s += f"LIVES REMAINING:{LIVES - self.__lives_used}       "[:24]
        s += f"TIME: {self.__level_ticks//10}       "[:14]
        s += f"LEVEL: {self.__level}        "
        if self.__paddle.check_have_bullet_powerup():
            # (self.__ticks - self.__paddle.get_powerup_start_time())//10 >= POWERUP_LIFE
            # (X - S) // 10 = POWERUP_LIFE
            # X = S + 10*POWERUP_LIFE
            # ANSWER = X - NOW.
            x = self.__paddle.get_powerup_start_time() + 10 * POWERUP_LIFE
            s += f"POWERUP TIME LEFT: {x - self.__ticks}        "

        if self.__level == UFO_LEVEL:
            s += f"UFO HEALTH: {self.__ufo.get_health()}        "
            s += f"Press q to quit."
        else:
            s += f"Press q to quit."
        self.__frame[1][2:2 + len(s)] = [
            Style.BRIGHT + Fore.WHITE + Back.LIGHTBLACK_EX + x for x in s
        ]

    # DRAW THE BRICK STRUCTURE
    def _draw_bricks(self):
        self.__bricks = []
        y = BRICK_STRUCTURE_Y

        if self.__level == UFO_LEVEL:
            y += 7

        dummy_row = [
            "X" for i in range(len(BRICK_STRUCTURE[self.__level - 1][0]) + 2)
        ]

        self.__map_position_to_bricks = [dummy_row]

        for i, row in enumerate(BRICK_STRUCTURE[self.__level - 1]):
            x = BRICK_STRUCTURE_X
            row_bricks = ["X"]
            for j, brick_type in enumerate(row):
                if brick_type == " ":
                    row_bricks.append("X")
                    x += BRICK_WIDTH
                    continue
                if int(brick_type) == WEAK_BRICK_ID:
                    self.__bricks.append(WeakBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == NORMAL_BRICK_ID:
                    self.__bricks.append(NormalBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == STRONG_BRICK_ID:
                    self.__bricks.append(StrongBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == UNBREAKABLE_BRICK_ID:
                    self.__bricks.append(UnbreakableBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == EXPLODING_BRICK_ID:
                    self.__bricks.append(ExplodingBrick(x, y, i + 1, j + 1))
                elif int(brick_type) == RAINBOW_BRICK_ID:
                    self.__bricks.append(RainbowBrick(x, y, i + 1, j + 1))

                row_bricks.append(self.__bricks[-1])
                x += BRICK_WIDTH

            row_bricks.append("X")
            self.__map_position_to_bricks.append(row_bricks)
            y += BRICK_HEIGHT

        self.__map_position_to_bricks.append(dummy_row)
        # print(len(self.__map_position_to_bricks), len(self.__map_position_to_bricks[0]), len(B))
        # input()

    # HOLD SCREEN. BETWEEN LIFE LOSTS
    def _draw_hold_screen(self, message=""):
        self.__frame = np.array([[
            Style.BRIGHT + Fore.WHITE + Back.LIGHTBLACK_EX + " "
            for _ in range(FRAME_WIDTH)
        ] for _ in range(FRAME_HEIGHT)])
        self._top_info_print()
        s = message + " Press ENTER to continue."
        self.__frame[FRAME_HEIGHT // 2][50:50 + len(s)] = [x for x in s]
        sra = str(Style.RESET_ALL)
        # get the grid string
        grid_str = "\n".join(
            [sra + " " * 4 + "".join(row) + sra for row in self.__frame])
        # displaying the grid
        os.write(1, str.encode(grid_str))

    # DRAW ONE FRAME
    def _draw(self):
        # drawing the grid
        self.__frame = np.array([[
            Style.BRIGHT + Fore.WHITE + Back.LIGHTBLACK_EX + " "
            for _ in range(FRAME_WIDTH)
        ] for _ in range(FRAME_HEIGHT)])
        self.__bricks_broken = 0

        # TOP INFO BAR
        self._top_info_print()

        # PADDLE
        self._draw_obj(self.__paddle.get_box(), self.__paddle.get_obj())

        # UFO
        if self.__level == UFO_LEVEL:
            if self.__ufo.check_active():
                self._draw_obj(self.__ufo.get_box(), self.__ufo.get_obj())

        # UFO BRICKS
        for ufo_brick in self.__ufo_bricks:
            if not ufo_brick.check_active():
                continue
            self._draw_obj(ufo_brick.get_box(), ufo_brick.get_obj())

        # BRICKS
        for brick in self.__bricks:
            if brick.check_active():
                self._draw_obj(brick.get_box(), brick.get_obj())
            else:
                self.__bricks_broken += 1

        #BULLETS
        for bullet in self.__bullets:
            if bullet.check_active():
                self._draw_obj(bullet.get_box(), bullet.get_obj())

        #BOMBS
        for bomb in self.__ufo_bombs:
            if bomb.check_active():
                self._draw_obj(bomb.get_box(), bomb.get_obj())

        # BALLS
        for ball in self.__balls:
            if ball.check_active():
                self._draw_obj(ball.get_box(), ball.get_obj())

        # POWERUPS
        for powerup in self.__powerups:
            if powerup.check_active():
                self._draw_obj(powerup.get_box(), powerup.get_obj())

        sra = str(Style.RESET_ALL)
        grid_str = "\n".join(
            [sra + " " * 4 + "".join(row) + sra for row in self.__frame])
        os.write(1, str.encode(grid_str))

    # TAKE INPUT FROM KBHIT
    def _get_input(self):
        c = ""
        if self.__kb.kbhit():
            c = self.__kb.getch()
        self.__kb.flush()
        return c

    # HANDLE THE INPUT TAKEN
    def _handle_input(self, key):
        key = key.lower()
        if key == 'q':
            self.Quit()
        if key in "ad":
            if self.__level == UFO_LEVEL:
                self.__paddle.handle_key_press(key, self.__ufo)
                for idx, brick in enumerate(self.__ufo_bricks):
                    brick.set_x(self.__ufo.get_x() + idx * BRICK_WIDTH)
            else:
                self.__paddle.handle_key_press(key)
        if key in " ad":
            for ball in self.__balls:
                ball.handle_key_press(self.__paddle, key)
        if key == 'l':
            self.change_level()

    # DIVIDE THE BALL INTO TWO
    def divide_ball(self, ball):
        new_ball = Ball()
        x, y = ball.get_position()
        vx, vy = ball.get_velocity()
        if vx != 0:
            new_ball.set_velocity(vx * -1, vy)
        else:
            new_ball.set_velocity(-1, vy)
        new_ball.set_position(x, y)
        new_ball.set_state(BALL_RELEASED)
        return new_ball

    # DIFFRENT COLLISIONS
    def _ball_and_wall(self):
        for ball in self.__balls:
            if ball.check_active():
                ball.check_wall_collission()

    def _ball_and_paddle(self):
        for ball in self.__balls:
            if ball.check_active():
                if ball.check_paddle_collission(
                        self.__paddle) and self.__fall_bricks:
                    self.__brick_structure_y_fall += 1
                    if self.__brick_structure_y_fall + BRICK_STRUCTURE_Y + len(
                            BRICK_STRUCTURE[self.__level -
                                            1]) * BRICK_HEIGHT == PADDLE_Y:
                        self.Quit()

    def _bomb_and_paddle(self):
        for bomb in self.__ufo_bombs:
            if bomb.check_active():
                if bomb.check_paddle_collission(self.__paddle):
                    self.__cnt_active_balls = 0

    def _ball_and_ufo(self):
        for ball in self.__balls:
            if ball.check_active():
                if ball.check_ufo_collission(self.__ufo):
                    self.Quit()

    def _powerup_and_paddle(self):
        for powerup in self.__powerups:
            if not powerup.check_active():
                continue
            if check_intersection(powerup, self.__paddle):
                if powerup.get_type() == POWERUP_EXPAND_PADDLE:
                    self.__paddle.change_width(INC_PADDLE_WIDTH)

                elif powerup.get_type() == POWERUP_SHRINK_PADDLE:
                    self.__paddle.change_width(-1 * SHRINK_PADDLE_WIDTH)

                elif powerup.get_type() == POWERUP_FAST_BALL:
                    for ball in self.__balls:
                        ball.inc_speed(2)

                elif powerup.get_type() == POWERUP_BALL_MULITIPLIER:
                    new_balls = []
                    for ball in self.__balls:
                        if ball.check_active():
                            new_balls.append(self.divide_ball(ball))
                    for new_ball in new_balls:
                        self.__balls.append(new_ball)

                elif powerup.get_type() == POWERUP_THRU_BALL:
                    for ball in self.__balls:
                        ball.set_type(THRU_BALL)
                elif powerup.get_type() == POWERUP_GRAB_BALL:
                    for ball in self.__balls:
                        ball.set_grabbable()
                elif powerup.get_type() == POWERUP_SHOOTING_BULLET:
                    self.__paddle.set_have_bullet_powerup(1)
                    self.__paddle.set_powerup_start_time(self.__ticks)
                elif powerup.get_type() == POWERUP_FIREBALL:
                    for ball in self.__balls:
                        ball.set_fire()
                else:
                    continue
                powerup.deactivate()

    def _update(self):

        # ball moved
        self.__cnt_active_balls = 0
        for ball in self.__balls:
            if ball.check_active():
                ball.update()
                self.__cnt_active_balls += 1

        # Powerup moved
        powerup_remove = []
        for id, powerup in enumerate(self.__powerups):
            if powerup.check_active():
                powerup.update()
            else:
                powerup_remove.append(id)
        for id in sorted(powerup_remove, reverse=True):
            del self.__powerups[id]

        # Bullet moved
        bullet_remove = []
        for id, bullet in enumerate(self.__bullets):
            if bullet.check_active():
                bullet.update()
            else:
                bullet_remove.append(id)
        for id in sorted(bullet_remove, reverse=True):
            del self.__bullets[id]

        # Bomb moved
        bomb_remove = []
        for id, bomb in enumerate(self.__ufo_bombs):
            if bomb.check_active():
                bomb.update()
            else:
                bomb_remove.append(id)
        for id in sorted(bomb_remove, reverse=True):
            del self.__ufo_bombs[id]

        # Bullet powerup done
        if self.__paddle.check_have_bullet_powerup(
        ) and (self.__ticks -
               self.__paddle.get_powerup_start_time()) // 10 >= POWERUP_LIFE:
            self.__paddle.set_have_bullet_powerup(0)

        # Generate Bullet
        if self.__paddle.check_have_bullet_powerup() and self.__ticks % 8 == 0:
            x, y = self.__paddle.get_position()
            self.__bullets.append(Bullet(x + PADDLE_WIDTH // 2, y, -1))

        # Generate Bomb
        if self.__level == UFO_LEVEL and self.__ufo.can_drop_bomb():
            u_x, u_y, u_width, u_height = self.__ufo.get_box()
            self.__ufo_bombs.append(Bomb(u_x + u_width // 2, u_y + u_height))

        # ball and wall collissins
        self._ball_and_wall()
        # ball and paddle collissions
        self._ball_and_paddle()
        # bomb and paddle
        if self.__level == UFO_LEVEL:
            self._bomb_and_paddle()
        # powerup and paddle collissions
        self._powerup_and_paddle()

        # ufo bricks and ball
        if self.__level == UFO_LEVEL:
            for brick in self.__ufo_bricks:
                if not brick.check_active():
                    continue
                for ball in self.__balls:
                    if not ball.check_active():
                        continue
                    is_destroyed = brick.handle_collission(ball)

        # ufo and ball
        if self.__level == UFO_LEVEL:
            got_critical = True
            if self.__ufo.check_critical():
                got_critical = False

            self._ball_and_ufo()

            if not self.__ufo.check_critical():
                got_critical = False

            if got_critical:
                u_x, u_y, u_width, u_height = self.__ufo.get_box()
                for i in range(UFO_WIDTH // BRICK_WIDTH):
                    b_x = u_x + i * BRICK_WIDTH
                    b_y = u_y + u_height
                    self.__ufo_bricks.append(WeakBrick(b_x, b_y))

        for powerup in self.__powerups:
            if powerup.check_active():
                powerup.check_wall_collission()

        for brick in self.__bricks:
            if brick.check_active():
                for bullet in self.__bullets:
                    if bullet.check_active():
                        vx, vy = bullet.get_velocity()
                        is_destroyed = brick.handle_collission_bullet(bullet)
                        if not is_destroyed:
                            continue
                        if is_destroyed and brick.id == EXPLODING_BRICK_ID:
                            os.system('aplay -q ./sounds/explosions.wav&')
                            for i in self.__explode_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                            for i in self.__explode_nbrs_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                        if is_destroyed and random.random(
                        ) > POWERUP_PROBABILITY:
                            # generate power_up
                            (x, y, _, _) = brick.get_box()
                            powerup_type = random.randint(0, 7)
                            self.__powerups.append(
                                PowerUp(x, y, vx, vy, powerup_type))

        self.__cnt_active_bricks = 0
        for brick in self.__bricks:
            if brick.check_active():
                if brick.get_type() != UNBREAKABLE_BRICK_ID:
                    self.__cnt_active_bricks += 1
                for ball in self.__balls:
                    if ball.check_active():
                        vx, vy = ball.get_velocity()
                        is_destroyed = brick.handle_collission(
                            ball, self.__map_position_to_bricks)
                        if is_destroyed and brick.id == EXPLODING_BRICK_ID:
                            for i in self.__explode_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                            for i in self.__explode_nbrs_ids:
                                if self.__bricks[i].check_active():
                                    self.__bricks[i].destroy()
                        if is_destroyed and random.random(
                        ) > POWERUP_PROBABILITY:
                            # generate power_up
                            (x, y, _, _) = brick.get_box()
                            powerup_type = random.randint(0, 7)
                            # powerup_type = POWERUP_FIREBALL
                            self.__powerups.append(
                                PowerUp(x, y, vx, vy, powerup_type))

        for brick in self.__bricks:
            if brick.check_active():
                brick.set_y_fall(self.__brick_structure_y_fall)

        if (self.__level_ticks // 10) == LEVEL_TIME[self.__level - 1]:
            self.__fall_bricks = 1

    def _get_score(self):
        self.__score = max(
            0, 100 * self.__bricks_broken - (self.__ticks // 100) * 10)

        if self.__level == UFO_LEVEL:
            self.__score += (max(0, 1000 *
                                 (UFO_HEALTH - self.__ufo.get_health())))

        return self.__score + self.__last_level_score

    def refresh(self):
        self.__powerups = []
        self.__paddle.set_default()
        self.__balls = [Ball(paddle=self.__paddle)]
        self.__bullets = []

    def change_level(self):
        if self.__level == MAX_LEVEL:
            self.Quit()

        self.__level += 1

        while True:
            print("\033[0;0H")
            self._draw_hold_screen(f"Moving to level {self.__level}.")
            last_key_pressed = self._get_input().lower()
            if last_key_pressed == "\n":
                print("\033[0;0H")
                break
            elif last_key_pressed == "q":
                self.Quit()
                break

        if self.__level == UFO_LEVEL:
            os.system('aplay -q ./sounds/ufo.wav& 2>/dev/null')

        self._draw_bricks()
        self.__brick_structure_y_fall = 0
        self.__fall_bricks = 0
        self.__level_ticks = 0
        self.__last_level_score = self.__score
        self.refresh()

    # loop over frames
    def _loop(self):
        self.__game_status = GAME_START
        clear_terminal_screen()

        while self.__game_status == GAME_START:

            # 1. Clear Screen
            # 2. update positions and handle collisions
            # 3. update info
            # 4. draw
            # 5. handle input

            # clear screen and reposition cursor.
            print("\033[0;0H")

            self._update()

            if self.__cnt_active_bricks == 0 and self.__level != UFO_LEVEL:
                self.change_level()

            if self.__cnt_active_balls == 0:
                self.refresh()
                self.__lives_used += 1
                self.__game_status = GAME_HOLD
                while self.__game_status == GAME_HOLD:
                    print("\033[0;0H")
                    self._draw_hold_screen("Life lost. Game Paused.")
                    last_key_pressed = self._get_input().lower()
                    if last_key_pressed == "\n":
                        print("\033[0;0H")
                        self.__game_status = GAME_START
                    elif last_key_pressed == "q":
                        self.Quit()
                        break

            if LIVES - self.__lives_used == 0:
                self.Quit()
                break

            self._draw()
            last = time.time()

            last_key_pressed = self._get_input()
            self._handle_input(last_key_pressed)

            self.__score = self._get_score()
            self.__ticks += 1
            self.__level_ticks += 1

            while time.time() - last < self._refresh_time:
                pass

    def Quit(self):
        clear_terminal_screen()
        self.__game_status = GAME_END
        s = " " * 5
        s = "GAME OVER!\n"
        s += f"SCORE:{self.__score}\n"[:13]
        s += f"LIVES USED:{self.__lives_used}\n"[:24]
        s += f"TIME: {self.__ticks//10}\n"
        os.write(1, str.encode(s))
        os.system('setterm -cursor on')
        os._exit(0)
示例#24
0
    coins = sorted(coins,key = lambda x: x.get_pos()[0])

    num_beams = 10
    beams = []
    beam_places_list = [np.array(range(board.get_bg_size()[0]+6,board.get_bg_size()[1]-board.get_window_size()[1],6)),np.array(range(din.get_ceil_ground()[1]+20,din.get_ceil_ground()[0]-10,6))]
    for i in range(num_beams):
        x = (int(np.random.choice(beam_places_list[0])),int(np.random.choice(beam_places_list[1])))
        if x not in coins and x[0]:
            beams.append(Beam(x[0],x[1],np.random.choice([7,8,12]),np.random.choice([0,1,2])))
    coins = sorted(coins,key = lambda x: x.get_pos()[0])


    magnet = Magnet(np.random.randint(board.get_window_size()[0]+10,board.get_bg_size()[1]-board.get_window_size()[1]))
    dragon = Dragon(din,board)
    # board.set_current_pos(board.get_bg_size()[1] - board.get_window_size()[1])
    kb.getch()
    while dragon.get_ended() == 0 and din.get_lives() > 0:
        board.update()
        if kb.kbhit():
            c = kb.getch()
            if c == 'q':
                break
            if c == 'k':
                board.speed_up()
            if c == 'j':
                board.speed_down()
            din_ret = din.update(c)
            if c == 's':
                bullets.append(din_ret)
        else:
            din.update()
示例#25
0
        if pawns[8][i].get_shield_active() is True:
            if (now - pawns[8][i].get_timestamp()).seconds > 5:
                pawns[8][i].deactivate_shield()

        if pawns[8][i].get_dragon_active() is True:
            if (now - pawns[8][i].get_dragon_timestamp()).seconds > 5:
                pawns[8][i].deactivate_dragon()

        if pawns[8][i].get_dragon_active() is True:
            pawns[8][i].set_dragon_sprite(offsets[idx])
            speed_boost += 0.005
            speed_boost_times.append(now)
            pawns[8][i].set_position(np.array([GROUND_SIZE[0] - 12, 0]))

    if _KBHIT.kbhit():
        inp = _KBHIT.getch().lower()
        if inp == 'q':
            break
        elif inp == 'e' and pawns[8][0].get_dragon_active() is False:
            pawns[9].append(
                Bullet([
                    pawns[8][0].get_position()[0],
                    pawns[8][0].get_position()[1] + 2
                ], ObjNumber, 0))
            ObjNumber += 1
        else:
            pawns[8][0].control(inp, offsets[i], GROUND_SIZE[0])

    for i in range(len(pawns[5])):
        pawns[8][0] = pawns[5][i].on_trigger(pawns[8][0])
示例#26
0
    def run(self):
        kb = KBHit()
        selectedData = []
        dataToAverage = []
        print('Hit ESC to exit')
        while True:
            if kb.kbhit():
                c = kb.getch()
                if ord(c) == 27:  # ESC
                    kb.set_normal_term()
                    print "Quitting!"
                    os._exit(0)
            now = time.time()
            due = now - self.parent.offset
            search_from = self.parent.index - 1
            if search_from == -1:
                search_from = self.parent.buffer_size - 1
            timestamp = 0
            nextTimestamp = 0
            self.waitForNewData = 0.5
            self.parent.mutex.acquire()

            lastjvalue = 0

            dataArray = []

            for theid in range(self.parent.channel_count):

                data = self.parent.outbuffers[int(theid)][self.parent.index]

                for i in range(search_from,
                               search_from - self.parent.buffer_size, -1):
                    j = i if i >= 0 else i + self.parent.buffer_size
                    timestamp = self.parent.timestamp_buffer[j]
                    if timestamp is not None and timestamp <= due:
                        data = self.parent.outbuffers[int(theid)][j]
                        lastjvalue = j
                        if (j < self.parent.buffer_size - 2):
                            nextTimestamp = self.parent.timestamp_buffer[j + 1]
                        else:
                            nextTimestamp = self.parent.timestamp_buffer[0]
                        break
                if data is not None:
                    dataArray.append(data)

            #print "data array: ", dataArray

            for f in config.streams:
                stream = f['stream']
                if len(dataArray) > stream:
                    #print "stream = ", stream,  dataArray[stream]
                    if 'scale' in f:
                        dataArray[stream] = self.format.scale(
                            dataArray[stream], f['scale'])
                    if 'type' in f and f['type'] == int:
                        #msgString += str(int(dataArray[stream]))
                        selectedData.append(int(dataArray[stream]))
                    else:
                        #msgString += str(dataArray[stream])
                        selectedData.append(dataArray[stream])

                    if len(selectedData) == len(config.streams):
                        self.sendMessage(selectedData)
                        selectedData = []

            if timestamp is not None and nextTimestamp is not None:
                waitTime = nextTimestamp - timestamp
                if waitTime > 0:
                    time.sleep(waitTime)
                else:
                    print "timing out waiting for new data - time < 0"
                    time.sleep(self.waitForNewData)
            else:
                print "timing out waiting for new data - time or nextTime is None"
                time.sleep(self.waitForNewData)
            self.parent.mutex.release()
示例#27
0
            direction = new_direction
            #m.move(direction, speed=70)
        else:
            #m.course_correct()
            pass
        dist = us_dist(15)
        if (dist < dist_to_stop):
            print("too close, stop")
            m.stop()
            break
    else: # we could not find the target - stop and wait
        m.stop
    # clear the stream in preparation for the next frame
    rawCapture.truncate(0)
    i = i+1
    time.sleep(0.1) #allow the system some time - don't hog the CPU
    # if the `q` key was pressed, break from the loop
    if ch == ord('q'):
        break
    if (kb.kbhit()):
        c = kb.getch()
        if (c == 'q'):
            break
    if ( (time.clock() - tstart) > max_time_to_run):
        break

print("fps: ", i / (time.time() - tstart), i, time.time() - tstart)
m.stop()
cv2.destroyAllWindows()
print("out")
示例#28
0
文件: game.py 项目: spashal/Rdx-ball
from levels import Level1, Moderate, Easy, Difficult, FinalLevel
# os.system('afplay ' + 'barbie.mp3 &')

keyboard = KBHit()
lives = 5
score = 0
while lives > 0:

    # level 1
    level = Easy()
    level.placeBricks()
    while True:
        level.screen.time += level.ball.waitTime
        time.sleep(level.ball.waitTime)
        if keyboard.kbhit():
            inp = keyboard.getch()
            if inp == 'q':
                sys.exit()
            elif inp == 'a' or inp == 'd':
                level.paddle.move(inp)
            elif inp == ' ':
                level.ball.launch()
            elif inp == 't':
                break
            keyboard.flush()
        level.ball.move()

        if level.ball.gameOver == True:
            break
        os.system("clear")
        level.screen.display()