Exemplo n.º 1
0
 private Layer redraw(final int z) {
   final ArrayList<Sprite.Part> parts = new ArrayList<Sprite.Part>();
   Sprite.Drawer drw =
       new Sprite.Drawer() {
         public void addpart(Sprite.Part p) {
           if (p.z == z) parts.add(p);
         }
       };
   for (Sprite spr : sprites.values()) {
     if (spr != null) spr.setup(drw, Coord.z, Coord.z);
   }
   Collections.sort(parts, Sprite.partcmp);
   Coord ul = new Coord(0, 0);
   Coord lr = new Coord(0, 0);
   for (Sprite.Part part : parts) {
     if (part.ul.x < ul.x) ul.x = part.ul.x;
     if (part.ul.y < ul.y) ul.y = part.ul.y;
     if (part.lr.x > lr.x) lr.x = part.lr.x;
     if (part.lr.y > lr.y) lr.y = part.lr.y;
   }
   BufferedImage buf = TexI.mkbuf(lr.add(ul.inv()).add(1, 1));
   Graphics g = buf.getGraphics();
   /*
   g.setColor(java.awt.Color.RED);
   g.fillRect(0, 0, buf.getWidth(), buf.getHeight());
   */
   for (Sprite.Part part : parts) {
     part.cc = part.cc.add(ul.inv());
     part.draw(buf, g);
   }
   g.dispose();
   return (new Layer(buf, ul.inv()));
 }
Exemplo n.º 2
0
  @Override
  public void awake() {
    rand = new Random();

    texture = new Texture("aiplayer.png");
    spriteBatch = new SpriteBatch();
    sprite = new Sprite(texture);
    collider =
        new BoxCollider(
            new Rect(sprite),
            false,
            new ContactListener() {
              @Override
              public void onContactEnter(Collider collider) {
                if (collider.tag.equals("Ball")) {
                  Vector2 ballVelocity = collider.rigidBody.getVelocity();
                  ballVelocity.set(ballVelocity.getX() * translation * 0.2f, -ballVelocity.getY());
                }
              }
            });
    collider.tag = "Platform";

    sprite.translateY(Application.HEIGHT / 2 - sprite.getWidth() / 2 + 40);
    collider.shape.translateY(Application.HEIGHT / 2 - sprite.getWidth() / 2 + 40);
  }
Exemplo n.º 3
0
  public GameScreen() {
    addKeyListener(new TAdapter());
    addMouseListener(new CustomListener());
    addMouseMotionListener(new CustomListener());
    setFocusable(true);
    setBackground(Color.BLACK);
    setDoubleBuffered(true);
    player = new Sprite();
    player.setX(500);
    player.setY(250);
    player.set_speed(player_speed);
    bullet = new Vector<Bullet>();
    enemy = new Vector<Enemy>();
    v_explosion = new Vector<Explosion>();
    ImageIcon ii =
        new ImageIcon(this.getClass().getResource("Data/Sprite/background/background1.png"));
    fon = ii.getImage();
    timer = new Timer(5, this);
    timer.start();
    timerj = new java.util.Timer();
    timerj.schedule(task, 100);
    ImageIcon ii2 = new ImageIcon(this.getClass().getResource("Data/Sprite/player/explosion.png"));
    explosion = ii2.getImage();

    ImageIcon i3 = new ImageIcon(this.getClass().getResource("Data/Sprite/player/live.png"));
    live = i3.getImage();
    i3 = new ImageIcon(this.getClass().getResource("Data/Sprite/player/str.png"));
    pointer = i3.getImage();
    image_bullet = new Bullet();
    start_game();
  }
Exemplo n.º 4
0
 public synchronized boolean checkhit(Coord c) {
   if (base.get() == null) return (false);
   for (Sprite spr : sprites.values()) {
     if (spr == null) continue;
     if (spr.checkhit(c)) return (true);
   }
   return (false);
 }
Exemplo n.º 5
0
 private synchronized Object[] stateid(Object... extra) {
   Object[] ret = new Object[layers.size() + extra.length];
   for (int i = 0; i < layers.size(); i++) {
     Sprite spr = sprites.get(layers.get(i));
     if (spr == null) ret[i] = null;
     else ret[i] = spr.stateid();
   }
   for (int i = 0; i < extra.length; i++) ret[i + layers.size()] = extra[i];
   return (ArrayIdentity.intern(ret));
 }
Exemplo n.º 6
0
  @Override
  public void update() {
    if (Ball.velocity.getY() > 0) {
      Vector2 p0 = Ball.position;
      Vector2 p1 = Vector2.add(Ball.position, Vector2.one());

      float k = (p0.getY() - p1.getY()) / (p0.getX() - p1.getX());
      float m = p1.getY() - k * p1.getX();
      float x = (sprite.getPosition().getY() - m) / k;

      sprite.setX(Math.min(x, Application.WIDTH / 2));
      collider.shape.setX(Math.min(x, Application.WIDTH / 2));
    }
  }
Exemplo n.º 7
0
 public synchronized void ctick(int dt) {
   for (Map.Entry<Indir<Resource>, Sprite> e : sprites.entrySet()) {
     Indir<Resource> r = e.getKey();
     Sprite spr = e.getValue();
     if (spr != null) {
       int ldt = dt;
       if (delays.get(r) != null) {
         ldt += delays.get(r);
         delays.remove(r);
       }
       spr.tick(ldt);
     } else {
       delays.put(r, delays.get(r) + dt);
     }
   }
 }
 public boolean testCollision(Sprite testSprite) {
   // Check for collision with
   // another sprite
   if (testSprite != this) {
     return spaceOccupied.intersects(testSprite.getSpaceOccupied());
   } // end if
   return false;
 } // end testCollision
Exemplo n.º 9
0
  public void bumpInto(int x, int y) {
    byte block = level.getBlock(x, y);
    if (((Level.TILE_BEHAVIORS[block & 0xff]) & Level.BIT_PICKUPABLE) > 0) {
      Mario.getCoin();
      sound.play(
          Art.samples[Art.SAMPLE_GET_COIN], new FixedSoundSource(x * 16 + 8, y * 16 + 8), 1, 1, 1);
      level.setBlock(x, y, (byte) 0);
      addSprite(new CoinAnim(x, y + 1));

      // TODO no idea when this happens... maybe remove coin count
      if (recorder != null) recorder.recordCoin();
    }

    for (Sprite sprite : sprites) {
      sprite.bumpCheck(x, y);
    }
  }
  public void update() {
    Sprite sprite;

    // Iterate through sprite list
    for (int cnt = 0; cnt < size(); cnt++) {
      sprite = (Sprite) elementAt(cnt);
      // Update a sprite's position
      sprite.updatePosition();

      // Test for collision. Positive
      // result indicates a collision
      int hitIndex = testForCollision(sprite);
      if (hitIndex >= 0) {
        // a collision has occurred
        bounceOffSprite(cnt, hitIndex);
      } // end if
    } // end for loop
  } // end update
  /** Force a packet to be sent. */
  public void sendPacket() {
    // Also save stuff to a player's local hard-drive.

    if (activationEvent) {
      View MyView = MyHacker.getView();
      Object[] send =
          new Object[] {new Integer(activationID), new Integer(activationType), MyHacker.getIP()};
      MyView.addFunctionCall(
          new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER, "hacktendoActivate", send));
    } else if (targetEvent) {
      View MyView = MyHacker.getView();
      Object[] send = null;
      if (playerSprite != null)
        send =
            new Object[] {
              new Integer(targetX),
              new Integer(targetY),
              MyHacker.getIP(),
              new Integer(playerSprite.getX()),
              new Integer(playerSprite.getY())
            };
      else
        send =
            new Object[] {
              new Integer(targetX),
              new Integer(targetY),
              MyHacker.getIP(),
              new Integer(targetX),
              new Integer(targetY)
            };

      MyView.addFunctionCall(
          new RemoteFunctionCall(Hacker.HACKTENDO_PLAYER, "hacktendoTarget", send));
    }

    activationEvent = false;
    targetEvent = false;
  }
 private void bounceOffSprite(int oneHitIndex, int otherHitIndex) {
   // Swap motion vectors for
   // bounce algorithm
   Sprite oneSprite = (Sprite) elementAt(oneHitIndex);
   Sprite otherSprite = (Sprite) elementAt(otherHitIndex);
   Point swap = oneSprite.getMotionVector();
   oneSprite.setMotionVector(otherSprite.getMotionVector());
   otherSprite.setMotionVector(swap);
 } // end bounceOffSprite()
 public void ctick(int dt) {
   int dt2 = dt + initdelay;
   initdelay = 0;
   for (GAttrib a : attr.values()) {
     if (a instanceof Drawable) a.ctick(dt2);
     else a.ctick(dt);
   }
   for (Iterator<Overlay> i = ols.iterator(); i.hasNext(); ) {
     Overlay ol = i.next();
     if (ol.spr == null) {
       if (((getattr(Drawable.class) == null) || (getneg() != null)) && (ol.res.get() != null))
         ol.spr = Sprite.create(this, ol.res.get(), ol.sdt);
     } else {
       boolean done = ol.spr.tick(dt);
       if ((!ol.delign || (ol.spr instanceof Overlay.CDel)) && done) i.remove();
     }
   }
 }
 private int testForCollision(Sprite testSprite) {
   // Check for collision with other
   // sprites
   Sprite sprite;
   for (int cnt = 0; cnt < size(); cnt++) {
     sprite = (Sprite) elementAt(cnt);
     if (sprite == testSprite)
       // don't check self
       continue;
     // Invoke testCollision method
     // of Sprite class to perform
     // the actual test.
     if (testSprite.testCollision(sprite))
       // Return index of colliding
       // sprite
       return cnt;
   } // end for loop
   return -1; // No collision detected
 } // end testForCollision()
Exemplo n.º 15
0
 public synchronized void setup(Sprite.Drawer drw, final Coord cc, final Coord off) {
   if (base.get() == null) return;
   if (loading) {
     loading = false;
     for (Indir<Resource> r : layers) {
       if (sprites.get(r) == null) {
         if (r.get() == null) loading = true;
         else sprites.put(r, Sprite.create(gob, r.get(), null));
       }
     }
   }
   /* XXX: Fix this to construct parts dynamically depending on
    * which layers exist. */
   Sprite.Part me;
   me = makepart(0);
   me.setup(cc, off);
   drw.addpart(me);
   me = makepart(-10);
   me.setup(cc, off);
   drw.addpart(me);
 }
Exemplo n.º 16
0
  public void compute() {
    for (int i = 0; i < bullet.size(); i++) {
      bullet.get(i).bullet_x = bullet.get(i).bullet_x + 3 * bullet.get(i).current_direction_x;
      bullet.get(i).bullet_y = bullet.get(i).bullet_y + 3 * bullet.get(i).current_direction_y;
    }
    for (int i = 0; i < bullet.size(); i++) {
      if (bullet.get(i).bullet_x > 1366
          || bullet.get(i).bullet_x < 0
          || bullet.get(i).bullet_y > 768
          || bullet.get(i).bullet_y < 0) bullet.remove(i);
    }
    // Check collision bullet with enemy
    for (int i = 0; i < bullet.size(); i++) {
      for (int j = 0; j < enemy.size(); j++) {
        if (collision.collision_bullet_enemy(
                18,
                (int) bullet.get(i).bullet_x + 18,
                (int) bullet.get(i).bullet_y + 18, // bullet
                (int) enemy.get(j).getX(),
                (int) enemy.get(j).getY(), // point x1, y1
                (int) enemy.get(j).getX() + (int) enemy.get(j).get_spr_w(),
                (int) enemy.get(j).getY(), // point x2, y2
                (int) enemy.get(j).getX() + (int) enemy.get(j).get_spr_w(),
                (int) enemy.get(j).getY() + (int) enemy.get(j).get_spr_h(),
                (int) enemy.get(j).getX(),
                (int) enemy.get(j).getY() + (int) enemy.get(j).get_spr_h() // point x4, y4
                )
            == true) {
          //	create_explosion(bullet.get(i).bullet_x, bullet.get(i).bullet_y);
          if (bullet.get(i).get_type() == 's') // simple bullet
          {
            enemy.get(j).dec_live();
          }
          if (bullet.get(i).get_type() == 'f') // fireball
          {
            enemy.get(j).dec_live();
            enemy.get(j).dec_live();
          }
          if (bullet.get(i).get_type() == 'r') // rocket
          {
            enemy.get(j).dec_live();
            enemy.get(j).dec_live();
            enemy.get(j).dec_live();
          }
          if (enemy.get(j).get_live() <= 0) {
            enemy.remove(j);
          } else // push enemy
          {
            enemy.get(j).push();
          }
          bullet.remove(i);
          break;
        }
      }
    }
    // Преследование игрока
    for (int i = 0; i < enemy.size(); i++) {
      if (enemy.get(i).get_type() == "enemy1"
          || enemy.get(i).get_type() == "enemy2"
          || enemy.get(i).get_type() == "enemy3") {
        angle2 =
            Math.atan2(player.getY() - enemy.get(i).getY(), player.getX() - enemy.get(i).getX())
                * 180
                / 3.14;
        double a = player.getX() - enemy.get(i).getX();
        double b = player.getY() - enemy.get(i).getY();
        double kvadrat = Math.sqrt((a * a + b * b));
        double tempx = a / kvadrat;
        double tempy = Math.sqrt(1 - tempx * tempx);
        if (b < 0) tempy = -tempy;
        enemy.get(i).v_x = enemy.get(i).speed * tempx;
        enemy.get(i).v_y = enemy.get(i).speed * tempy;
        enemy.get(i).setX((enemy.get(i).getX() + enemy.get(i).speed * tempx));
        enemy.get(i).setY((enemy.get(i).getY() + enemy.get(i).speed * tempy));
      } else {
        if (enemy.get(i).created == false) {
          angle2 =
              Math.atan2(player.getY() - enemy.get(i).getY(), player.getX() - enemy.get(i).getX())
                  * 180
                  / 3.14;
          double a = player.getX() - enemy.get(i).getX();
          double b = player.getY() - enemy.get(i).getY();
          double kvadrat = Math.sqrt((a * a + b * b));
          double tempx = a / kvadrat;
          double tempy = Math.sqrt(1 - tempx * tempx);
          if (b < 0) tempy = -tempy;
          enemy.get(i).v_x = enemy.get(i).speed * tempx;
          enemy.get(i).v_y = enemy.get(i).speed * tempy;
          enemy.get(i).created = true;
        }
        enemy.get(i).setX((enemy.get(i).getX() + enemy.get(i).get_vx()));
        enemy.get(i).setY((enemy.get(i).getY() + enemy.get(i).get_vy()));
      }
    }
    for (int j = 0; j < enemy.size(); j++) {
      if (collision.collision_with_box(
              (int) player.getX() + 14,
              (int) player.getY() + 28,
              (int) player.getX() + 114,
              (int) player.getY() + 95,
              (int) enemy.get(j).getX() + 22,
              (int) enemy.get(j).getY() + 30,
              (int) enemy.get(j).getX() + 102,
              (int) enemy.get(j).getY() + 96)
          == true) {
        enemy.remove(j);
        player_live--;
        if (player_live == 0) {
          JOptionPane.showMessageDialog(null, "Game over!");
          start_game();
        }
      }
    }
    if (time_game > frequency) {
      generate_enemy();
      time_game = 0;
    }
    if (left_mouse_pressed == true && allow_shoot == true) {}

    time_game += 0.01;
    frequency -= 0.0001;
  }
Exemplo n.º 17
0
 /** Get the Key used in comparison. */
 public Object getKey(Object o) {
   Sprite S = (Sprite) o;
   return (new Integer(S.getZ()));
 }
  /** Update or add a sprite to the client side game. */
  public void addPacket(HacktendoPacket Packet) {
    while (!getInitialized()) { // Make sure things have loaded before we start mucking with stuff.
      try {
        Thread.sleep(5);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    do {
      Sprite S = (Sprite) Sprites.get(new Integer(Packet.getID()));
      boolean setRenderType = false;
      if (S == null) {
        S = new Sprite(this);
        setRenderType = true;
        S.setParameter("destroy", new TypeBoolean(false));
        S.setParameter("globalID", new TypeInteger(Packet.getID()));
        S.setParameter("id", new TypeInteger(Packet.getID()));
        Sprites.put(new Integer(Packet.getID()), S);
        S.setOffscreenProcessing(false);
      }
      S.setScriptID(Packet.getScriptID());
      S.setImageID(Packet.getImage());

      if (S.getSpriteID() != playerID || setRenderType) { // Allow the sprite to move client side.
        S.setX(Packet.getX());
        S.setY(Packet.getY());
        S.setZ(Packet.getZ());
        S.setParameter("xTarget", new TypeInteger(Packet.getTargetX()));
        S.setParameter("yTarget", new TypeInteger(Packet.getTargetY()));
        S.setParameter("newTarget", new TypeBoolean(true));
      }

      if (Packet.getExplodeSprite()) S.explode();
      if (Packet.getDestroySprite()) S.setParameter("destroy", new TypeBoolean(true));
      S.setFrame(Packet.getFrame());
      S.setXRotation(Packet.getXRotation());
      S.setYRotation(Packet.getYRotation());
      S.setZRotation(Packet.getZRotation());

      S.setWidth(Packet.getWidth());
      S.setHeight(Packet.getHeight());
      S.setDepth(Packet.getDepth());
      S.setZOffset(Packet.getZOffset() * -1);

      if (setRenderType) S.setRenderType(Packet.getRenderType());

    } while (Packet.next() > 0);

    // Takes the form Object[]{ID,IP,Name,NPC,BODY_ID}
    if (Packet.getReferenceArray() != null) {
      for (int i = 0; i < Packet.getReferenceArray().size(); i++) {
        Object O[] = (Object[]) Packet.getReferenceArray().get(i);
        Sprite S = (Sprite) Sprites.get((Integer) O[0]);

        System.out.println("ID: " + O[0]);
        if (S != null) {
          String ip = (String) O[1];
          String name = (String) O[2];
          boolean npc = (Boolean) O[3];

          S.setParameter("ip", new TypeString(ip));
          S.setParameter("name", new TypeString(name));
          S.setParameter("npc", new TypeBoolean(npc));

          if (S.getScriptID() == SPRITE_SCRIPT) {
            S.setOffscreenProcessing(true);
            S.setAutoCollide(true);
            Sprite S2 = (Sprite) Sprites.get((Integer) O[4]);
            S.setParameter("body", new TypeInteger(S2.getSpriteID()));
          }

          if (ip.equals(MyHacker.getIP())) {
            if (S.getScriptID() == SPRITE_SCRIPT) {
              playerSprite = S;
            }
            playerID = S.getSpriteID();
            System.out.println(
                "We are setting the player to equal : "
                    + S.getSpriteID()
                    + " This Is Sprite ID: "
                    + O[0]);
            HacktendoLinker.addGlobal("player", new TypeInteger(S.getSpriteID()));
          }
        }
      }
    }
  }
Exemplo n.º 19
0
  public void tick() {
    timeLeft--;

    if (widthArrow < 0) {
      widthArrow *= -1;
      tipWidthArrow *= -1;

      xPositionsArrow =
          new int[] {
            xArrow + -widthArrow / 2,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + widthArrow / 2,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + widthArrow / 2 - tipWidthArrow,
            xArrow + -widthArrow / 2
          };
      yPositionsArrow =
          new int[] {
            yArrow + -heightArrow / 4,
            yArrow + -heightArrow / 4,
            yArrow + -heightArrow / 2,
            yArrow + 0,
            yArrow + heightArrow / 2,
            yArrow + heightArrow / 4,
            yArrow + heightArrow / 4
          };
    }

    if (timeLeft == 0) {
      mario.dieTime();
    }

    xCamO = xCam;
    yCamO = yCam;

    if (startTime > 0) {
      startTime++;
    }

    float targetXCam = mario.x - 160;

    xCam = targetXCam;

    if (xCam < 0) xCam = 0;
    if (xCam > level.getWidth() * 16 - 320) xCam = level.getWidth() * 16 - 320;

    /*      if (recorder != null)
    {
    recorder.addTick(mario.getKeyMask());
    }

    if (replayer!=null)
    {
    mario.setKeys(replayer.nextTick());
    }*/

    fireballsOnScreen = 0;

    for (Sprite sprite : sprites) {
      if (sprite != mario) {
        float xd = sprite.x - xCam;
        float yd = sprite.y - yCam;
        if (xd < -64 || xd > 320 + 64 || yd < -64 || yd > 240 + 64) {
          removeSprite(sprite);
        } else {
          if (sprite instanceof Fireball) {
            fireballsOnScreen++;
          }
        }
      }
    }

    if (paused) {
      for (Sprite sprite : sprites) {
        if (sprite == mario) {
          sprite.tick();
        } else {
          sprite.tickNoMove();
        }
      }
    } else {

      tick++;
      level.tick();

      boolean hasShotCannon = false;
      int xCannon = 0;

      for (int x = (int) xCam / 16 - 1; x <= (int) (xCam + layer.width) / 16 + 1; x++)
        for (int y = (int) yCam / 16 - 1; y <= (int) (yCam + layer.height) / 16 + 1; y++) {
          int dir = 0;

          if (x * 16 + 8 > mario.x + 16) dir = -1;
          if (x * 16 + 8 < mario.x - 16) dir = 1;

          SpriteTemplate st = level.getSpriteTemplate(x, y);

          if (st != null) {
            if (st.lastVisibleTick != tick - 1) {
              if (st.sprite == null || !sprites.contains(st.sprite)) {
                st.spawn(this, x, y, dir);
              }
            }

            st.lastVisibleTick = tick;
          }

          if (dir != 0) {
            byte b = level.getBlock(x, y);
            if (((Level.TILE_BEHAVIORS[b & 0xff]) & Level.BIT_ANIMATED) > 0) {
              if ((b % 16) / 4 == 3 && b / 16 == 0) {
                if ((tick - x * 2) % 100 == 0) {
                  xCannon = x;
                  for (int i = 0; i < 8; i++) {
                    addSprite(
                        new Sparkle(
                            x * 16 + 8,
                            y * 16 + (int) (Math.random() * 16),
                            (float) Math.random() * dir,
                            0,
                            0,
                            1,
                            5));
                  }
                  addSprite(new BulletBill(this, x * 16 + 8 + dir * 8, y * 16 + 15, dir));
                  hasShotCannon = true;
                }
              }
            }
          }
        }

      if (hasShotCannon) {
        sound.play(
            Art.samples[Art.SAMPLE_CANNON_FIRE],
            new FixedSoundSource(xCannon * 16, yCam + 120),
            1,
            1,
            1);
      }

      for (Sprite sprite : sprites) {
        sprite.tick();
      }

      for (Sprite sprite : sprites) {
        sprite.collideCheck();
      }

      for (Shell shell : shellsToCheck) {
        for (Sprite sprite : sprites) {
          if (sprite != shell && !shell.dead) {
            if (sprite.shellCollideCheck(shell)) {
              if (mario.carried == shell && !shell.dead) {
                mario.carried = null;
                shell.die();
              }
            }
          }
        }
      }
      shellsToCheck.clear();

      for (Fireball fireball : fireballsToCheck) {
        for (Sprite sprite : sprites) {
          if (sprite != fireball && !fireball.dead) {
            if (sprite.fireballCollideCheck(fireball)) {
              fireball.die();
            }
          }
        }
      }
      fireballsToCheck.clear();
    }

    sprites.addAll(0, spritesToAdd);
    sprites.removeAll(spritesToRemove);
    spritesToAdd.clear();
    spritesToRemove.clear();

    // TODO: THIS IS TEST FLIP
    //        if(keys[Mario.KEY_UP] && tick%2 == 0)
    //        	level.startFlipping = true;

    //        if(level.canFlip)
    //        	flip();
  }
Exemplo n.º 20
0
  public void render(Graphics g, float alpha) {
    int xCam = (int) (mario.xOld + (mario.x - mario.xOld) * alpha) - 160;
    int yCam = (int) (mario.yOld + (mario.y - mario.yOld) * alpha) - 120;
    // int xCam = (int) (xCamO + (this.xCam - xCamO) * alpha);
    //        int yCam = (int) (yCamO + (this.yCam - yCamO) * alpha);
    if (xCam < 0) xCam = 0;
    if (yCam < 0) yCam = 0;
    if (xCam > level.getWidth() * 16 - 320) xCam = level.getWidth() * 16 - 320;
    if (yCam > level.getHeight() * 16 - 240) yCam = level.getHeight() * 16 - 240;

    //      g.drawImage(Art.background, 0, 0, null);

    for (int i = 0; i < 2; i++) {
      bgLayer[i].setCam(xCam, yCam);
      bgLayer[i].render(g, tick, alpha);
    }

    g.translate(-xCam, -yCam);
    for (Sprite sprite : sprites) {
      if (sprite.layer == 0) sprite.render(g, alpha);
    }
    g.translate(xCam, yCam);

    //////////// THIS RENDERS THE LEVEL
    layer.setCam(xCam, yCam);
    layer.render(g, tick, paused ? 0 : alpha);
    layer.renderExit0(g, tick, paused ? 0 : alpha, mario.winTime == 0);
    //////////// END OF LEVEL RENDER

    //////////// RENDERS SPRITES
    g.translate(-xCam, -yCam);
    for (Sprite sprite : sprites) {
      if (sprite.layer == 1) sprite.render(g, alpha);
    }
    g.translate(xCam, yCam);
    g.setColor(Color.BLACK);
    layer.renderExit1(g, tick, paused ? 0 : alpha);
    //////////// END OF SPRITE RENDERING

    drawStringDropShadow(g, "MARIO " + df.format(Mario.lives), 0, 0, 7);
    //        drawStringDropShadow(g, "00000000", 0, 1, 7);

    drawStringDropShadow(g, "COIN", 14, 0, 7);
    drawStringDropShadow(g, " " + df.format(Mario.coins), 14, 1, 7);

    drawStringDropShadow(g, "WORLD", 24, 0, 7);
    drawStringDropShadow(g, " " + Mario.levelString, 24, 1, 7);

    drawStringDropShadow(g, "TIME", 35, 0, 7);
    int time = (timeLeft + TPS - 1) / TPS;
    if (time < 0) time = 0;
    drawStringDropShadow(g, " " + df2.format(time), 35, 1, 7);

    renderDirectionArrow(g);

    if (startTime > 0) {
      float t = startTime + alpha - 2;
      t = t * t * 0.6f;
      renderBlackout(g, 160, 120, (int) (t));
    }
    //        mario.x>level.xExit*16
    if (mario.winTime > 0) {
      float t = mario.winTime + alpha;
      t = t * t * 0.2f;

      if (t > 0) {
        if (recorder != null) {
          recorder.stopRecord();
          recorder.levelWon();
          //                	recorder.printAll();
        }
      }

      if (t > 900) {

        winActions();
        return;

        //              replayer = new Replayer(recorder.getBytes());
        //                init();
      }

      renderBlackout(
          g, (int) (mario.xDeathPos - xCam), (int) (mario.yDeathPos - yCam), (int) (320 - t));
    }

    if (mario.deathTime > 0) {
      g.setColor(Color.BLACK);
      float t = mario.deathTime + alpha;
      t = t * t * 0.4f;

      if (t > 0 && Mario.lives <= 0) {
        if (recorder != null) {
          recorder.stopRecord();
        }
      }

      if (t > 1800) {
        Mario.lives--;
        deathActions();
      }

      renderBlackout(
          g, (int) (mario.xDeathPos - xCam), (int) (mario.yDeathPos - yCam), (int) (320 - t));
    }
  }
Exemplo n.º 21
0
  // Konstruktor mängu objekti loomiseks
  public GameView() {
    this.setHeight(600);
    this.setWidth(800);
    this.currentLevel = startingLevel;

    // kasutajad, loome kasutades collision box muutujate modifitseerimisega konstruktorit
    user1.setImage("images/kasutaja1sinine.png");
    user1.setPosition(200, 355);
    user1.setMoveLeft("Q");
    user1.setMoveRight("W");

    user2.setImage("images/kasutaja2punane.png");
    user2.setPosition(600, 365);
    user2.setMoveLeft("LEFT");
    user2.setMoveRight("RIGHT");

    this.setOnKeyPressed(
        e -> {
          String code = e.getCode().toString();
          if (!input.contains(code)) input.add(code);
        });

    this.setOnKeyReleased(
        e -> {
          String code = e.getCode().toString();
          input.remove(code);
        });

    Canvas canvas = new Canvas(800, 600);
    GraphicsContext gc = canvas.getGraphicsContext2D();
    this.getChildren().add(canvas);

    gc.setFont(theFont);
    gc.setLineWidth(1);

    // Mänguekraanil olevad kujutised ja pildid
    Sprite skyBackgroundSprite = new Sprite();
    skyBackgroundSprite.setImage("images/taevas.png");
    skyBackgroundSprite.setPosition(0, 0);

    Sprite grassSprite = new Sprite();
    grassSprite.setImage("images/grass2.png");
    grassSprite.setPosition(0, 540);
    LongValue lastNanoTime = new LongValue(System.nanoTime());

    // See on toiduloopija, mis lisav toitu meie foodList-i
    // timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 600);
    // timer.scheduleAtFixedRate(new HealthPotionFallingTask(), 5000, 10000);

    animationTimer =
        new AnimationTimer() {
          public void handle(long currentNanoTime) {
            // calculate time since last update.
            gc.clearRect(0, 0, 800, 600);
            skyBackgroundSprite.render(gc);

            double elapsedTime = (currentNanoTime - lastNanoTime.value) / 1000000000.0;
            lastNanoTime.value = currentNanoTime;

            // anname kasutajatele kiirust vastavalt vajutatud klahvidele
            user1.setVelocity(0, 0);
            if (input.contains(user1.getMoveLeft()) && user1.getPositionX() > -80)
              user1.addVelocity(-150, 0);
            if (input.contains(user1.getMoveRight()) && user1.getPositionX() < 750)
              user1.addVelocity(150, 0);

            user2.setVelocity(0, 0);
            if (input.contains(user2.getMoveLeft()) && user2.getPositionX() > -80)
              user2.addVelocity(-150, 0);
            if (input.contains(user2.getMoveRight()) && user2.getPositionX() < 720)
              user2.addVelocity(150, 0);

            grassSprite.render(gc);
            // liigutame kasutajaid
            user2.update(elapsedTime);
            user1.update(elapsedTime);
            user1.render(gc);
            user2.render(gc);

            // LEVELITE haldus

            if (currentLevel == 0 && usersCombinedScore > level1Threshold) {
              currentLevel++;
              timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 1000);
              fallingStuffSpeed = level1Speed;
              nextLevelAt = level2Threshold;
            } else if (currentLevel == 1 && usersCombinedScore > level2Threshold) {
              currentLevel++;
              fallingStuffSpeed = level2Speed;
              timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 1000);
              nextLevelAt = level3Threshold;
            } else if (currentLevel == 2 && usersCombinedScore > level3Threshold) {
              currentLevel++;
              fallingStuffSpeed = level3Speed;
              nextLevelAt = level4Threshold;
            } else if (currentLevel == 3 && usersCombinedScore > level4Threshold) {
              currentLevel++;
              fallingStuffSpeed = level4Speed;
              timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 1000);
              nextLevelAt = level5Threshold;
            } else if (currentLevel == 4 && usersCombinedScore > level5Threshold) {
              currentLevel++;
              fallingStuffSpeed = level5Speed;
              nextLevelAt = level6Threshold;
              timer.scheduleAtFixedRate(new HealthPotionFallingTask(), 0, 10000);
            } else if (currentLevel == 5 && usersCombinedScore > level6Threshold) {
              currentLevel++;
              fallingStuffSpeed = level6Speed;
              timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 1000);
              nextLevelAt = level7Threshold;
            } else if (currentLevel == 6 && usersCombinedScore > level7Threshold) {
              currentLevel++;
              fallingStuffSpeed = level7Speed;
              nextLevelAt = level8Threshold;
            } else if (currentLevel == 7 && usersCombinedScore > level8Threshold) {
              currentLevel++;
              fallingStuffSpeed = level8Speed;
              timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 1000);
              nextLevelAt = level9Threshold;
              timer.scheduleAtFixedRate(new HealthPotionFallingTask(), 0, 10000);
            } else if (currentLevel == 8 && usersCombinedScore > level9Threshold) {
              currentLevel++;
              fallingStuffSpeed = level9Speed;
              nextLevelAt = level10Threshold;
            } else if (currentLevel == 9 && usersCombinedScore > level10Threshold) {
              currentLevel++;
              fallingStuffSpeed = level10Speed;
              timer.scheduleAtFixedRate(new FoodThrowingTask(), 0, 500);
              timer.scheduleAtFixedRate(new HealthPotionFallingTask(), 0, 5000);
              nextLevelAt = 9999;
            }

            // kokkupõrgete avastamine ja nendele vastavad tegevused
            Iterator<Potion> potionIter = potionsList.iterator();
            while (potionIter.hasNext()) {
              try {
                Potion potionSprite = potionIter.next();
                potionSprite.fallingStuffSpeed = fallingStuffSpeed;
                potionSprite.render(gc);
                if (user1.intersects(potionSprite) || user2.intersects(potionSprite)) {
                  if (healthRemaining < healthAtStart) {
                    healthRemaining++;
                    System.out.println("Yey, you got a brand new heart");
                  }
                  setHealthoMeter();
                  potionIter.remove();
                } else if (potionSprite.intersects(grassSprite)) {
                  potionIter.remove();
                }
                potionSprite.update(elapsedTime);
              } catch (ConcurrentModificationException e) {
                System.out.println("Mitu asja sai korraga otsa. Pole erilist probleemi.");
                break;
              }
            }

            // kokkupõrgete avastamine ja nendele vastavad tegevused
            Iterator<Food> foodIter = foodList.iterator();
            while (foodIter.hasNext()) {
              try {
                Food foodSprite = foodIter.next();
                foodSprite.render(gc);
                foodSprite.fallingStuffSpeed = fallingStuffSpeed;
                if (user1.intersects(foodSprite) || user2.intersects(foodSprite)) {
                  if (foodSprite.good) {
                    usersCombinedScore += 10; // kui toit oli tervislik suurendame skoori
                    PlaySound("src/sounds/213424__taira-komori__short-pickup03.mp3");
                  } else {
                    healthRemaining--; // kui toit oli paha, vähendame elusid
                    setHealthoMeter(); // uuenda elude näitamise mõõdikut
                    PlaySound("src/sounds/249615__vincentm400__confirm.mp3");
                  }
                  foodIter.remove(); // viska toit minema
                } else if (foodSprite.intersects(grassSprite)) {
                  foodIter.remove();
                  if (foodSprite.good) {
                    usersCombinedScore--;
                    PlaySound("src/sounds/149899__animationisaac__box-crash.mp3");
                  }
                }
                foodSprite.update(elapsedTime);
              } catch (ConcurrentModificationException e) {
                System.out.println("Mitu asja sai korraga otsa. Pole erilist probleemi.");
                break;
              }
            }

            // Näita elusid, mis järgi on
            gc.drawImage(healthoMeter, 140, 8);

            // Näita levelit ja skoori mis vaja järgmiseks
            gc.setFill(Color.GREEN);
            gc.setStroke(Color.BLACK);
            String pointsText = "TASE: " + currentLevel + " (järgmine: " + nextLevelAt + " punkti)";
            gc.fillText(pointsText, 260, 36);
            gc.strokeText(pointsText, 260, 36);

            // Näita hea skoori suurust
            String goodPointsText = "PUNKTE:" + (usersCombinedScore);
            gc.setFill(Color.PURPLE);
            gc.setStroke(Color.DARKBLUE);
            gc.fillText(goodPointsText, 400, 62);
            gc.strokeText(goodPointsText, 400, 62);

            /**
             * MEGA TÄHTIS!!! Lõpetab mängu kui elud otsa saavad. Muudab m2ngLbi
             * SimpleBooleanProperty variably, millele on ehitatud kuulaja Main meetodi jaoks. Sealt
             * käivitub HighScoreide kuvamine
             */
            if (healthRemaining < 1) {
              stopGame();
              gameOver.set(true);
            }
          }
        };

    // tekitab ajastaja, mis loobib iga 0,8s tagant toitu alla
  }
Exemplo n.º 22
0
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    c.getAlpha();
    g.setFont(font2);
    g.setColor(c);
    g.drawImage(fon, 0, 0, 1024, 700, null);

    if (type_bullet1 == true) g.drawImage(pointer, 30, 550, 49, 47, null);

    image_bullet = new Sphere();
    g.drawImage(image_bullet.getImage(), 40, 600, 24, 24, null);
    g.drawString(Integer.toString(count_sphere), 35, 650);

    if (type_bullet2 == true) g.drawImage(pointer, 85, 550, 49, 47, null);
    image_bullet = new FireBall();
    g.drawImage(image_bullet.getImage(), 95, 600, 24, 24, null);
    g.drawString(Integer.toString(count_fireball), 95, 650);

    if (type_bullet3 == true) g.drawImage(pointer, 140, 550, 49, 47, null);
    image_bullet = new Rocket();
    g.drawImage(image_bullet.getImage(), 145, 595, 40, 40, null);
    g.drawString(Integer.toString(count_rocket), 150, 650);
    distance = 10;
    // Draw life
    for (int i = 0; i < player_live; i++) {
      g.drawImage(live, distance, 10, 11, 57, null);
      distance += 20;
    }
    // Create bullet
    for (int i = 0; i < bullet.size(); i++) {
      if (type_bullet1 == true && count_sphere > 0) {
        g2d.drawImage(
            bullet.get(i).getImage(),
            (int) bullet.get(i).bullet_x,
            (int) bullet.get(i).bullet_y,
            this);
      }
      if (type_bullet2 == true && count_fireball > 0) {
        g2d.drawImage(
            bullet.get(i).getImage(),
            (int) bullet.get(i).bullet_x,
            (int) bullet.get(i).bullet_y,
            this);
      }
      if (type_bullet3 == true && count_rocket != 0) {
        bullet.get(i).set_rotate(angle);
        g2d.setTransform(bullet.get(i).rotateX());
        g2d.drawImage(
            bullet.get(i).getImage(),
            (int) bullet.get(i).bullet_x,
            (int) bullet.get(i).bullet_y,
            this);
      }
    }
    g2d.setTransform(player.rotateX(angle));
    g2d.drawImage(player.getImage(), (int) player.getX(), (int) player.getY(), this);
    for (int i = 0; i < v_explosion.size(); i++) {
      g.drawImage(explosion, (int) v_explosion.get(i).x, (int) v_explosion.get(i).y, 59, 57, null);
    }
    for (int i = 0; i < enemy.size(); i++) {
      double povorot3 =
          Math.atan2(player.getY() - enemy.get(i).getY(), player.getX() - enemy.get(i).getX())
              * 180
              / 3.14;
      g2d.setTransform(enemy.get(i).rotateX(povorot3)); // new	
      g2d.drawImage(
          enemy.get(i).getImage(), (int) enemy.get(i).getX(), (int) enemy.get(i).getY(), this);
      g2d.setTransform(enemy.get(i).rotateX(0)); // new
      g.drawString(
          Integer.toString(enemy.get(i).get_live()),
          (int) enemy.get(i).getX() + (int) enemy.get(i).get_spr_w() / 2,
          (int) enemy.get(i).getY());
    }
    g.setFont(font);
    g2d.setTransform(affine);
    g.drawString("Level: " + Integer.toString(level), 710, 50);
    g.drawString("Next level: " + Integer.toString(time_level), 710, 90);
  }
Exemplo n.º 23
0
 public void addSprite(Sprite sprite) {
   spritesToAdd.add(sprite);
   sprite.tick();
 }
Exemplo n.º 24
0
 public void actionPerformed(ActionEvent e) {
   compute();
   player.move();
   repaint();
 }
Exemplo n.º 25
0
 @Override
 public void draw() {
   sprite.draw(spriteBatch);
 }