示例#1
0
 def mvup(self):
     if (globally.matrix[self.x - 2][self.y] == ' '):
         self.x -= 2
         Movement.move('\u001b[0;32mB\u001b[0m', self.x, self.y)
         if (globally.matrix[self.x +
                             2][self.y] == '\u001b[0;32mB\u001b[0m'):
             Clear.clear(self.x + 2, self.y)
示例#2
0
def get_manhattan_distance(start_move, instructions, waypoint=False):

    northness = 0
    eastness = 0

    for instruction in instructions:
        command = instruction[0]
        amount = int(instruction[1:])
        if command in ['L', 'R']:
            curr_move.rotate(command, amount)
        else:
            if command == 'F':
                change_to_position = curr_move.apply(amount)
            else:
                if waypoint:
                    curr_move.modify(Movement.specify(command).apply(amount))
                    change_to_position = None
                else:
                    change_to_position = Movement.specify(command).apply(
                        amount)
            if change_to_position:
                eastness += change_to_position.eastwards
                northness += change_to_position.northwards

    return abs(eastness) + abs(northness)
示例#3
0
 def __init__(self):
     self.__arena = Arena()
     self.__wall = Wall(self.__arena)
     self.__snake = Snake(self.__arena)
     self.__movement = Movement(self.__arena, self.__snake)
     self.cls()
     self.gameloop()
示例#4
0
class Ghost(Sprite):

    def __init__(self, posx, posy):
        Sprite.__init__(self)
        self.move = Movement(self, thrust_strength = 1000,
                             accelx = 1000,
                             accely = 1000,
                             maxspeedx = 153,
                             maxspeedy = 153,
                             gravity = 0,
                             posx = posx,
                             posy = posy)

        if random.randint(0, 2) == 1:        
            self.image = media.load_image('Cone.png')
            self.rect = self.image.get_rect()
            self.image = pygame.transform.scale(self.image, (int(self.rect.width*1.5), int(self.rect.height*1.5)))
        else:
            self.image = media.load_image('Trou.png')
            self.rect = self.image.get_rect()
            self.image = pygame.transform.scale(self.image, (self.rect.width*2, self.rect.height*2))
            
        self.rect = self.image.get_rect()
    def update(self, tick):
        self.move.moveleft(tick)
        self.move.calculate_movement(tick)
        self.rect.x = self.move.posx
        self.rect.y = self.move.posy        
示例#5
0
class Ghost(Sprite):

    def __init__(self, posx, posy):
        Sprite.__init__(self)
        self.move = Movement(self, thrust_strength = 1000,
                             accelx = 1000,
                             accely = 1000,
                             maxspeedx = 60,
                             maxspeedy = 60,
                             gravity = 0,
                             posx = posx,
                             posy = posy)
        self.ghost1 = media.load_image('ghost1.png')
        self.ghost2 = media.load_image('ghost2.png')
        self.image = self.ghost1
        self.rect = self.image.get_rect()
        self.currentframe = 1
        
    def update(self, tick):
        if self.currentframe >= 1 and self.currentframe <= 4:
            self.image = self.ghost2
        elif self.currentframe >= 5 and self.currentframe <= 8:
            self.image = self.ghost1
        self.currentframe += 1
        if self.currentframe == 9:
            self.currentframe = 1

        self.brain.update(tick)
        self.move.calculate_movement(tick)
        self.rect.x = self.move.posx
        self.rect.y = self.move.posy        
示例#6
0
class Fairy(Sprite):

    def __init__(self, posx, posy):
        Sprite.__init__(self)
        self.move = Movement(self, thrust_strength = 15000,
                             accelx = 3800,
                             maxspeedx = 2000,
                             maxspeedy = 2500,
                             posx=posx,
                             posy=posy)
        self.brain = None
        self.fairy_wingup = media.load_image('fairy_wingup.png')
        self.fairy_wingmid = media.load_image('fairy_wingmid.png')
        self.fairy_wingdown = media.load_image('fairy_wingdown.png')
        self.image = self.fairy_wingup
        self.rect = self.image.get_rect()
        self.currentframe = 1
        
    def update(self, tick):
        if self.currentframe == 1:
            self.image = self.fairy_wingup
        elif self.currentframe == 2:
            self.image = self.fairy_wingmid
        elif self.currentframe == 3:
            self.image = self.fairy_wingdown
        self.currentframe += 1
        if self.currentframe == 4:
            self.currentframe = 1
            
        self.brain.update(tick)
        self.move.calculate_movement(tick)
        self.rect.x = self.move.posx
        self.rect.y = self.move.posy
示例#7
0
 def mvleft(self):
     if (globally.matrix[self.x][self.y - 4] == ' '):
         self.y -= 4
         Movement.move('\u001b[0;32mB\u001b[0m', self.x, self.y)
         if (globally.matrix[self.x][self.y +
                                     4] == '\u001b[0;32mB\u001b[0m'):
             Clear.clear(self.x, self.y + 4)
示例#8
0
    def __init__(self):
        coordList = []
        self.currLocation = [0, 0, 90]

        self.nSteps = len(coordList)
        self.mov = Movement()
        self.rad = 180 / 3.14
示例#9
0
 def __init__(self, character):
     pygame.sprite.Sprite.__init__(self)
     self.character = character
     self.image = pygame.image.load(IMG + character).convert()
     self.image.set_colorkey(WHITE)
     self.rect = self.image.get_rect()
     self.movement = Movement(self)
     self.pos = VEC(WIDTH / 2 + 10, HEIGHT / 2)
     self.rect.midbottom = self.pos
示例#10
0
class MyBot():
    def __init__(self):
        self.movement = Movement(self)

    def machin(self):
        a = 1
        print str(a) + "\n"
        self.movement.add()
        print str(a) + "\n"
示例#11
0
class MyBot():
	def __init__(self):
		self.movement = Movement(self)
	
	def machin(self):
		a = 1
		print str(a)+"\n"
		self.movement.add()
		print str(a)+"\n"
class Client:
    def __init__(self, x, y):
        self.location_api = Movement()

    def next_time(self, unit=1):
        self.location_api.next_time(unit)

    def location(self):
        return self.location_api.location()
示例#13
0
def speedAnalysis():
    speedList = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
    timeList = [30, 30, 20, 20, 10, 10, 5, 5, 4, 4]
    mov = Movement()
    for speed, time in zip(speedList, timeList):
        print("Speed: ", speed, "\t Time: ", time, "\n")
        mov.setSpeed(speed)
        mov.moveForward(time)
        mov.pause(15)
    mov.stop()
    del mov
示例#14
0
class Animation:
    def __init__(
        self,
        visual: Visual,
        parameters: Parameters,
        history: History,
        controllers,
        plotting,
        result,
    ):
        self.visual = visual
        self.parameters = parameters
        self.history = history
        self.movement = Movement(parameters, history)
        self.controllers = controllers
        self.plotting = plotting
        self.result = result

    def run(self):
        """Run the game"""

        self.animation_func = animation.FuncAnimation(
            self.plotting.fig,
            self.update,
            init_func=self.initialise,
            interval=self.visual.frame_interval_ms,
        )

        plt.show()

    def initialise(self):

        return self.plotting.plots

    def _ntimesteps_per_frame_refresh(self):

        return int(self.visual.frame_interval_ms /
                   (1000 * self.parameters.time.timestep))

    def update(self, _):

        for _ in range(self._ntimesteps_per_frame_refresh()):
            if not self.result.winner:
                self.controllers.process_inputs()
                self.result.check_controllers()
            if not self.result.winner:
                self.movement.move_objects()
                self.result.check_win_conditions()

        self.plotting.plot_board()

        return self.plotting.plots
示例#15
0
    def __init__(self, width, height, title):
        super().__init__()

        self.screen = Window(width, height, title)
        self.ball = Ball(20, (0, 0, 255), 2)
        self.ball.position = (math.ceil(width / 2), math.ceil(height / 2))

        self.movementObj = Movement(self.ball.x, self.ball.y, self.ball.radius)

        self.speed = 1

        self.createObjects([self.ball])
        self.run()
示例#16
0
 def mv(self):
     if self.direction == 1:
         if globally.matrix[self.x][self.y + 4] == ' ' or globally.matrix[self.x][self.y + 4] == '\u001b[0;32mB\u001b[0m' or globally.matrix[self.x][self.y + 4] == '\u001b[0;36m0\u001b[0m':
             self.y += 4
             Movement.move('\u001b[0;31mE\u001b[0m', self.x, self.y)
             Clear.clear(self.x, self.y - 4)
         else:
             Enemy.rmv(self)
     elif self.direction == 2:
         if globally.matrix[self.x][self.y - 4] == ' ' or globally.matrix[self.x][self.y - 4] == '\u001b[0;32mB\u001b[0m' or globally.matrix[self.x][self.y - 4] == '\u001b[0;36m0\u001b[0m':
             self.y -= 4
             Movement.move('\u001b[0;31mE\u001b[0m', self.x, self.y)
             Clear.clear(self.x, self.y + 4)
         else:
             Enemy.rmv(self)
     elif self.direction == 3:
         if globally.matrix[self.x - 2][self.y] == ' ' or globally.matrix[self.x - 2][self.y] == '\u001b[0;32mB\u001b[0m' or globally.matrix[self.x - 2][self.y] == '\u001b[0;36m0\u001b[0m':
             self.x -= 2
             Movement.move('\u001b[0;31mE\u001b[0m', self.x, self.y)
             Clear.clear(self.x + 2, self.y)
         else:
             Enemy.rmv(self)
     else:
         if globally.matrix[self.x + 2][self.y] == ' ' or globally.matrix[self.x + 2][self.y] == '\u001b[0;32mB\u001b[0m' or globally.matrix[self.x + 2][self.y] == '\u001b[0;36m0\u001b[0m':
             self.x += 2
             Movement.move('\u001b[0;31mE\u001b[0m', self.x, self.y)
             Clear.clear(self.x - 2, self.y)
         else:
             Enemy.rmv(self)
示例#17
0
def main():
    # setup the static classes
    ap.init()

    #try to handle the Ctrl-C and then clean the app
    try:
        #ServGrap.hook(ServGrap.UP)
        #time.sleep(1)
        #ServGrap.hook(ServGrap.DOWN)
        #time.sleep(1)
        Movement.snake()
    except KeyboardInterrupt:
        print('Ctrl C')
    finally:
        ap.cleanup()
 def __init__(self):
     self.config = PepperConfiguration(_ROBOT_NAME)
     if(not self.config.isAvailable()):
         Logger.err("ControlFlow", "checkAvailability", "name: " + self.config.Name + ", ip: " + self.config.Ip + " not reachable!")
         sys.exit(1) #Abort since robot is not available...
     self.robot = Robot(self.config)
     Speech(self.robot) #Initialize Speech (static class, no reference needed)
     DoorChecker(self.robot) #Initialize DoorChecker (static class, no reference needed)
     TabletHandler(self.robot) #Initialize TabletHandler (static class, no reference needed)
     Filetransfer(self.config) #Initialize Filetransfer (static class, no reference needed)
     #self.tracer = Tracer(self.robot) # enable to gather sensor data
     self.sensorhandler = SensorHandler(self.robot)
     self.planner = Planner()
     self.movement = Movement(self.robot)
     self.poscalib = PositionCalibrator(self.robot)
     self.currentpos = _START_COORDINATE
示例#19
0
def generate_individuals(num, bench_press_fitness_mean,
                         bench_press_fitness_variance):
    """
    Generates individuals to be used in the simulator

    :param num: Number of individuals to generate.
    :param bench_press_fitness_mean: The mean of the 1RM in bench press for the individuals
    :param bench_press_fitness_variance: The variance in the 1RM for the individuals for a normal
    distribution
    :return: A list of individuals generated

    """

    # Holds all individuals
    individuals = []

    # Normally distributed bench press fitnesses used to create bench press movementss
    bench_press_performances = np.random.normal(bench_press_fitness_mean,
                                                bench_press_fitness_variance,
                                                num).astype("int")

    for i in tqdm(range(num)):
        banister_params = random_banister_parameters()
        name = names.get_full_name()
        bench_press_movement = Movement(0, 0, bench_press_performances[i],
                                        banister_params["fitness_gain"],
                                        banister_params["fatigue_gain"],
                                        banister_params["fitness_decay"],
                                        banister_params["fatigue_decay"])
        individual = Individual(i, datetime.datetime.now(), name,
                                bench_press_movement)
        individuals.append(individual)

    return individuals
 def __init__(self, world, sprite, pos, power, timer=3000):
     """."""
     self.sprite = sprite
     self.sprite.position = pos
     self.sprite.depth = 1
     self.bombdata = BombData(power, timer)
     self.movement = Movement(pos)
示例#21
0
 def __init__(
     self,
     visual: Visual,
     parameters: Parameters,
     history: History,
     controllers,
     plotting,
     result,
 ):
     self.visual = visual
     self.parameters = parameters
     self.history = history
     self.movement = Movement(parameters, history)
     self.controllers = controllers
     self.plotting = plotting
     self.result = result
示例#22
0
文件: ball.py 项目: janEntikan/wecs
 def update(self, entities_by_filter):
     start_balls = base.mouseWatcherNode.is_button_down(
         KeyboardButton.space(), )
     if start_balls:
         for entity in set(entities_by_filter['ball']):
             entity.remove_component(Resting)
             entity.add_component(Movement(value=Vec3(-1, 0, 0)))
示例#23
0
    def __init__(self):
        self.move = Movement(self, thrust_strength = 100000,
                             accelx = 100000,
                             accely = 100000,
                             maxspeedx = 120,
                             maxspeedy = 120,
                             gravity = 0,
                             posx=200,
                             posy=200)
        self.hunter = media.load_image('hunter.png').convert_alpha()
        self.firstupdate = False
        self.image = self.hunter
        self.rect = self.image.get_rect()
        self.imgflip = False
        self.dir = 1

        self.fuel = 10000
        self.lives = 3
        self.score = 0
        
        self.caught_fairies = Group()
        self.fairies_to_catch = Group()

        self.out_of_fuel_event = None
        self.no_more_life_event = None
        self.all_fairies_caught_event = None
        self.moveright(1000)
示例#24
0
def generate_data(game, winner):
    board = CheckersBoard()
    movement = Movement()
    board.set_pieces_on_board_for_a_new_game()
    game_states = ''

    for move in game[:-1]:
        board = movement.make_move(board, move)
        board_state = board.get_wooden_board()
        reduced_board_state = reduce_board(board_state)
        reduced_board_state = [piece[item] for item in reduced_board_state]
        game_states += ''.join(str(x) for x in reduced_board_state) + '\n'

    timestamp = str(int(time.time() * 1000000))
    file = open('games/' + winner + '/' + winner + timestamp, 'w+')
    file.write(game_states)
    file.close()
示例#25
0
    def load_from_series(self, series):
        """Loads an individual from a given one-dimentional array (series).

        :param series: The one-dimentional array (series) that the individual will be initialized from.
        """
        self.id = series['ID']
        self.name = series['Name']
        self.bench_press_movement = Movement(
            series["bench_press_fitness"],
            series["bench_press_fatigue"],
            series["bench_press_basic_performance"],
            series["bench_press_fitness_gain"],
            series["bench_press_fatigue_gain"],
            series["bench_press_fitness_decay"],
            series["bench_press_fatigue_decay"],
        )
        self.timestamp = pd.to_datetime(series["Timestamp"])
示例#26
0
    def __init__(self):
        rospy.init_node('controller', anonymous=True)

        navigation = actionlib.SimpleActionClient("move_base", MoveBaseAction)
        navigation.wait_for_server()

        self.poses = Poses()

        self.movement = Movement(navigation, "/map", self.poses)
        self.move = self.movement.move

        self.object_detector = ObjectDetector("/object_detection/coordinates")
        self.find_red_object = self.object_detector.find_red_object

        self.arm = Arm()

        print("I'm up")
示例#27
0
文件: ball.py 项目: Schwarzbaer/wecs
    def update(self, entities_by_filter):
        # Should resting balls be started?
        start_key = KeyboardButton.space()
        start_balls = base.mouseWatcherNode.is_button_down(start_key)

        if start_balls:
            for entity in set(entities_by_filter['ball']):
                del entity[Resting]
                entity[Movement] = Movement(value=Vec3(-1, 0, 0))
示例#28
0
def bench_press():
    """Fixture for sample bench press movement with set parameters"""
    return Movement(fitness=0,
                    fatigue=0,
                    basic_performance=300,
                    fitness_gain=1,
                    fatigue_gain=1,
                    fitness_decay=1,
                    fatigue_decay=0.99)
示例#29
0
    def __init__(self, graphics, root):

        # global variables
        self.k = K()

        # piece - piece identifier.  px, py - piece position(472x472).  mx, my - mouse position(472x472)
        self.data = {"piece": None, "px": 0, "py": 0, "mx": 0, "my": 0}

        # keeps track of current turn
        self.color = "token"

        # true when menu is displayed, else false
        self.menuOn = False

        # tkinter root
        self.root = root

        # creates window and all images
        self.graphics = graphics

        # Canvas from graphics class. Tkinter object, draws images
        self.canvas = graphics.canvas

        # functions for special moves.
        self.specialMoves = SpecialMoves(self.canvas)

        # contains board and functions pertaining to position
        self.position = Position(self.canvas, self.specialMoves)
        self.position.updateBoard()

        # contains functions for moving pieces
        self.movement = Movement(self.canvas, self.position)

        # handles menues
        self.interface = Interface(graphics)

        # creates highlights around boxes
        self.highlight = Highlight(self.canvas, self.position)

        # finds move for computer player
        self.cpu = CPU(self.position, self.canvas)

        # brings up main menu, starts game
        self.showMain(0)
示例#30
0
    def load_from_series(self, series):
        """Loads an individual from a given one-dimentional array (series).

        :param series: The one-dimentional array (series) that the individual will be initialized from.
        """
        self.id = series['ID']
        self.birth = datetime.strptime(series['Birth'], '%Y-%m-%d').date()
        self.gender = series['Gender']
        self.name = series['Name']
        self.weight = series['Weight']
        self.bench_press_movement = Movement(
            series["bench_press_fitness"],
            series["bench_press_fatigue"],
            series["bench_press_basic_performance"],
            series["bench_press_fitness_gain"],
            series["bench_press_fatigue_gain"],
            series["bench_press_fitness_decay"],
            series["bench_press_fatigue_decay"],
        )
示例#31
0
    def update(self):
        # atack

        if self.time_to_atack == -1 and self.in_range(
        ) and self.atack_is_ready():  # ready to atack
            self.time_to_atack = self.reaction  # time to atack
        elif self.time_to_atack > 0:  # wait to atack
            self.time_to_atack -= 1
        elif self.time_to_atack == 0:  # atack
            Atack.atack(self)
            Fade.fadein(self)
            self.time_to_atack -= 1  # goes back to ready

            # movement
        x_speed, y_speed = self.calc_direction()
        Movement.accelerate(self, x_speed, y_speed)
        Movement.update(self)
        # fade
        Fade.update(self)
示例#32
0
    def __init__(self):
        """Creates all the modules"""
        print("class: Controller created.")

        self.stances = ["default", "arm", "build", "dance", "battle_stance", ""]
        self.stance = "default"

        self.args = "|"
        self.using_joysticks = False
        self.speed1_x = 0
        self.speed1_y = 0
        self.speed2_x = 0
        self.speed2_y = 0
        self.arm = Arm()
        self.builder = Builder()
        self.dancing = Dancing()
        self.direction = ObjectDetection()
        self.movement = Movement()
        self.sound = SoundRecognition()
        self.reset = False
        self.drive = False

        # initialize bluetooth_connection connection
        self.host = connect.Connect(1, "host", 'B8:27:EB:36:3E:F8', 4, self)
        self.host.start()
        time.sleep(20)
        self.client = send.Send(2, "client", 'B8:27:EB:DE:5F:36', 5)
        self.client.start()
        time.sleep(10)

        self.msg_received = False
        # Add controller as observer to classes
        self.arm.addObserver(self)
        self.builder.addObserver(self)
        self.dancing.addObserver(self)
        self.direction.addObserver(self)
        self.movement.addObserver(self)
        self.sound.addObserver(self)

        self.robot = robot.Robot(6, 3)

        self.list = [self.arm, self.builder, self.dancing, self.direction, self.movement, self.sound]
示例#33
0
 def __init__(self, x, y, color, size, lifes, atack_time, sec_div10,
              temporary_list, enemy_list):
     self.size = size
     self.type = -1  # just to atack function work
     self.sec_div10 = sec_div10
     self.lifes = lifes
     self.msgs_list = []  # damage and kill text displays
     # statistics
     self.type_list = []  # types of dead enemies
     self.kills = 0
     self.bombs = 0
     # self.temporary_list = temporary_list
     # self.enemy_list = enemy_list
     # Movement(x, y, max_speed, acceleration, decelerate)
     Movement.__init__(self, x, y, 1.8, 0.105, 0.955)
     #Fade(color, time_fade, start_fadein)
     Fade.__init__(self, color, 0, True)
     #Atack(x, y, atack_time, range, color, fadeout_time, sec_div10, temporary_list, enemy_list)
     Atack.__init__(self, x, y, atack_time, size * 5, color, 40, sec_div10,
                    temporary_list, enemy_list)
示例#34
0
    def __init__(self, angular_speed, linear_speed):
        Movement.__init__(self, angular_speed, linear_speed)
        self.left_distance_to_obstacle_sensor = 90
        self.right_distance_to_obstacle_sensor = 270

        self.left_distance_sensor = 45 #ustawienie na 45 stopni z lewej
        self.forward_distance_sensor = 0 #wykrycie przeszkody na wprost
        self.right_distance_sensor = 315 #ustawienie na 45 stopni z prawej (360-45)

        self.forward_distance_threshold = 0.4
        self.distance_threshold = 0.35

        self.wall_distance_threshold = 0.3

        self.obstacle_location = None

        self.previous_distance_to_obstacle = 0
        self.distance_to_obstacle = 0

        self.set_PID_params()
示例#35
0
    def __init__(self, x, y, type, color, size, time_fade, sec_div10,
                 temporary_list, sub):
        self.type = type
        self.size = size
        self.sec_div10 = sec_div10
        self.sub = sub
        self.time_to_atack = -1

        # move
        max_speed, accel, decel, self.lifes = self.movem_attributes(type)
        # Movement(x, y, max_speed, acceleration, decelerate)
        Movement.__init__(self, x, y, max_speed, accel, decel)
        # fade
        #Fade(color, time_fade, start_fadein)
        Fade.__init__(self, color, time_fade, False)
        # atack
        atack_time, self.reaction, range, fadeout_time_atack = self.atack_attributes(
            type)
        #Atack(x, y, atack_time, range, color, fadeout_time, sec_div10, temporary_list, enemy_list)
        Atack.__init__(self, x, y, atack_time, range, color,
                       fadeout_time_atack, sec_div10, temporary_list, [sub])
示例#36
0
文件: server.py 项目: tuvokki/pistuff
def move(direction, seconds):
    """generic move method"""
    if direction in ['forward', 'backward']:
        exec_move = Move()
        if direction == 'forward':
            exec_move.forward(seconds)
        else:
            exec_move.backward(seconds)
        result = 'done move'
    elif direction in ['left', 'right']:
        exec_move = Turn()
        if direction == 'left':
            exec_move.left(seconds)
        else:
            exec_move.right(seconds)
        result = 'done turn'
    else:
        result = '{0} is no valid direction, choose between forward, backward, left, right.'.format(
            direction)
    return jsonify({'result': result, 'direction': direction, 'seconds':
                    seconds})
示例#37
0
 def __init__(self, posx, posy):
     Sprite.__init__(self)
     self.move = Movement(self, thrust_strength = 15000,
                          accelx = 3800,
                          maxspeedx = 2000,
                          maxspeedy = 2500,
                          posx=posx,
                          posy=posy)
     self.brain = None
     self.fairy_wingup = media.load_image('fairy_wingup.png')
     self.fairy_wingmid = media.load_image('fairy_wingmid.png')
     self.fairy_wingdown = media.load_image('fairy_wingdown.png')
     self.image = self.fairy_wingup
     self.rect = self.image.get_rect()
     self.currentframe = 1
示例#38
0
 def __init__(self, posx, posy):
     Sprite.__init__(self)
     self.move = Movement(self, thrust_strength = 1000,
                          accelx = 1000,
                          accely = 1000,
                          maxspeedx = 60,
                          maxspeedy = 60,
                          gravity = 0,
                          posx = posx,
                          posy = posy)
     self.ghost1 = media.load_image('ghost1.png')
     self.ghost2 = media.load_image('ghost2.png')
     self.image = self.ghost1
     self.rect = self.image.get_rect()
     self.currentframe = 1
示例#39
0
 def __init__(self, server=False, dispatch_proj=None, id=False):
     super(Player, self).__init__()
     self.state = state(vec2(100, 130), vec2(0, 0), 100)
     self.move = Movement(*self.state.pos)
     self.dispatch_proj = dispatch_proj
  # spawning player at 0,0, width 32 = 1280 / 40. and height 72 = 720/10.
     if not server:
         self.Rect = Rect
     else:
         self.Rect = AABB
     if id:
         self.id = id
         self.weapons = WeaponsManager(self.dispatch_proj, self.id)
     #self.color = Options()['color']  #(0, 204, 255)
     self.set_color(Options()['color'])
     self.rect = self.Rect(0, 0, 32, 72, self.color, isplayer=True)
     #input will be assigned by windowmanager class
     self.input = proto.Input()
     self.listeners = {}
     self.ready = False
示例#40
0
文件: vehicle.py 项目: cbguder/mugen
	def calculate_movements(self):
		self.movements = []

		t = self.arrival
		for i in range(len(self.path) - 1):
			m = Movement()
			m.time = t
			m.start = self.path[i]
			m.end = self.path[i+1]
			m.speed = self.speed

			duration = distance(m.start, m.end) / m.speed
			t += duration

			if t > 0:
				if m.time < 0:
					# Interpolate position at t = 0
					ratio   = -m.time / duration
					m.start = interpolate(m.start, m.end, ratio)
					self.arrival = m.time = 0.0

				self.movements.append(m)

		self.leave = t
示例#41
0
class MainChar(Sprite):

    def __init__(self):
        self.move = Movement(self, thrust_strength = 1800,
                             accelx = 900,
                             maxspeedx = 1000,
                             maxspeedy = 1000,
                             posx=50,
                             posy=50)
        self.hunter = media.load_image('hunter.png').convert_alpha()
        self.hunter_boost = media.load_image('hunter_boost.png').convert_alpha()
        self.firstupdate = False
        self.image = self.hunter
        self.rect = self.image.get_rect()
        self.imgflip = False
        self.dir = 1

        self.fuel = 10000
        self.lives = 3
        
        self.caught_fairies = Group()
        self.fairies_to_catch = Group()

        self.out_of_fuel_event = None
        self.no_more_life_event = None
        self.all_fairies_caught_event = None

    def set_init_pos(self):
        self.move.posx = 33
        self.move.posy = 50
        self.move.speedx = 0
        self.move.speedy = 0
        self.dir = 1
        self.flip()
        
    def flip(self):
        if not self.imgflip and self.dir == -1:
            self.image = pygame.transform.flip(self.image, True, False)
            self.imgflip = True
        elif self.imgflip and self.dir == 1:
            self.image = pygame.transform.flip(self.image, True, False)
            self.imgflip = False
        
    def moveleft(self, tick):
        self.dir = -1
        self.flip()

        if self.move.speedy == 0:
            self.move.moveleft(tick)
        
    def moveright(self, tick):
        self.dir = 1
        self.flip()
        if self.move.speedy == 0:
            self.move.moveright(tick)
        
    def thrust(self, tick):
        if self.fuel > 0:
            self.image = self.hunter_boost
            self.imgflip = False
            self.flip()
            self.firstupdate = True
            if self.imgflip:
                self.move.moveleft(tick / 2)
            else:
                self.move.moveright(tick / 2)
            self.move.thrust(tick)
            self.fuel -= tick / 8
        else:
            self.fuel = 0
            self.out_of_fuel_event()
        
    def update(self, tick):
        if not self.firstupdate:
            self.image = self.hunter
            self.imgflip = False
            self.flip()
        self.firstupdate = False
        
        self.move.calculate_movement(tick)

        if self.move.speedx > 0:
            self.move.speedx -= 1
        elif self.move.speedx < 0:
            self.move.speedx += 1
            
        self.rect.x = self.move.posx
        self.rect.y = self.move.posy

        self.catch_fairies()
        
    def raise_out_of_fuel_event(self):
        self.out_of_fuel_event()

    def raise_no_more_life_event(self):
        self.no_more_life_event()

    def raise_all_fairies_caught_event(self):
        self.all_fairies_caught_event()

    def remove_life(self):
        self.lives -= 1
        if self.lives == 0:
            self.raise_no_more_life_event()
        
    def catch_fairies(self):
        for f in self.fairies_to_catch:
            dist = math.sqrt((f.rect.centerx - self.rect.centerx)**2 + (f.rect.centery - self.rect.centery)**2)
            if dist < 20:
                f.kill()
                self.caught_fairies.add(f)
        if len(self.fairies_to_catch) == 0:
            self.raise_all_fairies_caught_event()
示例#42
0
class Player(Events):
    """docstring for player"""
    def __init__(self, server=False, dispatch_proj=None, id=False, batch=None,
                 renderhook=None):
        super(Player, self).__init__()
        self.state = state(vec2(100, 130), vec2(0, 0), 100)
        self.move = Movement(*self.state.pos)
        self.dispatch_proj = dispatch_proj
        # spawning player at 0,0, width 32 = 1280 / 40. and height 72 = 720/10.
        self.Rect = Rect
        if id:
            self.id = id
            self.weapons = WeaponsManager(self.dispatch_proj, self.id)
        # self.color = Options()['color']  #(0, 204, 255)
        self.set_color(Options()['color'])
        self.rect = self.Rect(0, 0, pext.x, pext.y, self.color, isplayer=True,
                              batch=batch)
        # input will be assigned by windowmanager class
        self.input = proto.Input()
        self.listeners = {}
        self.ready = False
        self.renderhook = renderhook
        self.state.conds.direction = proto.down

    def update(self, dt, rectgen, state=False, input=False):
        if not state:
            state = self.state
        if not input:
            input = self.input
        self.rect.vel = self.move.get_vel(dt, state, input)
        self.rect.update(*state.pos)
        state = self.collide(dt, rectgen, state)
        self.weapons.update(dt, state, input)
        self.state.update(dt, state)

    def predict_step(self, dt, rectgen, state, input):
        newrect = self.rect.copy()
        newrect.vel = self.move.get_vel(dt, state, input)
        newrect.update(*state.pos)
        state = self.collide(dt, rectgen, state, newrect)
        state.mpos = vec2(self.input.mx, self.input.my)
        state.id = self.id
        if self.renderhook:
            self.renderhook(state, update=True)

    def specupdate(self, dt):
        if self.input.up:
            self.state.pos.y += 1000 * dt
        if self.input.right:
            self.state.pos.x += 1000 * dt
        if self.input.left:
            self.state.pos.x -= 1000 * dt
        if self.input.down:
            self.state.pos.y -= 1000 * dt

    def client_update(self, s_state):
        easing = .3
        snapping_distance = 20

        diff = vec2(s_state.pos.x - self.state.pos[0],
                    s_state.pos.y - self.state.pos[1])
        len_diff = diff.mag()

        if len_diff > snapping_distance:
            self.state.pos = s_state.pos
        elif len_diff > .1:
            self.state.pos += diff * easing
        self.state.vel = s_state.vel
        self.rect.update(*self.state.pos)
        self.state.update(0, s_state)
        self.state.conds = s_state.conds
        self.state.id = self.id
        self.state.mpos = vec2(self.input.mx, self.input.my)
        if self.renderhook:
            self.renderhook(self.state, update=True)

    def predict(self, dt, rectgen):
        self.rect.vel = self.move.get_vel(dt, self.state, self.input)
        self.rect.update(*self.state.pos)
        self.collide(dt, rectgen, self.state)
        self.weapons.update(dt, self.state, self.input)
        self.state.id = self.id
        self.state.mpos = vec2(self.input.mx, self.input.my)
        if self.renderhook:
            self.renderhook(self.state, update=True)

    def draw(self):
        self.rect.draw()

    def collide(self, dt, rectgen, state, external_rect=None):
        if not external_rect:
            all_cols = [self.rect.sweep(obj, dt) for obj in rectgen]
        else:
            all_cols = [external_rect.sweep(obj, dt) for obj in rectgen]
        cols = [coldata for coldata in all_cols if coldata]
        try:
            xt = min(col[1] for col in cols if col[0].x != 0)
            xnorm, yt_ent = [(col[0].x, col[2]) for col in cols
                             if col[1] == xt and col[0].x != 0][0]
        except ValueError:
            xt = dt
            xnorm = 0.
        try:
            yt = min(col[1] for col in cols if col[0].y != 0)
            ynorm, xt_ent = [(col[0].y, col[2]) for col in cols
                             if col[1] == yt and col[0].y != 0][0]
        except ValueError:
            yt = dt
            ynorm = 0.

        """if xnorm:
            # check for stair
            stairoffset = 10
            testr = self.rect.copy()
            testr.update(testr.pos.x, testr.pos.y + stairoffset)
            first = testr.sweep(rct, dt)
            if not first:
                testr.update(testr.pos.x + testr.sign_of(testr.vel.x) * 30,
                             testr.pos.y)
                testr.vel.x = 0
                second = testr.sweep(rct, float('Inf'))
                if second and testr.vel.y != 0:
                    s1 = testr.vel.y * second[1]
                    s = stairoffset + s1
                    t = s / testr.vel.y
                    if not abs(t) == float('Inf'):
                        yt = t
                        xnorm = 0
                        ynorm = -1"""
        if xnorm and ynorm:
            if yt_ent == yt and xt > yt:
                xnorm = 0
                xt = dt
            elif xt_ent == xt and yt > xt:
                ynorm = 0
                yt = dt

        dt = vec2(xt, yt)
        norm = vec2(xnorm, ynorm)
        return self.resolve_sweep(norm, dt, state)

    def resolve_sweep(self, normal, dt, state):
        state.pos, state.vel = self.move.step(dt, state.pos)
        state.vel.x *= normal.x == 0.
        state.vel.y *= normal.y == 0.
        """if normal.y < 0:
            state.set_cond('onGround')
            elif normal.x > 0:
                    state.set_cond('onRightWall')
            elif normal.x < 0:
                    state.set_cond('onLeftWall')
        elif normal.y == 0.:# and normal.y == 0.:
            self.determine_state(state)"""
        self.determine_state(state, normal)
        return state

    def determine_state(self, state, normal):
        dir = state.conds.direction
        mult_sign = (-1 if dir % 2 else 1)
        vert = dir < 2
        if normal[vert] * mult_sign < 0:
            state.set_cond('onGround')
        elif state.vel[vert] * mult_sign < 0:
            state.set_cond('descending')

    def spawn(self, x, y, other=False):
        self.state.pos = vec2(x, y)
        self.state.vel = vec2(0, 0)
        self.state.hp = 100
        self.state.armor = 0
        self.state.isDead = False
        self.state.frozen = False
        self.weapons.reset()

    def get_id(self, id, name):
        self.id = id
        self.name = name
        self.weapons = WeaponsManager(self.dispatch_proj, self.id)
        self.renderhook(self, add=True)

    def die(self):
        self.state.isDead = 5

    def freeze(self):
        self.state.frozen = True

    def set_color(self, cstr):
        self.color = colors[cstr]

    def remove_from_view(self):
        self.renderhook(self, remove=True)

    def add_to_view(self):
        self.renderhook(self, add=True)
示例#43
0
class MainChar(Sprite):

    def __init__(self):
        self.move = Movement(self, thrust_strength = 100000,
                             accelx = 100000,
                             accely = 100000,
                             maxspeedx = 120,
                             maxspeedy = 120,
                             gravity = 0,
                             posx=200,
                             posy=200)
        self.hunter = media.load_image('hunter.png').convert_alpha()
        self.firstupdate = False
        self.image = self.hunter
        self.rect = self.image.get_rect()
        self.imgflip = False
        self.dir = 1

        self.fuel = 10000
        self.lives = 3
        self.score = 0
        
        self.caught_fairies = Group()
        self.fairies_to_catch = Group()

        self.out_of_fuel_event = None
        self.no_more_life_event = None
        self.all_fairies_caught_event = None
        self.moveright(1000)
        
    def set_init_pos(self):
        self.move.posx = 200
        self.move.posy = 200
        self.move.speedx = 0
        self.move.speedy = 0
        self.dir = 1
        self.flip()
        
    def flip(self):
        if not self.imgflip and self.dir == -1:
            self.image = pygame.transform.flip(self.image, True, False)
            self.imgflip = True
        elif self.imgflip and self.dir == 1:
            self.image = pygame.transform.flip(self.image, True, False)
            self.imgflip = False
                
    def moveright(self, tick):
        self.dir = 1
        self.flip()
        self.move.moveright(tick)
        
    def moveup(self, tick):
        self.move.thrust(tick)
    
    def movedown(self, tick):
        self.move.movedown(tick)
            
    def update(self, tick):
        if not self.firstupdate:
            self.image = self.hunter
            self.imgflip = False
            self.flip()
        self.firstupdate = False
        
        self.move.calculate_movement(tick)
            
        self.rect.x = self.move.posx
        self.rect.y = self.move.posy
        
    def raise_no_more_life_event(self):
        self.no_more_life_event()

    def remove_life(self):
        self.lives -= 1
        if self.lives == 0:
            self.raise_no_more_life_event()
示例#44
0
	def __init__(self):
		self.movement = Movement(self)
示例#45
0
文件: mover.py 项目: tuvokki/pistuff
                    action="store_true")
PARSER.add_argument(
    '--direction', help='Set to 1 for clockwise and -1 for anti-clockwise', type=int, default=1)
PARSER.add_argument(
    '--seconds', help='How long must the car drive', type=int, default=1)
PARSER.add_argument(
    '--speed', help='How fast must the car drive', type=int, default=1)
ARGS = PARSER.parse_args()
# LOGLEVEL = ARGS.loglevel
DIRECTION = ARGS.direction
DIRECTION = -1  # backward
DRIVE_TIME = ARGS.seconds
WAIT_TIME = ARGS.speed / float(1000)

# set log level
if ARGS.verbose:
    logging.getLogger().setLevel(logging.DEBUG)

AMOVE = Move()
AMOVE.drive_time = 2
AMOVE.run()

ATURN = Turn()
ATURN.drive_time = 2
ATURN.direction = -1
ATURN.run()

AMOVE = Move()
AMOVE.wait_time = 5
AMOVE.run()
示例#46
0
class Player(Events):
    """docstring for player"""
    def __init__(self, server=False, dispatch_proj=None, id=False):
        super(Player, self).__init__()
        self.state = state(vec2(100, 130), vec2(0, 0), 100)
        self.move = Movement(*self.state.pos)
        self.dispatch_proj = dispatch_proj
     # spawning player at 0,0, width 32 = 1280 / 40. and height 72 = 720/10.
        if not server:
            self.Rect = Rect
        else:
            self.Rect = AABB
        if id:
            self.id = id
            self.weapons = WeaponsManager(self.dispatch_proj, self.id)
        #self.color = Options()['color']  #(0, 204, 255)
        self.set_color(Options()['color'])
        self.rect = self.Rect(0, 0, 32, 72, self.color, isplayer=True)
        #input will be assigned by windowmanager class
        self.input = proto.Input()
        self.listeners = {}
        self.ready = False

    def update(self, dt, rectgen, state=False, input=False):
        if not state:
            state = self.state
        if not input:
            input = self.input
        self.rect.vel = self.move.get_vel(dt, state, input)
        self.rect.update(*state.pos)
        self.collide(dt, rectgen, state)
        self.weapons.update(dt, state, input)
        self.state.update(dt, state)

    def specupdate(self, dt):
        if self.input.up:
            self.state.pos.y += 1000 * dt
        if self.input.right:
            self.state.pos.x += 1000 * dt
        if self.input.left:
            self.state.pos.x -= 1000 * dt
        if self.input.down:
            self.state.pos.y -= 1000 * dt

    def client_update(self, s_state):
        easing = .8
        snapping_distance = 20

        diff = vec2(s_state.pos.x - self.state.pos[0],
                    s_state.pos.y - self.state.pos[1])
        len_diff = diff.mag()

        if len_diff > snapping_distance:
            self.state.pos = s_state.pos
        elif len_diff > .1:
            self.state.pos += diff * easing
        self.state.vel = s_state.vel
        self.rect.update(*self.state.pos)

    def draw(self):
        self.rect.draw()

    def collide(self, dt, rectgen, state):
        all_collisions = (self.rect.sweep(obj, dt) for obj in rectgen)
        collisions = [coldata for coldata in all_collisions if coldata]
        try:
            xt = min(col[1] for col in collisions if col[0].x != 0)
            xnorm = [col[0].x for col in collisions if col[1] == xt][0]
        except ValueError:
            xt = dt
            xnorm = 0.
        try:
            yt = min(col[1] for col in collisions if col[0].y != 0)
            ynorm = [col[0].y for col in collisions if col[1] == yt][0]
        except ValueError:
            yt = dt
            ynorm = 0.
        dt = vec2(xt, yt)
        norm = vec2(xnorm, ynorm)
        self.resolve_sweep(norm, dt, state)

    def resolve_sweep(self, normal, dt, state):
        self.state.pos, self.state.vel = self.move.step(dt, state.pos)
        self.rect.update(*self.state.pos)
        self.state.vel.x *= normal.x == 0.
        self.state.vel.y *= normal.y == 0.
        self.move.resolve_coll(self.state.pos, self.state.vel)
        if normal.y < 0:
            self.state.set_cond('onGround')
        elif normal.x > 0:
            self.state.set_cond('onRightWall')
        elif normal.x < 0:
            self.state.set_cond('onLeftWall')
        elif normal.x == 0. and normal.y == 0.:
            self.determine_state()

    def resolve_collision(self, ovrlap, axis, angle):
        self.state.pos[0] = self.rect.x1 - ovrlap * axis[0]
        self.state.pos[1] = self.rect.y1 - ovrlap * axis[1]
        self.state.vel[0] *= axis[1] > 0
        self.state.vel[1] *= axis[0] > 0
        self.rect.update(*self.state.pos)
        self.move.resolve_coll(self.state.pos, self.state.vel)
        if axis[1] > 0 and ovrlap < 0:
            #self.move.conds['on_ground'] = True
            self.state.set_cond('onGround')
            #self.move.angle = angle
        elif axis[0] > 0:
            if ovrlap > 0:
                self.state.set_cond('onRightWall')
            elif ovrlap < 0:
                self.state.set_cond('onLeftWall')

    def determine_state(self):
        if self.state.vel.y < 0:
            self.state.set_cond('descending')

    def spawn(self, x, y, other=False):
        self.state.pos = vec2(x, y)
        self.state.vel = vec2(0, 0)
        self.state.hp = 100
        self.state.armor = 0
        self.state.isDead = False
        self.state.frozen = False
        if isinstance(self.rect, Rect):
            self.rect.update_color(self.color)
        if not other:
            self.weapons.reset()

    def get_id(self, id, name):
        self.id = id
        self.name = name
        self.weapons = WeaponsManager(self.dispatch_proj, self.id)

    def die(self):
        self.state.isDead = 5
        if isinstance(self.rect, Rect):
            self.rect.update_color([128] * 3)

    def freeze(self):
        self.state.frozen = True

    def set_color(self, cstr):
        self.color = colors[cstr]
示例#47
0
文件: server.py 项目: tuvokki/pistuff
def forward(seconds):
    """forward method"""
    move_fwd = Move()
    move_fwd.forward(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
示例#48
0
文件: server.py 项目: tuvokki/pistuff
def backward(seconds):
    """backward method"""
    move_bwd = Move()
    move_bwd.backward(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})