Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                h1#loading Loading...
canvas#canvas

              
            
!

CSS

              
                body {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
  font-family: "VT323", sans-serif;
  background: #67a7cb;
}

canvas {
  display: none;
  border: 10px solid #0a2839;
}

              
            
!

JS

              
                const KEY_MAP = {
  KeyD: "right",
  ArrowRight: "right",
  KeyA: "left",
  ArrowLeft: "left",
  Space: "accept"
};

const MIN_CATCHING_TIME = 2000;
const MAX_CATCHING_TIME = 4000;
const BITING_TIME = 5000;

const DIRECTIONS = {
  LEFT: "LEFT",
  RIGHT: "RIGHT"
};

const DIRECTION_CHANGE_CHANCE = 0.025;
const BLACK_COLOR = "#000000";
const BACKGROUND_COLORS = ["#30bfff", "#19b7ff", "#06A9F3", "#2196F3"];

const FISH = [
  "Golden Trout",
  "Amber Trout",
  "Catfish",
  "Striped Bass",
  "Nothern Pike",
  "Silverfish",
  "Red Herring",
  "Bluegill",
  "Vampire Squid",
  "Horsheshoe Crab",
  "Red Gunard",
  "Gourami",
  "Moonfin"
];

const randomIntFromInterval = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

class FishingGame {
  constructor() {
    this.initialise();
  }
  initialise() {
    this.lastRender = 0;
    this.canvas = document.querySelector("#canvas");
    this.loadingElement = document.querySelector("#loading");
    this.ctx = this.canvas.getContext("2d");
    this.width = 500;
    this.height = 500;
    this.centerWidth = this.width / 2;
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    this.pressedKeys = {};

    this.started = false;
    this.catching = false;
    this.fishBiting = false;
    this.fishOnLine = false;
    this.successfullCatch = false;
    this.fishBitingTimeoutID = null;
    this.waitingForBiteTimeoutID = null;

    this.fishPosition = 50;
    this.playerPosition = 50;
    this.playerWidth = 28;
    this.fishWidth = 15;
    this.progress = 0;
    this.fishDirection = "LEFT";
    this.fish = null;
    this.pixelScale = 5;
    this.noiseScale = 70;
    this.noise = new SimplexNoise();
    this.time = 0;
    this.fishDirectionTimer = 200;
    this.miniGameWidth = 400;
    this.miniGameBounds = {
      top: Math.ceil(this.height / 2),
      left: Math.ceil(this.width / 2 - this.miniGameWidth / 2),
      right: Math.ceil(this.width / 2 + this.miniGameWidth / 2)
    };
    this.fishSpeeds = {
      1: 1.9,
      2: 2.2,
      3: 2.3
    };
    this.fishSpeed = this.fishSpeeds["2"];

    window.addEventListener("keydown", this.keydown.bind(this), false);
    window.addEventListener("keyup", this.keyup.bind(this), false);

    window.requestAnimationFrame((timestamp) => {
      this.loadingElement.style.display = "none";
      this.canvas.style.display = "block";
      this.loop(timestamp);
    });
  }
  keydown(e) {
    const action = KEY_MAP[e.code];
    e.preventDefault();
    if (action) {
      this.pressedKeys[action] = true;
    }
  }
  keyup(e) {
    const action = KEY_MAP[e.code];
    e.preventDefault();
    if (action) {
      this.pressedKeys[action] = false;
    }
  }
  update(progress) {
    const p = progress / 24;
    const fishMovement = p / this.fishSpeed;
    const playerMovement = p / 1.8;

    const updatePlayer = () => {
      if (
        this.pressedKeys[KEY_MAP.ArrowRight] &&
        this.playerPosition < 100 - this.playerWidth
      ) {
        this.playerPosition += playerMovement;
      } else if (
        this.pressedKeys[KEY_MAP.ArrowLeft] &&
        this.playerPosition > 0
      ) {
        this.playerPosition -= playerMovement;
      }
    };

    const updateFish = () => {
      this.fishDirectionTimer -= p;
      const currentDirection = this.fishDirection;
      if (this.fishPosition <= 0) {
        this.fishDirection = DIRECTIONS.RIGHT;
        this.fishPosition = 1;
      } else if (this.fishPosition >= 100 - this.fishWidth) {
        this.fishDirection = DIRECTIONS.LEFT;
        this.fishPosition = 100 - this.fishWidth;
      } else {
        let changeDirection = Math.random() < DIRECTION_CHANGE_CHANCE;
        if (this.fishPosition < 30 || this.fishPosition > 60) {
          changeDirection = changeDirection * 6;
        }
        if (changeDirection && this.fishDirectionTimer <= 0) {
          this.fishDirection =
            this.fishDirection === DIRECTIONS.LEFT
              ? DIRECTIONS.RIGHT
              : DIRECTIONS.LEFT;
          this.fishDirectionTimer = 200;
        }
      }
      if (this.fishDirection !== currentDirection) {
        this.fishSpeed = this.fishSpeeds[
          randomIntFromInterval(1, Object.values(this.fishSpeeds).length)
        ];
      }
      if (this.fishDirection === DIRECTIONS.LEFT) {
        this.fishPosition -= fishMovement;
      } else {
        this.fishPosition += fishMovement;
      }
    };

    const updateProgress = () => {
      if (
        this.fishPosition >= this.playerPosition &&
        this.fishPosition + this.fishWidth <
          this.playerPosition + this.playerWidth
      ) {
        this.progress += p / 3;
      } else if (this.progress > 0) {
        this.progress -= p / 2.5;
        if (this.progress < 0) {
          this.progress = 0;
        }
      }
      if (this.progress >= 100) {
        this.fishOnLine = false;
        this.successfullCatch = true;
        this.catching = false;
        this.fish = FISH[randomIntFromInterval(0, FISH.length - 1)];
        this.progress = 0;
      }
    };

    this.time += p / 2000;
    if (!this.started && this.pressedKeys[KEY_MAP.Space]) {
      this.started = true;
      this.startWaitingForBite();
    }
    if (this.fishBiting && this.pressedKeys[KEY_MAP.Space]) {
      this.fishOnLine = true;
      this.fishBiting = false;
    }
    if (this.successfullCatch && this.pressedKeys[KEY_MAP.Space]) {
      this.fishOnLine = false;
      this.successfullCatch = false;
      this.fish = null;
      this.fishOnLine = false;
      this.fishBiting = false;
      this.playerPosition = 50;
      this.fishPosition = 50;
      this.startWaitingForBite();
    }
    if (this.fishOnLine) {
      if (this.waitingForBiteTimeoutID) {
        window.clearTimeout(this.waitingForBiteTimeoutID);
      }
      if (this.fishBitingTimeoutID) {
        window.clearTimeout(this.fishBitingTimeoutID);
      }
      updatePlayer();
      updateFish();
      updateProgress();
    }
  }
  startWaitingForBite() {
    this.catching = true;
    this.waitingForBiteTimeoutID = window.setTimeout(() => {
      this.fishBiting = true;
      this.fishBitingTimeoutID = window.setTimeout(() => {
        this.fishBiting = false;
        this.startWaitingForBite();
      }, BITING_TIME);
    }, randomIntFromInterval(MIN_CATCHING_TIME, MAX_CATCHING_TIME));
  }
  draw() {
    this.ctx.clearRect(0, 0, this.width, this.height);
    this.setSmallFont();
    this.drawBackground();
    this.ctx.fillStyle = BLACK_COLOR;
    this.ctx.textAlign = "center";
    if (this.started) {
      this.setMediumFont();
      if (this.catching) {
        if (this.fishBiting) {
          // Exclamation point
          this.ctx.fillStyle = "#D12D18";
          this.ctx.fillRect(
            this.centerWidth - this.pixelScale * 2,
            this.miniGameBounds.top - this.pixelScale * 14,
            this.pixelScale * 4,
            this.pixelScale * 4
          );
          this.ctx.fillRect(
            this.centerWidth - this.pixelScale * 2,
            this.miniGameBounds.top - this.pixelScale * 30,
            this.pixelScale * 4,
            this.pixelScale * 12
          );
          this.ctx.fillStyle = BLACK_COLOR;
          this.ctx.fillText(
            "A fish is biting, press space",
            this.centerWidth,
            this.miniGameBounds.top
          );
        } else if (this.fishOnLine) {
          this.drawMiniGame();
        } else {
          this.ctx.fillText(
            "Waiting for a fish to bite",
            this.centerWidth,
            this.miniGameBounds.top
          );
        }
      }
      if (this.successfullCatch) {
        this.ctx.fillText(
          `You caught a ${this.fish}`,
          this.centerWidth,
          this.miniGameBounds.top - 40
        );
        this.ctx.fillText(
          "Press space to fish again",
          this.centerWidth,
          this.miniGameBounds.top
        );
      }
    } else {
      this.setLargeFont();
      this.ctx.fillText("Fishing Mini-Game", this.centerWidth, 50);
      this.setSmallFont();
      this.ctx.fillText("(Guild Wars 2 Inspired)", this.centerWidth, 90);
      this.ctx.fillText("By Daniel Hearn", this.centerWidth, 120);
      this.setMediumFont();
      this.ctx.fillText(
        "Press space to begin",
        this.centerWidth,
        this.miniGameBounds.top
      );
    }
  }
  drawBackground() {
    // Add sea colors from closest color to noise value
    for (let y = 0; y < Math.ceil(this.height / this.pixelScale); y++) {
      for (let x = 0; x < Math.ceil(this.width / this.pixelScale); x++) {
        this.ctx.fillStyle =
          BACKGROUND_COLORS[
            ~~(
              this.noise.noise3D(
                x / this.noiseScale,
                y / this.noiseScale,
                this.time
              ) * 3
            ) + 2
          ];
        this.ctx.fillRect(
          x * this.pixelScale,
          y * this.pixelScale,
          this.pixelScale,
          this.pixelScale
        );
      }
    }
  }
  drawMiniGame() {
    const boundsPercentage = this.miniGameWidth / 100;

    const drawInstructions = () => {
      this.setSmallFont();
      this.ctx.textAlign = "left";
      this.ctx.fillStyle = "black";
      this.ctx.fillText("A/D or arrow keys to move the orange", 20, 50);
      this.ctx.fillText("catching rectangle to contain the fish.", 20, 80);
      this.ctx.fillText("This increases the catch progress bar.", 20, 110);
    };

    const drawFishBar = () => {
      this.ctx.fillStyle = "#0a2839";
      this.ctx.fillRect(
        -this.pixelScale,
        0,
        this.miniGameWidth + this.pixelScale * 2,
        this.pixelScale * 8
      );
      this.ctx.fillStyle = "#113A4F";
      this.ctx.fillRect(
        0,
        this.pixelScale,
        this.miniGameWidth,
        this.pixelScale * 6
      );
    };

    const drawFish = () => {
      const fishLeft = boundsPercentage * this.fishPosition;
      this.ctx.fillStyle = "#81d063";
      this.ctx.fillRect(
        fishLeft,
        this.pixelScale * 2,
        this.pixelScale * 1,
        this.pixelScale * 4
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 1,
        this.pixelScale * 1.5,
        this.pixelScale * 2,
        this.pixelScale * 5
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 3,
        this.pixelScale * 3.5,
        this.pixelScale * 8,
        this.pixelScale * 1
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 4,
        this.pixelScale * 1.5,
        this.pixelScale * 1,
        this.pixelScale * 5
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 6,
        this.pixelScale,
        this.pixelScale * 1,
        this.pixelScale * 6
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 8,
        this.pixelScale * 1.5,
        this.pixelScale * 1,
        this.pixelScale * 5
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 10.5,
        this.pixelScale * 2,
        this.pixelScale * 1,
        this.pixelScale * 1.5
      );
      this.ctx.fillRect(
        fishLeft + this.pixelScale * 10.5,
        this.pixelScale * 4.5,
        this.pixelScale * 1,
        this.pixelScale * 1.5
      );
    };

    const drawPlayer = () => {
      this.ctx.fillStyle = "#f1c66d";
      this.ctx.fillRect(
        boundsPercentage * this.playerPosition,
        -this.pixelScale,
        boundsPercentage * this.playerWidth,
        this.pixelScale * 10
      );
      this.ctx.fillStyle = "#5B320A";
      this.ctx.fillRect(
        boundsPercentage * this.playerPosition,
        0,
        boundsPercentage * this.playerWidth,
        this.pixelScale * 8
      );
    };

    const drawProgress = () => {
      this.ctx.fillStyle = BLACK_COLOR;
      this.ctx.fillText(
        "Catch Progress:",
        -this.pixelScale,
        this.pixelScale * 15
      );
      this.ctx.fillStyle = "#06171c";
      this.ctx.fillRect(
        -this.pixelScale,
        this.pixelScale * 17,
        this.miniGameWidth + this.pixelScale * 2,
        this.pixelScale * 6
      );
      this.ctx.fillStyle = "#13333c";
      this.ctx.fillRect(
        0,
        this.pixelScale * 18,
        this.miniGameWidth,
        this.pixelScale * 4
      );
      this.ctx.fillStyle = "#ffb15c";
      this.ctx.fillRect(
        0,
        this.pixelScale * 18,
        boundsPercentage * this.progress,
        this.pixelScale * 4
      );
      this.ctx.fillStyle = "#F8E2C2";
      this.ctx.fillRect(
        boundsPercentage * this.progress,
        this.pixelScale * 18,
        this.pixelScale,
        this.pixelScale * 4
      );
    };

    drawInstructions();
    this.ctx.save();
    this.ctx.translate(this.miniGameBounds.left, this.miniGameBounds.top);
    drawFishBar();
    drawPlayer();
    drawFish();
    drawProgress();
    this.ctx.restore();
  }
  setSmallFont() {
    this.ctx.font = "30px VT323";
  }
  setMediumFont() {
    this.ctx.font = "40px VT323";
  }
  setLargeFont() {
    this.ctx.font = "45px VT323";
  }
  loop(timestamp) {
    const progress = timestamp - this.lastRender;

    this.update(progress);
    this.draw();

    this.lastRender = timestamp;
    window.requestAnimationFrame((timestamp) => {
      this.loop(timestamp);
    });
  }
}

const font = new FontFace(
  "VT323",
  "url(https://fonts.cdnfonts.com/s/15755/VT323-Regular.woff)"
);

font.load().then((font) => {
  document.fonts.add(font);
  const game = new FishingGame();
});

              
            
!
999px

Console