2023/03/28

ウルティマオンラインとシャドウガード攻略とJavaScriptその1


今週はシャドウガード攻略の屋上調査隊だけでなく、裁縫師決定戦も開催。
イベント盛りだくさんでござる♪



上記動画はjavascriptをブラウザで実行したものを、Windows11の標準機能で録画(win+Gキー)したものになります。
コードはこんな感じ♪


<!DOCTYPE html>
<html>
<head>
  <title>ヽ(=´▽`=)ノ</title>
  <style>
    #box {
      width: 256px;
      height: 240px;
      background-image: url("uo_sg_20230313a.png");
      border: 2px solid black;
      position: relative;
    }
    img {
      position: absolute;
    }
  </style>
</head>
<body>
<center>
  <div id="box">
    <img id="img1" src="dot_001.png">
    <img id="img2" src="dot_002.png">
    <img id="img3" src="dot_003.png">
    <img id="img4" src="dot_004.png">
    <img id="img5" src="dot_005.png">
    <img id="img6" src="dot_006.png">
    <img id="img7" src="dot_007.png">
    <img id="img8" src="dot_008.png">
    <img id="img9" src="dot_009.png">
    <img id="img10" src="dot_010.png">
    <img id="img11" src="dot_011.png">
    <img id="img12" src="dot_012.png">
    <img id="img13" src="dot_013.png">
    <img id="img14" src="dot_014.png">
    <img id="img15" src="dot_cameo.png">
  </div>
</center>
  <script>
    // Get the box and the images
    let box = document.getElementById('box');
    let imgs = document.getElementsByTagName('img');

    // Set the initial positions and velocities of the images
    let positions = [];
    let velocities = [];
    for (let i = 0; i < imgs.length; i++) {
      positions[i] = {
        x: Math.random() * (box.offsetWidth - imgs[i].width),
        y: Math.random() * (box.offsetHeight - imgs[i].height)
      };
      velocities[i] = {
        x: Math.random() * 10 - 5,
        y: Math.random() * 10 - 5
      };
      imgs[i].style.left = positions[i].x + 'px';
      imgs[i].style.top = positions[i].y + 'px';
    }

    // Move the images
    setInterval(function() {
      for (let i = 0; i < imgs.length; i++) {
        // Get the current position and velocity of the image
        let pos = positions[i];
        let vel = velocities[i];

        // Update the position based on the velocity
        pos.x += vel.x;
        pos.y += vel.y;

        // Check if the image has hit a wall and reverse the velocity if it has
        if (pos.x < 0 || pos.x > box.offsetWidth - imgs[i].width) {
          vel.x = -vel.x;
        }
        if (pos.y < 0 || pos.y > box.offsetHeight - imgs[i].height) {
          vel.y = -vel.y;
        }

        // Update the position of the image
        imgs[i].style.left = pos.x + 'px';
        imgs[i].style.top = pos.y + 'px';

        // Update the positions and velocities arrays
        positions[i] = pos;
        velocities[i] = vel;
      }
    }, 20);
  </script>
</body>
</html>

(注)htmlで表示するため、インデント(行頭揃え)は全角空白を使っています。