Exemplo n.º 1
0
    def run(self):
        self.visualizer.canvas.delete("all")
        #Change our status var
        self.statusVar.set("Initializing")

        # Create our network change our visualizers size
        network = Network.Network(self.widthVar.get(), self.heightVar.get(),
                                  float(self.springVar.get()))
        self.visualizer.config(width=self.widthVar.get(),
                               height=self.heightVar.get())
        self.visualizer.addNetwork(network)

        #Create our settings dict
        settingsDict = dict()
        settingsDict["path"] = (self.pathVar.get())
        settingsDict["t"] = float(self.tVar.get())
        settingsDict["iter"] = float(self.iterVar.get())
        settingsDict["radius"] = float(self.radiusVar.get())
        settingsDict["spring"] = float(self.springVar.get())
        settingsDict["network"] = network
        settingsDict["visualizer"] = self.visualizer
        settingsDict["statusVar"] = self.statusVar

        #Run our program
        Animator.run(settingsDict)
Exemplo n.º 2
0
    def __init__(self):
        self.window_width = 800
        self.window_height = 600
        self.window = pygame.display.set_mode(
            (self.window_width, self.window_height))
        self.running = True
        self.top_color = (255, 225, 200)
        self.bottom_color = (50, 0, 50)
        self.clock = pygame.time.Clock()
        self.audio_manager = AudioManager.AudioManager()
        self.part_sys = ParticleSystem.ParticleSystem(self.top_color,
                                                      self.bottom_color)
        self.top_player = Player.Player(self.window_width // 2 - 12, -50,
                                        self.part_sys, self.audio_manager)
        self.bottom_player = Player.Player(self.window_width // 2 - 12,
                                           self.window_height, self.part_sys,
                                           self.audio_manager)
        self.immovable_num = 3
        self.level_num = -1
        self.max_level_num = 5
        self.level = Level.Level()
        self.camera = Camera.Camera(self.window)
        self.game_state = GameState.MENU
        self.credits = Credits.Credits(self.window_width, self.window_height,
                                       self.top_color)
        self.menu = Menu.Menu(self.window_width, self.window_height,
                              self.bottom_color, self.top_color)
        self.next_state = None
        self.transitioning = False
        self.animator = Animator.Animator()

        pygame.display.set_caption("Laws of Reflection")
        self.bottom_player.inverse()
        self.next_level()
Exemplo n.º 3
0
    def move_ball_right(
        arbiter, space, data
    ):  # changes ball's position to the right, after collision with the left segment
        global score
        score += 500
        ball = arbiter.shapes[0]
        space.remove(ball.body, ball)
        ball = spawn_ball(
            space, (posStart2[0] - 20, ball.body.position.y),
            ball.body.velocity
        )  # spawns ball in again with new velocity and in the right position

        screen = pygame.display.get_surface()

        def animate(percentage_complete):
            s = pygame.Surface((14, 300))
            s.fill((142, 150, 163))
            s.set_alpha(255 * (1 - percentage_complete))
            screen.blit(s, (transport_coordinates[3][0] - 5,
                            height - transport_coordinates[3][1]))

        text_popup(text="500",
                   duration=30,
                   size=25,
                   color=(175, 174, 176),
                   position=ball.position)
        animators.append(Animator.Animator(20, animate))

        return False
Exemplo n.º 4
0
    def post_solve(arbiter, space, data):
        bumper_body = arbiter.shapes[1].body
        ball_body = arbiter.shapes[0].body

        strength_of_bumper = 20
        impulse = normalized_vector_between(bumper_body, ball_body)
        impulse = [
            impulse[0] * strength_of_bumper, impulse[1] * strength_of_bumper
        ]
        global score
        score += 1000
        ball_body.apply_impulse_at_world_point(
            impulse, (ball_body.position[0], ball_body.position[1]))

        radius = arbiter.shapes[1].radius
        pos = bumper_body.position
        screen = pygame.display.get_surface()

        def animate(percentage_complete):
            s = pygame.Surface((52, 52))
            s.set_colorkey((0, 0, 0))
            s.set_alpha(255 * (1 - percentage_complete))
            pygame.draw.circle(s, (255, 232, 140), (26, 26), int(radius))
            screen.blit(s, (int(pos.x - radius), int(height - pos.y - radius)))

        text_popup(text="1000",
                   duration=30,
                   size=25,
                   color=(175, 174, 176),
                   position=ball_body.position)
        animators.append(Animator.Animator(30, animate))
Exemplo n.º 5
0
def text_popup(text, duration, size, color, position):
    screen = pygame.display.get_surface()
    dynamic_pos = [position[0], position[1]]
    font = pygame.font.Font("Roboto-Black.ttf", size)
    s = font.render(text, False, color)

    def animate_text(percentage_complete):
        s.set_alpha(255 * (1 - percentage_complete))
        dynamic_pos[1] += 1
        screen.blit(s, (dynamic_pos[0] - 13, height - dynamic_pos[1] - 25))

    animators.append(Animator.Animator(duration, animate_text))
Exemplo n.º 6
0
def draw_trail(shape):
    radius = shape.radius
    local_pos = [shape.body.position.x, shape.body.position.y]
    screen = pygame.display.get_surface()

    def animate(percentage_complete):
        #print("SHAPE POSITION" + str(shape.body.position))
        s = pygame.Surface((radius * 2, radius * 2))
        s.set_alpha(255 / 20 * (1 - percentage_complete))
        s.set_colorkey((0, 0, 0))
        pygame.draw.circle(s, (237, 247, 246), (int(radius), int(radius)),
                           int(radius * (1 - percentage_complete)))
        screen.blit(
            s,
            (int(local_pos[0] - radius), int(height - local_pos[1] - radius)))

    animators.append(Animator.Animator(15, animate))
Exemplo n.º 7
0
def add_powerup(
    space, color, position
):  # adds circular power ups that affect ball differently upon impact
    body = pymunk.Body(body_type=pymunk.Body.STATIC)
    pow = pymunk.Circle(body, 10)
    pow.sensor = True
    pow.body.position = position
    pow.collision_type = collision_types["powerup"]
    pow.color = color
    space.add(pow, body)
    if color == THECOLORS[
            "red"]:  # once powerups are displayed sets dictionary value to -1
        pow_timewait["red"] = -1
    if color == THECOLORS["yellow"]:
        pow_timewait["yellow"] = -1
    if color == THECOLORS["blue"]:
        pow_timewait["blue"] = -1

    radius = pow.radius
    screen = pygame.display.get_surface()
    pos = body.position
    multiplier = 4

    def animate(percentage_complete):
        s = pygame.Surface((radius * multiplier * 2, radius * multiplier * 2))
        s.set_colorkey((0, 0, 0))
        s.set_alpha(255 * (1 - (percentage_complete % 1)))
        pygame.draw.circle(
            s, color, (int(radius) * multiplier, int(radius) * multiplier),
            int(radius * (1 + multiplier / 2 * (percentage_complete % 1))), 2)
        screen.blit(s, (int(pos.x - multiplier * radius),
                        int(height - pos.y - multiplier * radius)))

    def custom_is_done():
        if pow in space.shapes:
            return False
        return True

    custom_animator = Animator.Animator(45, animate)
    custom_animator.is_done = custom_is_done

    animators.append(custom_animator)
Exemplo n.º 8
0
def main(
    image,
    width,
    height,
    rows,
    columns,
    frame_renderer,
    frame_selector,
    trailing_blank_frames=0,
):
    frame_width = width / columns
    frame_height = height / rows
    return Animator(
        frame_count=rows * columns - trailing_blank_frames,
        frame_loader=(lambda frame_index: frame_selector(
            image,
            columns % frame_index * frame_width,
            floor(rows / frame_index) * frame_height,
            frame_width,
            frame_height,
        )),
        frame_renderer=frame_renderer,
    )
Exemplo n.º 9
0
    def __init__(self, file):
        self.file = file
        self.spriteBanks = []
        self.templates = {}

        with open(self.file) as json_file:
            data = json.load(json_file)

            # Register the related frames
            if 'imageBanks' in data.keys():
                for b in data["imageBanks"]:

                    #create new bank
                    bank = SpriteBank(b["id"], b["file"])
                    self.spriteBanks.append(bank)
                    pyxel.image(b["id"]).load(0, 0, b["file"])

                    #add sprites
                    for s in b["sprites"]:
                        bank.addSprite(
                            Sprite(Vector2f(s["pos_x"], s["pos_y"]),
                                   Vector2f(s["width"], s["height"]),
                                   Vector2f(s["pivot_x"], s["pivot_y"]),
                                   s["transparent"]), s["id"])
            else:
                print("Warning: EntityFactory: no 'imageBanks' in " +
                      self.file)

            # create entity
            if ('entities' in data.keys()):
                for name in data["entities"].keys():
                    templateData = data["entities"][name]
                    template = Entity()

                    # basic information
                    template.size.x = templateData["size_x"]
                    template.size.y = templateData["size_y"]

                    if ('rigidbody' in templateData):
                        template.addComponent('RigidBody', RigidBody())

                    # rendering informations
                    if ('renderer' in templateData):
                        palette = templateData["renderer"]["imageBank"]
                        bank = self.spriteBanks[palette]
                        renderer = templateData["renderer"]

                        # prefab is rendered using an Animator
                        if ('animations' in renderer):
                            animations = []

                            #create the animations
                            for a in renderer["animations"]:
                                frames = []
                                for f in a["frames"]:
                                    frame = bank.searchByName(f)
                                    if frame != None:
                                        frames.append(frame)
                                    else:
                                        print(
                                            "Warning: EntityFactory: no sprite under the name "
                                            + str(f) + ", for loading " + name)
                                animations.append(
                                    Animation(a["animationName"], bank, frames,
                                              a["interruptable"],
                                              1.0 / a["speed"], a["loop"]))

                            template.addComponent(
                                'Animator',
                                Animator(palette, animations,
                                         renderer["defaultAnimation"]))

                        # prefab is rendered using a SpriteRenderer
                        elif ('spriteList' in renderer):
                            spriteList = []
                            for s in renderer["spriteList"]:
                                sprite = bank.searchByName(s)
                                if sprite != None:
                                    spriteList.append(sprite)
                                else:
                                    print(
                                        "Warning: EntityFactory: no sprite under the name "
                                        + str(s) + ", for loading " + name)
                            template.addComponent('SpriteList', spriteList)
                            template.addComponent('ComponentRenderer',
                                                  SpriteRenderer(bank))
                    else:
                        print(
                            "Warning: EntityFactory: no component renderer for entity "
                            + name)

                    # collision informations
                    if ('colliders' in templateData):
                        colliderList = []
                        for c in templateData["colliders"]:
                            collider = Collider(c["type"])
                            collider.position = Vector2f(
                                c["pos_x"], c["pos_y"])
                            collider.size = Vector2f(c["width"], c["height"])
                            colliderList.append(collider)
                        template.addComponent('ColliderList', colliderList)
                    else:
                        print(
                            "Warning: EntityFactory: no colliders for entity "
                            + name)

                    # scripts
                    if ('scripts' in templateData):
                        scripts = []
                        for s in templateData["scripts"]:
                            try:
                                module = __import__(s["name"])
                                class_ = getattr(module, s["name"])
                                script = class_()
                                scripts.append(script)
                            except:
                                print(
                                    "Warning: EntityFactory: script loading error for entity "
                                    + name)
                        template.addComponent('Scripts', scripts)

                    # register template
                    self.templates[name] = template
            else:
                print("Warning: EntityFactory: no entities in " + self.file)
Exemplo n.º 10
0
def main():
    # Parse CLI arguments
    parser = argparse.ArgumentParser(prog="pathfinder.py", description="Solves a maze using Depth First Search, Breadth First Search, Best-first Search and A* Search, optionally outputting an animation.")

    requiredArgs = parser.add_argument_group("required arguments")
    requiredArgs.add_argument("-f", "--file", help="filename of the maze to be solved", type=str)

    parser.add_argument("-a", "--animate", help="outputs an animation showing all paths", action="store_true")
    parser.add_argument("-l", "--length", help="length of the animation, in seconds (only has effect with -a) | Default: 15", type=int, default=15)

    args = parser.parse_args()

    if not args.file:
        print("Please declare a filename as argument with '-f FILE'. Use '-h' for help.")
        return

    animate = args.animate
    filename = args.file
    videoLength = args.length

    try:
        maze = Maze(filename=filename)
    except:
        print("Couldn't find or read file '{}'. Please check if it exists and is in the right format.".format(filename))
        return

    solver = Solver(animate)

    # Show interpreted maze
    if animate:
        print("{}x{} Maze:".format(maze.w, maze.h))
        print(maze)

    # Run DFS algorithm
    try:
        dfsSolution = solver.dfs(maze)
        print("[DFS] Path Length: {:.2f} | Steps Taken: {}".format(dfsSolution.pathLength, dfsSolution.stepCounter))
        # print([(a, b) for a, b, _ in dfsSolution.path])
        if animate:
            print("".join(["".join(l)+"\n" for l in dfsSolution.frames[-1]]))
    except Exception as e:
        print("[DFS] Path Length: N/A | Steps Taken: {}".format(dfsSolution.stepCounter))

    # Run BFS algorithm
    try:
        bfsSolution = solver.bfs(maze)
        print("[BFS] Path Length: {:.2f} | Steps Taken: {}".format(bfsSolution.pathLength, bfsSolution.stepCounter))
        # print([(a, b) for a, b, _ in bfsSolution.path])
        if animate:
            print("".join(["".join(l)+"\n" for l in bfsSolution.frames[-1]]))
    except Exception as e:
        print("[BFS] Path Length: N/A | Steps Taken: {}".format(bfsSolution.stepCounter))

    # Run BestFS algorithm
    try:
        bestfsSolution = solver.bestfs(maze)
        print("[BestFS] Path Length: {:.2f} | Steps Taken: {}".format(bestfsSolution.pathLength, bestfsSolution.stepCounter))
        # print([(a, b) for a, b, _ in bestfsSolution.path])
        if animate:
            print("".join(["".join(l)+"\n" for l in bestfsSolution.frames[-1]]))
    except Exception as e:
        print("[BestFS] Path Length: N/A | Steps Taken: {}".format(bestfsSolution.stepCounter))

    # Run A* algorithm
    try:
        astarSolution = solver.astar(maze)
        print("[A*] Path Length: {:.2f} | Steps Taken: {}".format(astarSolution.pathLength, astarSolution.stepCounter))
        # print([(a, b) for a, b, _ in astarSolution.path])
        if animate:
            print("".join(["".join(l)+"\n" for l in astarSolution.frames[-1]]))
    except Exception as e:
        print("[A*] Path Length: N/A | Steps Taken: {}".format(astarSolution.stepCounter))

    # Generate animations
    if animate:
        filename = filename.split(".")[0]

        # if dfsSolution.path:
        #     Animator.animate(dfsSolution, str(filename) + "-dfs", videoLength)
        # if bfsSolution.path:
        #     Animator.animate(bfsSolution, str(filename) + "-bfs", videoLength)
        # if bestfsSolution.path:
        #     Animator.animate(bestfsSolution, str(filename) + "-best", videoLength)
        # if astarSolution.path:
        #     Animator.animate(astarSolution, str(filename) + "-astar", videoLength)

        if dfsSolution.path and bfsSolution.path and bestfsSolution.path and astarSolution.path:
            Animator.animateGrid(dfsSolution, bfsSolution, bestfsSolution, astarSolution, str(filename) + "-all", videoLength)
        else:
            print("One of the algorithms couldn't find a path. Can't animate.")
Exemplo n.º 11
0
        return x


def train(animator, ep):
    net = Net()
    input = torch.randn(1, 1, 32, 32)
    target = input[0][0][0][0:10] * 2 + 1.2345
    target = target.view(1, -1)  # 使target和output的shape相同
    criterion = nn.MSELoss()

    # create your optimizer
    optimizer = optim.SGD(net.parameters(), lr=0.01)

    # in your training loop:
    optimizer.zero_grad()  # zero the gradient buffers
    output = net(input)
    loss = criterion(output, target)
    x = torch.tensor([loss.detach()])
    print('output = ', output, '\ntarget = ', target, '\nloss = ', loss, '\n')
    animator.add(ep, (x, ep))
    loss.backward()
    optimizer.step()  # Does the update


animator = Animator(xlabel='epoch',
                    xlim=[0, 10],
                    ylim=[-5, 5],
                    legend=['train loss', 'test acc'])
for i in range(100):
    train(animator, i)
animator.stop()
Exemplo n.º 12
0
# Test of the translated/cleaned up drone sim code.
# creating a 'swarm' of two drones, flying in the
# same formation, just one above the other by 5 units.
from Animator import *
from DroneSim import *

# The waypoints - 'hardcoding' the swarm logic by spacing them enough.
wps = [[[-5, -5, 0], [5, -5, 0], [5, 5, 0], [-5, 5, 0]],
       [[-5, -5, 5], [5, -5, 5], [5, 5, 5], [-5, 5, 5]]]

sim = DroneSim(wps)
anm = Animator()

for i in range(5000):
    sim.tick()
    anm.plot_drones(sim.qrs)
Exemplo n.º 13
0
#tests the socket connection to the Animator
#run as sudo, all arguments get passed as the message

import Animator
import sys

if __name__ == "__main__":
    Animator.sendMessage(" ".join(sys.argv[1:]))
Exemplo n.º 14
0
import Animator
import threading
from time import sleep

animation = Animator.load("anim2.txt")
animation.play(1)

while animation._state == "playing":
    pass

animation.reverse()
animation.play(1)
Exemplo n.º 15
0
from Scene import *
from Visualizer import *
from Skeleton import *
from Animator import *
import sys, os
import subprocess

if __name__ == "__main__":
    cs = "tcp://localhost:5563"
    # os.system('mkdir -p ../MPII' + sys.argv[1])
    c = b"B"
    sk1 = Skeleton()
    sc1 = Scene()
    an1 = Animator(sk1, cs, c)
    if sys.argv[1]:
        viz = Visualizer(sk1, sc1, an1, sys.argv[1])
    else:
        viz = Visualizer(sk1, sc1, an1, None)
def main(images, frame_renderer):
    return Animator(
        frame_count=len(images),
        frame_loader=lambda frame_index: images[frame_index],
        frame_renderer=frame_renderer,
    )
Exemplo n.º 17
0
# Test of the translated/cleaned up drone sim code.
# creating a 'swarm' of two drones, flying in the
# same formation, just one above the other by 5 units.
from Animator import *
from DroneSim import *

# The waypoints - 'hardcoding' the swarm logic by spacing them enough.
#wps = [[[-5, -5, 0], [5, -5, 0], [5, 5, 0], [-5, 5, 0]],
#       [[-5, -5, 5], [5, -5, 5], [5, 5, 5], [-5, 5, 5]]]
wps = [[[-5, -5, 0], [-5, -1, 3], [-3, -1, 6], [5, 5, 5]]]

sim = DroneSim(wps)
anm = Animator()

sim.wind_vel = [0.01, 0.01, 0.01]

num_timesteps = 140
sim.transition_timestep = 120

for timestep in range(num_timesteps):  # 2000
    sim.timestep = timestep
    sim.tick()
    anm.plot_drones(sim.qrs, sim.learning_mode)
Exemplo n.º 18
0
import Animator
import subprocess

while True:
    s = raw_input(">")
    if s is "q":
        break
    Animator.sendMessage(s)
Exemplo n.º 19
0
    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.sigmoid(self.fc1(x))
        x = F.sigmoid(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
animator = Animator(xlabel='epoch',
                    xlim=[1, 10],
                    ylim=[0, 2],
                    legend=['loss', 'acc'])
# animator.add(epoch + 1, train_metrics + (test_acc,))
animator.add(0, (2, 0))

for epoch in range(10):  # 多批次循环
    running_loss = 0.0
    acc = 0.0
    for i, data in enumerate(trainloader, 0):
        # 获取输入
        inputs, labels = data
        # print(inputs.size())
        # 梯度置0
        optimizer.zero_grad()
        # print(inputs[0], '\ntp = ', type(inputs))     # 输入数据 tensor
        # print(labels[0], '\ntp = ', type(labels))       # 标签 tensor