Javascript RPG


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Epic RPG</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 20px;
    }
    #game-log {
      background: #f4f4f4;
      padding: 10px;
      margin-bottom: 20px;
      height: 200px;
      overflow-y: auto;
      border: 1px solid #ddd;
    }
    button {
      margin: 5px;
      padding: 10px;
    }
    #player-stats {
      margin-bottom: 20px;
    }
  </style>
</head>
<body>
  <h1>Epic RPG</h1>
  <div id="player-stats">
    <p><strong>Name:</strong> <span id="player-name">Hero</span></p>
    <p><strong>HP:</strong> <span id="player-hp">100</span>/<span id="player-max-hp">100</span></p>
    <p><strong>MP:</strong> <span id="player-mp">50</span>/<span id="player-max-mp">50</span></p>
    <p><strong>Level:</strong> <span id="player-level">1</span></p>
    <p><strong>EXP:</strong> <span id="player-exp">0</span>/100</p>
    <p><strong>Gold:</strong> <span id="player-gold">0</span></p>
    <p><strong>Inventory:</strong> <span id="player-inventory">Potion x1</span></p>
    <p><strong>Skills:</strong> <span id="player-skills">Fireball</span></p>
    <p><strong>Equipped Weapon:</strong> <span id="player-weapon">None</span></p>
    <p><strong>Equipped Armor:</strong> <span id="player-armor">None</span></p>
    <p><strong>Current Quest:</strong> <span id="player-quest">None</span></p>
    <p><strong>Stage:</strong> <span id="current-stage">1</span></p>
  </div>
  <div id="game-log"></div>
  <button onclick="attack()">Attack</button>
  <button onclick="useSkill()">Use Skill</button>
  <button onclick="heal()">Heal</button>
  <button onclick="openShop()">Shop</button>
  <button onclick="acceptQuest()">Quest</button>
  <button onclick="craftItem()">Craft Item</button>
  <button onclick="nextStage()">Next Stage</button>
  <button onclick="restart()">Restart</button>
  <script>
    // プレイヤーと敵のデータ
    let player = {
      name: "Hero",
      hp: 100,
      maxHp: 100,
      mp: 50,
      maxMp: 50,
      attackPower: 10,
      defense: 5,
      exp: 0,
      level: 1,
      gold: 50,
      inventory: ["Potion", "Iron Ore"],
      skills: ["Fireball"],
      weapon: null,
      armor: null,
      quest: null,
      stage: 1,
    };

    let enemy = {
      name: "Goblin",
      hp: 50,
      maxHp: 50,
      attackPower: 8,
      defense: 3,
    };

    const quests = [
      { name: "Defeat 3 Goblins", progress: 0, goal: 3, reward: 100 },
      { name: "Collect 2 Potions", progress: 0, goal: 2, reward: 50 },
    ];

    const stages = [
      { stage: 1, description: "The Forest of Beginnings", enemies: ["Goblin", "Orc"] },
      { stage: 2, description: "The Cursed Mines", enemies: ["Dark Bat", "Skeleton"] },
      { stage: 3, description: "The Dragon's Lair", enemies: ["Fire Dragon"] },
    ];

    // ゲームログ表示関数
    function log(message) {
      const logDiv = document.getElementById("game-log");
      logDiv.innerHTML += `<p>${message}</p>`;
      logDiv.scrollTop = logDiv.scrollHeight;
    }

    // プレイヤーの攻撃
    function attack() {
      const damage = Math.max(Math.floor(Math.random() * player.attackPower) - enemy.defense, 1);
      enemy.hp -= damage;
      log(`You attack the ${enemy.name} for ${damage} damage!`);
      if (enemy.hp <= 0) {
        log(`You defeated the ${enemy.name}!`);
        gainExp(20);
        gainGold(Math.floor(Math.random() * 20) + 10);
        updateQuestProgress("Defeat 3 Goblins");
        spawnNewEnemy();
        return;
      }
      enemyAttack();
    }

    // 敵の攻撃
    function enemyAttack() {
      const damage = Math.max(Math.floor(Math.random() * enemy.attackPower) - player.defense, 0);
      player.hp -= damage;
      log(`The ${enemy.name} attacks you for ${damage} damage! Current HP: ${player.hp}`);
      if (player.hp <= 0) {
        log("You have been defeated...");
        log("Press 'Restart' to try again.");
      }
      updateStats();
    }

    // ステージ移動
    function nextStage() {
      player.stage++;
      const currentStage = stages.find(stage => stage.stage === player.stage);
      if (!currentStage) {
        log("Congratulations! You have completed the game!");
        return;
      }
      log(`You enter the ${currentStage.description}.`);
      spawnNewEnemy();
      updateStats();
    }

    // 新しい敵を生成
    function spawnNewEnemy() {
      const currentStage = stages.find(stage => stage.stage === player.stage);
      const randomEnemyName = currentStage.enemies[Math.floor(Math.random() * currentStage.enemies.length)];
      enemy = {
        name: randomEnemyName,
        hp: Math.floor(Math.random() * 30 + 50),
        maxHp: Math.floor(Math.random() * 30 + 50),
        attackPower: Math.floor(Math.random() * 5 + 10),
        defense: Math.floor(Math.random() * 5),
      };
      log(`A wild ${enemy.name} appears with ${enemy.hp} HP!`);
    }

    // アイテムクラフト
    function craftItem() {
      if (player.inventory.includes("Iron Ore")) {
        player.inventory.splice(player.inventory.indexOf("Iron Ore"), 1);
        player.weapon = "Iron Sword";
        player.attackPower += 5;
        log("You crafted an Iron Sword! Attack power increased by 5.");
      } else {
        log("You don't have the required materials to craft an item.");
      }
      updateStats();
    }

    // ステータス更新
    function updateStats() {
      document.getElementById("player-name").innerText = player.name;
      document.getElementById("player-hp").innerText = player.hp;
      document.getElementById("player-max-hp").innerText = player.maxHp;
      document.getElementById("player-mp").innerText = player.mp;
      document.getElementById("player-max-mp").innerText = player.maxMp;
      document.getElementById("player-level").innerText = player.level;
      document.getElementById("player-exp").innerText = player.exp;
      document.getElementById("player-gold").innerText = player.gold;
      document.getElementById("player-inventory").innerText = player.inventory.join(", ") || "Empty";
      document.getElementById("player-skills").innerText = player.skills.join(", ") || "None";
      document.getElementById("player-weapon").innerText = player.weapon || "None";
      document.getElementById("player-armor").innerText = player.armor || "None";
      document.getElementById("player-quest").innerText = player.quest ? player.quest.name : "None";
      document.getElementById("current-stage").innerText = player.stage;
    }

    // 初期化
    log("Welcome to the RPG! A Goblin appears!");
    updateStats();
    spawnNewEnemy();
  </script>
</body>
</html>

高度なコード比較サイト

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>高度なコード比較サイト</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      margin: 0;
      padding: 0;
    }

    .container {
      width: 90%;
      max-width: 900px;
      margin: 20px auto;
      background: #fff;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      padding: 20px;
      border-radius: 5px;
    }

    h1 {
      text-align: center;
      margin-bottom: 20px;
      color: #333;
    }

    .code-input {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;
      gap: 10px;
    }

    textarea {
      width: 48%;
      height: 300px;
      font-family: monospace;
      font-size: 14px;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      resize: none;
      background-color: #f9f9f9;
    }

    .buttons {
      display: flex;
      justify-content: center;
      gap: 10px;
    }

    button {
      padding: 10px 20px;
      background: #007BFF;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
    }

    button:hover {
      background: #0056b3;
    }

    #result {
      white-space: pre-wrap;
      font-family: monospace;
      background-color: #f8f9fa;
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 5px;
      max-height: 300px;
      overflow-y: auto;
    }

    .highlight {
      background-color: #ffcccc;
      font-weight: bold;
      color: #d9534f;
    }

    .line {
      border-left: 4px solid #ccc;
      padding-left: 10px;
      margin: 5px 0;
    }
  </style>
</head>
<body>
  <div class="container">
    <h1>高度なコード比較ツール</h1>
    <div class="code-input">
      <textarea id="code1" placeholder="コード1を入力..."></textarea>
      <textarea id="code2" placeholder="コード2を入力..."></textarea>
    </div>
    <div class="buttons">
      <button onclick="compareCodes()">比較する</button>
      <button onclick="clearFields()">クリア</button>
    </div>
    <h3>比較結果</h3>
    <div id="result">
      <!-- 結果表示エリア -->
    </div>
  </div>
  <script>
    function compareCodes() {
      const code1 = document.getElementById('code1').value.split('\n');
      const code2 = document.getElementById('code2').value.split('\n');
      const resultContainer = document.getElementById('result');
      resultContainer.innerHTML = '';

      const maxLength = Math.max(code1.length, code2.length);

      for (let i = 0; i < maxLength; i++) {
        const line1 = code1[i] || '';
        const line2 = code2[i] || '';
        const lineClass = line1 !== line2 ? 'highlight' : '';

        resultContainer.innerHTML += `
          <div class="line">
            <strong>行 ${i + 1}:</strong>
            <span class="${lineClass}">コード1: "${line1}"</span> |
            <span class="${lineClass}">コード2: "${line2}"</span>
          </div>`;
      }

      if (!resultContainer.innerHTML.trim()) {
        resultContainer.innerHTML = '<div>コードに違いはありません。</div>';
      }
    }

    function clearFields() {
      document.getElementById('code1').value = '';
      document.getElementById('code2').value = '';
      document.getElementById('result').innerHTML = '';
    }
  </script>
</body>
</html>

node-js todo-list

Node.js での Todo リストの基本的なファイル構造と実装例を示します。

ファイル構造

javaコードをコピーする/todo-app
  ├── /node_modules    // npmパッケージ
  ├── /public          // 静的ファイル(CSS, JSなど)
  │   └── style.css
  ├── /views           // テンプレートファイル(HTML, EJSなど)
  │   └── index.ejs
  ├── /routes          // ルーティングファイル
  │   └── todos.js
  ├── app.js           // メインのアプリケーションファイル
  ├── package.json     // npmパッケージ設定ファイル
  └── README.md        // 説明書

1. package.json

jsonコードをコピーする{
  "name": "todo-app",
  "version": "1.0.0",
  "description": "Simple Todo app with Node.js",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "express": "^4.18.0",
    "ejs": "^3.1.6",
    "body-parser": "^1.19.0"
  }
}

2. app.js

jsコードをコピーするconst express = require('express');
const bodyParser = require('body-parser');
const app = express();
const todoRoutes = require('./routes/todos');

app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

app.use('/', todoRoutes);

app.listen(3000, () => {
  console.log('Todo app running on port 3000');
});

3. routes/todos.js

jsコードをコピーするconst express = require('express');
const router = express.Router();

let todos = [];

router.get('/', (req, res) => {
  res.render('index', { todos });
});

router.post('/add', (req, res) => {
  const newTodo = req.body.todo;
  if (newTodo) {
    todos.push(newTodo);
  }
  res.redirect('/');
});

router.post('/delete/:index', (req, res) => {
  const index = req.params.index;
  if (index >= 0 && index < todos.length) {
    todos.splice(index, 1);
  }
  res.redirect('/');
});

module.exports = router;

4. views/index.ejs

htmlコードをコピーする<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Todo App</title>
  <link rel="stylesheet" href="/style.css">
</head>
<body>
  <h1>Todo List</h1>
  <form action="/add" method="POST">
    <input type="text" name="todo" placeholder="Add a new task" required>
    <button type="submit">Add</button>
  </form>
  <ul>
    <% todos.forEach((todo, index) => { %>
      <li>
        <%= todo %> 
        <form action="/delete/<%= index %>" method="POST" style="display:inline;">
          <button type="submit">Delete</button>
        </form>
      </li>
    <% }) %>
  </ul>
</body>
</html>

5. public/style.css

cssコードをコピーするbody {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  text-align: center;
}

h1 {
  margin-top: 20px;
}

form {
  margin-bottom: 20px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 5px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

button {
  margin-left: 10px;
}

このコードは、Node.js を使用してシンプルな Todo リストを作成する基本構造を示しています。 express フレームワークを使ってルーティングを行い、 ejs を使ってテンプレートを表示しています。

4o

あなた:

コマンド

ChatGPT:

ChatGPT

以下は、Node.js での Todo リストアプリを実行するためのコマンドの手順です。

1. プロジェクトの初期化

最初に新しいプロジェクトフォルダを作成し、その中でプロジェクトを初期化します。

bashコードをコピーするmkdir todo-app
cd todo-app
npm init -y

npm init -ypackage.json ファイルが自動生成されます。

2. 必要なパッケージのインストール

express, ejs, body-parser などの必要なパッケージをインストールします。

bashコードをコピーするnpm install express ejs body-parser

3. アプリケーションの起動

app.js を実行して、アプリケーションを起動します。

bashコードをコピーするnode app.js

このコマンドを実行後、ブラウザで http://localhost:3000 にアクセスして Todo リストアプリを確認できます。

4. 開発中に自動的に再起動させたい場合 (オプション)

開発中に変更を加えるたびにサーバーを自動的に再起動させたい場合は、nodemon を使用すると便利です。

bashコードをコピーするnpm install -g nodemon
nodemon app.js

nodemon を使うと、コードを変更するたびにサーバーが自動でリスタートします。

確認事項

  1. コマンドはプロジェクトディレクトリ内で実行してください。
  2. ブラウザから http://localhost:3000 へアクセスして動作確認ができます。

Javascript 四角を描画

'use strict';

{
  function draw() {
    const canvas = document.querySelector('canvas');
    if (typeof canvas.getContext === 'undefined') {
      return;
    }
    const ctx = canvas.getContext('2d');

    // ctx.fillRect(50, 50, 50, 50);
    ctx.strokeRect(50, 50, 50, 50);
  }

  draw();
}
body {
  background: #222;
}

canvas {
  background: #fff;
}
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>My Canvas</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <canvas width="600" height="240">
    Canvas not supported.
  </canvas>

  <script src="js/main.js"></script>
</body>
</html>

Javascript 日時を更新してみよう

main.js

'use strict';

{
    // 2000 4 11
    // const d = new Date(2000, 3, 11);
    // 2000 2 ??
    const d = new Date(2000, 3, 0);
    d.setDate(d.getDate() + 100);


    console.log(d.toLocaleString());
}

index.html

<!DOCTYPE html>
<html lang="ja">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My JavaScript</title>
</head>

<body>
    <script src="main.js"></script>
</body>

</html>

myblog.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>私のブログ</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }
    .navbar {
      background-color: #333;
      color: #fff;
      padding: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .navbar a {
      color: #fff;
      text-decoration: none;
      padding: 0 15px;
    }
    .navbar a:hover {
      text-decoration: underline;
    }
    .navbar .menu-toggle {
      display: none;
    }
    .navbar .menu {
      display: flex;
    }
    .navbar .menu .dropdown {
      position: relative;
      display: inline-block;
    }
    .navbar .menu .dropdown-content {
      display: none;
      position: absolute;
      background-color: #444;
      min-width: 160px;
      box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
      z-index: 1;
    }
    .navbar .menu .dropdown-content a {
      color: #fff;
      padding: 12px 16px;
      text-decoration: none;
      display: block;
    }
    .navbar .menu .dropdown-content a:hover {
      background-color: #555;
    }
    .navbar .menu .dropdown:hover .dropdown-content {
      display: block;
    }
    .custom-banner {
      background-color: #f0f0f0;
      text-align: center;
      padding: 60px 20px;
    }
    .custom-banner h1 {
      color: #333;
      margin: 0;
      font-size: 2.5em;
    }
    .content {
      padding: 20px;
    }
    .post {
      border-bottom: 1px solid #ddd;
      padding: 20px 0;
      transition: background-color 0.3s;
    }
    .post:hover {
      background-color: #f9f9f9;
    }
    .post h2 {
      margin: 0;
      color: #333;
    }
    .post p {
      margin: 10px 0 0;
      color: #666;
    }
    .footer {
      background-color: #333;
      color: #fff;
      text-align: center;
      padding: 10px;
      position: fixed;
      width: 100%;
      bottom: 0;
    }
    .contact-form {
      max-width: 600px;
      margin: 20px auto;
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 5px;
      background-color: #fff;
    }
    .contact-form label {
      display: block;
      margin-bottom: 5px;
      color: #333;
    }
    .contact-form input, .contact-form textarea {
      width: 100%;
      padding: 10px;
      margin-bottom: 10px;
      border: 1px solid #ddd;
      border-radius: 3px;
    }
    .contact-form button {
      background-color: #333;
      color: #fff;
      padding: 10px 20px;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }
    .contact-form button:hover {
      background-color: #555;
    }
    @media (max-width: 600px) {
      .navbar .menu-toggle {
        display: block;
        cursor: pointer;
      }
      .navbar .menu {
        display: none;
        flex-direction: column;
        width: 100%;
      }
      .navbar .menu a {
        padding: 10px;
        border-top: 1px solid #444;
      }
      .navbar .menu.open {
        display: flex;
      }
    }
  </style>
</head>
<body>
  <div class="navbar">
    <div>私のブログ</div>
    <div class="menu-toggle">メニュー</div>
    <div class="menu">
      <a href="#home">ホーム</a>
      <a href="#about">紹介</a>
      <a href="#posts">記事</a>
      <a href="#contact">お問い合わせ</a>
      <div class="dropdown">
        <a href="#more">もっと</a>
        <div class="dropdown-content">
          <a href="#link1">リンク 1</a>
          <a href="#link2">リンク 2</a>
          <a href="#link3">リンク 3</a>
        </div>
      </div>
    </div>
  </div>

  <div class="custom-banner">
    <h1>私のブログへようこそ</h1>
  </div>

  <div class="content" id="home">
    <h2>ホーム</h2>
    <p>ここはホームセクションです。</p>
  </div>

  <div class="content" id="about">
    <h2>紹介</h2>
    <p>ここは紹介セクションです。</p>
  </div>

  <div class="content" id="posts">
    <h2>記事</h2>
    <div class="post">
      <h2>記事タイトル 1</h2>
      <p>この記事の概要や内容がここに表示されます。</p>
    </div>
    <div class="post">
      <h2>記事タイトル 2</h2>
      <p>この記事の概要や内容がここに表示されます。</p>
    </div>
    <!-- 追加の記事をここに追加 -->
  </div>

  <div class="content" id="contact">
    <h2>お問い合わせ</h2>
    <form class="contact-form">
      <label for="name">名前:</label>
      <input type="text" id="name" name="name" required>

      <label for="email">メールアドレス:</label>
      <input type="email" id="email" name="email" required>

      <label for="message">メッセージ:</label>
      <textarea id="message" name="message" rows="5" required></textarea>

      <button type="submit">送信</button>
    </form>
  </div>

  <div class="footer">
    &copy; 2024 私のブログ. All rights reserved.
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', function() {
      const menuToggle = document.querySelector('.menu-toggle');
      const menu = document.querySelector('.menu');
      const contactForm = document.querySelector('.contact-form');

      menuToggle.addEventListener('click', function() {
        menu.classList.toggle('open');
      });

      contactForm.addEventListener('submit', function(event) {
        event.preventDefault();
        alert('フォームが送信されました!');
        // ここでフォームのデータを送信する処理を追加できます
      });

      alert('ブログへようこそ!');
    });
  </script>
</body>
</html>

Q&Aサイト

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Q&A Site</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4;
        }

        h1, h2, h3 {
            color: #333;
        }

        #question-list, #add-question, #question-detail {
            margin-bottom: 20px;
        }

        #questions {
            list-style-type: none;
            padding: 0;
        }

        .question, .answer {
            background-color: #fff;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }

        .answer {
            margin-left: 20px;
        }

        form {
            display: flex;
            flex-direction: column;
        }

        form input, form textarea {
            margin-bottom: 10px;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
        }

        form button {
            padding: 10px;
            border: none;
            border-radius: 5px;
            background-color: #333;
            color: #fff;
            cursor: pointer;
        }

        form button:hover {
            background-color: #555;
        }

        .hidden {
            display: none;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
        }
    </style>
</head>
<body>
    <h1>Q&A Site</h1>
    <div id="question-list">
        <h2>Questions</h2>
        <ul id="questions"></ul>
    </div>
    <div id="add-question">
        <h2>Add a Question</h2>
        <form id="question-form">
            <input type="text" id="question-title" placeholder="Title" required>
            <textarea id="question-body" placeholder="Question" required></textarea>
            <button type="submit">Add Question</button>
        </form>
    </div>
    <div id="question-detail" class="hidden">
        <h2 id="detail-title"></h2>
        <p id="detail-body"></p>
        <div class="action-buttons">
            <button id="edit-question-button">Edit</button>
            <button id="delete-question-button">Delete</button>
        </div>
        <div id="edit-question" class="hidden">
            <h3>Edit Question</h3>
            <form id="edit-question-form">
                <input type="text" id="edit-question-title" required>
                <textarea id="edit-question-body" required></textarea>
                <button type="submit">Save Changes</button>
            </form>
        </div>
        <h3>Answers</h3>
        <ul id="answers"></ul>
        <h3>Add an Answer</h3>
        <form id="answer-form">
            <input type="text" id="answer-name" placeholder="Your name" required>
            <textarea id="answer-body" placeholder="Your answer" required></textarea>
            <button type="submit">Add Answer</button>
        </form>
        <button id="back-button">Back to Questions</button>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            let questions = [];
            let currentQuestionIndex = null;

            const questionForm = document.getElementById('question-form');
            const questionTitle = document.getElementById('question-title');
            const questionBody = document.getElementById('question-body');
            const questionsList = document.getElementById('questions');

            const questionDetail = document.getElementById('question-detail');
            const detailTitle = document.getElementById('detail-title');
            const detailBody = document.getElementById('detail-body');
            const answersList = document.getElementById('answers');
            const answerForm = document.getElementById('answer-form');
            const answerName = document.getElementById('answer-name');
            const answerBody = document.getElementById('answer-body');
            const backButton = document.getElementById('back-button');

            const editQuestionButton = document.getElementById('edit-question-button');
            const deleteQuestionButton = document.getElementById('delete-question-button');
            const editQuestionForm = document.getElementById('edit-question-form');
            const editQuestionTitle = document.getElementById('edit-question-title');
            const editQuestionBody = document.getElementById('edit-question-body');

            questionForm.addEventListener('submit', (e) => {
                e.preventDefault();

                const newQuestion = {
                    title: questionTitle.value,
                    body: questionBody.value,
                    answers: []
                };

                questions.push(newQuestion);
                displayQuestions();

                questionTitle.value = '';
                questionBody.value = '';
            });

            answerForm.addEventListener('submit', (e) => {
                e.preventDefault();

                const newAnswer = {
                    name: answerName.value,
                    body: answerBody.value
                };

                questions[currentQuestionIndex].answers.push(newAnswer);
                displayQuestionDetail(currentQuestionIndex);

                answerName.value = '';
                answerBody.value = '';
            });

            editQuestionButton.addEventListener('click', () => {
                editQuestionForm.classList.remove('hidden');
                editQuestionTitle.value = questions[currentQuestionIndex].title;
                editQuestionBody.value = questions[currentQuestionIndex].body;
            });

            editQuestionForm.addEventListener('submit', (e) => {
                e.preventDefault();
                questions[currentQuestionIndex].title = editQuestionTitle.value;
                questions[currentQuestionIndex].body = editQuestionBody.value;
                displayQuestionDetail(currentQuestionIndex);
                displayQuestions();
                editQuestionForm.classList.add('hidden');
            });

            deleteQuestionButton.addEventListener('click', () => {
                questions.splice(currentQuestionIndex, 1);
                questionDetail.classList.add('hidden');
                document.getElementById('question-list').classList.remove('hidden');
                document.getElementById('add-question').classList.remove('hidden');
                displayQuestions();
            });

            backButton.addEventListener('click', () => {
                questionDetail.classList.add('hidden');
                document.getElementById('question-list').classList.remove('hidden');
                document.getElementById('add-question').classList.remove('hidden');
            });

            function displayQuestions() {
                questionsList.innerHTML = '';

                questions.forEach((question, index) => {
                    const li = document.createElement('li');
                    li.className = 'question';
                    li.innerHTML = `
                        <h3>${question.title}</h3>
                        <p>${question.body}</p>
                        <button onclick="viewQuestion(${index})">View Details</button>
                    `;
                    questionsList.appendChild(li);
                });
            }

            window.viewQuestion = (index) => {
                currentQuestionIndex = index;
                displayQuestionDetail(index);
                document.getElementById('question-list').classList.add('hidden');
                document.getElementById('add-question').classList.add('hidden');
                questionDetail.classList.remove('hidden');
            };

            function displayQuestionDetail(index) {
                const question = questions[index];
                detailTitle.textContent = question.title;
                detailBody.textContent = question.body;
                displayAnswers(index);
            }

            function displayAnswers(index) {
                const question = questions[index];
                answersList.innerHTML = '';

                question.answers.forEach((answer, answerIndex) => {
                    const li = document.createElement('li');
                    li.className = 'answer';
                    li.innerHTML = `
                        <p><strong>${answer.name}:</strong> ${answer.body}</p>
                        <button onclick="editAnswer(${index}, ${answerIndex})">Edit</button>
                        <button onclick="deleteAnswer(${index}, ${answerIndex})">Delete</button>
                    `;
                    answersList.appendChild(li);
                });
            }

            window.editAnswer = (questionIndex, answerIndex) => {
                const answer = questions[questionIndex].answers[answerIndex];
                const newBody = prompt("Edit your answer:", answer.body);
                if (newBody) {
                    answer.body = newBody;
                    displayAnswers(questionIndex);
                }
            };

            window.deleteAnswer = (questionIndex, answerIndex) => {
                questions[questionIndex].answers.splice(answerIndex, 1);
                displayAnswers(questionIndex);
            };

            displayQuestions();
        });
    </script>
</body>
</html>

ニコニコ動画風サイト

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ニコニコ動画風サイト</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        header {
            background-color: #333;
            color: #fff;
            padding: 10px 20px;
            text-align: center;
        }
        nav {
            background-color: #555;
            color: #fff;
            display: flex;
            justify-content: space-around;
            padding: 10px 0;
        }
        nav a {
            color: #fff;
            text-decoration: none;
            padding: 10px 20px;
        }
        main {
            display: flex;
            margin: 20px;
        }
        aside {
            width: 25%;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        section {
            width: 75%;
            padding: 20px;
        }
        .video-player {
            background-color: #000;
            height: 400px;
            margin-bottom: 20px;
            position: relative;
        }
        .video-player video {
            width: 100%;
            height: 100%;
        }
        footer {
            background-color: #333;
            color: #fff;
            text-align: center;
            padding: 10px 0;
        }
        .comments {
            list-style: none;
            padding: 0;
        }
        .comments li {
            background-color: #fff;
            margin-bottom: 10px;
            padding: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .comment-form {
            display: flex;
            margin-top: 20px;
        }
        .comment-form input {
            flex: 1;
            padding: 10px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .comment-form button {
            padding: 10px 20px;
            border: none;
            background-color: #333;
            color: #fff;
            border-radius: 5px;
            cursor: pointer;
        }
        .thumbnail {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .thumbnail img {
            width: 120px;
            height: 90px;
            margin-right: 10px;
        }
        .login-form, .register-form, .upload-form, .profile {
            background-color: #fff;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .login-form h2, .register-form h2, .upload-form h2, .profile h2 {
            margin-top: 0;
        }
        .login-form input, .register-form input, .upload-form input {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .login-form button, .register-form button, .upload-form button {
            width: 100%;
            padding: 10px;
            border: none;
            background-color: #333;
            color: #fff;
            border-radius: 5px;
            cursor: pointer;
        }
        .search-form {
            display: flex;
            justify-content: center;
            margin: 20px 0;
        }
        .search-form input {
            width: 70%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .search-form button {
            padding: 10px 20px;
            border: none;
            background-color: #333;
            color: #fff;
            border-radius: 5px;
            cursor: pointer;
        }
        .rating {
            display: flex;
            align-items: center;
            margin-top: 10px;
        }
        .rating button {
            border: none;
            background: none;
            cursor: pointer;
            font-size: 1.2em;
            margin-right: 10px;
        }
        .rating span {
            margin-right: 20px;
        }
    </style>
</head>
<body>
    <header>
        <h1>ニコニコ動画風サイト</h1>
    </header>
    <nav>
        <a href="index.html">ホーム</a>
        <a href="ranking.html">ランキング</a>
        <a href="categories.html">カテゴリー</a>
        <a href="mypage.html">マイページ</a>
    </nav>
    <div class="search-form">
        <input type="text" id="searchInput" placeholder="検索...">
        <button onclick="search()">検索</button>
    </div>
    <main>
        <aside>
            <h2>おすすめ動画</h2>
            <div class="thumbnail">
                <a href="video.html"><img src="thumbnail1.jpg" alt="動画1"></a>
                <a href="video.html">動画1のタイトル</a>
            </div>
            <div class="thumbnail">
                <a href="video.html"><img src="thumbnail2.jpg" alt="動画2"></a>
                <a href="video.html">動画2のタイトル</a>
            </div>
            <div class="thumbnail">
                <a href="video.html"><img src="thumbnail3.jpg" alt="動画3"></a>
                <a href="video.html">動画3のタイトル</a>
            </div>
            <div class="thumbnail">
                <a href="video.html"><img src="thumbnail4.jpg" alt="動画4"></a>
                <a href="video.html">動画4のタイトル</a>
            </div>
        </aside>
        <section>
            <div class="video-player">
                <video controls>
                    <source src="sample.mp4" type="video/mp4">
                    あなたのブラウザは動画タグに対応していません。
                </video>
            </div>
            <h2>動画タイトル</h2>
            <p>動画の説明文がここに入ります。</p>
            <div class="rating">
                <button onclick="like()">👍</button><span id="likeCount">0</span>
                <button onclick="dislike()">👎</button><span id="dislikeCount">0</span>
            </div>
            <h3>コメント</h3>
            <ul class="comments" id="comments">
                <li><span class="timestamp">12:34</span> コメント1</li>
                <li><span class="timestamp">12:35</span> コメント2</li>
                <li><span class="timestamp">12:36</span> コメント3</li>
                <li><span class="timestamp">12:37</span> コメント4</li>
            </ul>
            <div class="comment-form">
                <input type="text" id="commentInput" placeholder="コメントを入力してください">
                <button onclick="addComment()">コメントを投稿</button>
            </div>
        </section>
    </main>
    <footer>
    </footer>

    <!-- Register Form -->
    <div class="register-form">
        <h2>ユーザー登録</h2>
        <input type="text" id="registerUsername" placeholder="ユーザー名">
        <input type="password" id="registerPassword" placeholder="パスワード">
        <button onclick="register()">登録</button>
    </div>

    <!-- Login Form -->
    <div class="login-form">
        <h2>ログイン</h2>
        <input type="text" id="loginUsername" placeholder="ユーザー名">
        <input type="password" id="loginPassword" placeholder="パスワード">
        <button onclick="login()">ログイン</button>
    </div>

    <!-- Upload Form -->
    <div class="upload-form">
        <h2>動画アップロード</h2>
        <input type="file" id="uploadVideo">
        <input type="text" id="uploadTitle" placeholder="タイトル">
        <button onclick="upload()">アップロード</button>
    </div>

    <!-- Profile Page -->
    <div class="profile">
        <h2>プロフィール</h2>
        <p>ユーザー名: <span id="profileUsername"></span></p>
        <p>登録日: <span id="profileDate"></span></p>
    </div>

    <script>
        let likeCount = 0;
        let dislikeCount = 0;

        function addComment() {
            var commentInput = document.getElementById('commentInput');
            var commentText = commentInput.value.trim();
            if (commentText !== "") {
                var commentsList = document.getElementById('comments');
                var newComment = document.createElement('li');
                var timestamp = new Date().toLocaleTimeString();
                newComment.innerHTML = '<span class="timestamp">' + timestamp + '</span> ' + commentText;
                commentsList.appendChild(newComment);
                commentInput.value = "";
            }
        }

        function like() {
            likeCount++;
            document.getElementById('likeCount').innerText = likeCount;
        }

        function dislike() {
            dislikeCount++;
            document.getElementById('dislikeCount').innerText = dislikeCount;
        }

        function search() {
            var searchInput = document.getElementById('searchInput').value.trim();
            if (searchInput !== "") {
                alert('検索結果: ' + searchInput);
            }
        }

        function register() {
            var username = document.getElementById('registerUsername').value.trim();
            var password = document.getElementById('registerPassword').value.trim();
            if (username !== "" && password !== "") {
                alert('ユーザー登録が完了しました: ' + username);
                localStorage.setItem('username', username);
                localStorage.setItem('password', password);
                document.getElementById('registerUsername').value = "";
                document.getElementById('registerPassword').value = "";
            }
        }

        function login() {
            var username = document.getElementById('loginUsername').value.trim();
            var password = document.getElementById('loginPassword').value.trim();
            var storedUsername = localStorage.getItem('username');
            var storedPassword = localStorage.getItem('password');
            if (username === storedUsername && password === storedPassword) {
                alert('ログイン成功');
                document.getElementById('profileUsername').innerText = username;
                document.getElementById('profileDate').innerText = new Date().toLocaleDateString();
                document.getElementById('loginUsername').value = "";
                document.getElementById('loginPassword').value = "";
            } else {
                alert('ユーザー名またはパスワードが間違っています');
            }
        }

        function upload() {
            var video = document.getElementById('uploadVideo').files[0];
            var title = document.getElementById('uploadTitle').value.trim();
            if (video && title !== "") {
                alert('動画アップロードが完了しました: ' + title);
                document.getElementById('uploadVideo').value = "";
                document.getElementById('uploadTitle').value = "";
            }
        }
    </script>
</body>
</html>

Social Networking Service

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Social Networking Service</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
  body {
    padding: 20px;
  }
  .card {
    margin-bottom: 20px;
  }
</style>
</head>
<body>

<div class="container">
  <h1 class="text-center mb-4">Social Networking Service</h1>

  <!-- ログインフォーム -->
  <div id="loginForm" class="card w-50 mx-auto">
    <div class="card-body">
      <h2 class="card-title text-center mb-4">Login</h2>
      <div class="form-group">
        <input type="text" id="loginUsername" class="form-control" placeholder="Username">
      </div>
      <div class="form-group">
        <input type="password" id="loginPassword" class="form-control" placeholder="Password">
      </div>
      <button onclick="login()" class="btn btn-primary btn-block">Login</button>
      <button onclick="registerForm()" class="btn btn-secondary btn-block">Register</button>
    </div>
  </div>

  <!-- 登録フォーム -->
  <div id="registerForm" class="card w-50 mx-auto" style="display: none;">
    <div class="card-body">
      <h2 class="card-title text-center mb-4">Register</h2>
      <div class="form-group">
        <input type="text" id="registerName" class="form-control" placeholder="Full Name">
      </div>
      <div class="form-group">
        <input type="text" id="registerUsername" class="form-control" placeholder="Username">
      </div>
      <div class="form-group">
        <input type="password" id="registerPassword" class="form-control" placeholder="Password">
      </div>
      <button onclick="register()" class="btn btn-primary btn-block">Register</button>
      <button onclick="loginForm()" class="btn btn-secondary btn-block">Back to Login</button>
    </div>
  </div>

  <!-- プロフィール -->
  <div id="profile" class="card w-50 mx-auto" style="display: none;">
    <div class="card-body">
      <h2 class="card-title text-center mb-4">Profile</h2>
      <p><strong>Name:</strong> <span id="profileName"></span></p>
      <p><strong>Username:</strong> <span id="profileUsername"></span></p>
      <button onclick="logout()" class="btn btn-danger btn-block">Logout</button>
    </div>
  </div>

  <!-- 投稿フォーム -->
  <div id="postForm" class="card w-75 mx-auto" style="display: none;">
    <div class="card-body">
      <h2 class="card-title text-center mb-4">Create Post</h2>
      <div class="form-group">
        <textarea id="postContent" class="form-control" rows="3" placeholder="What's on your mind?"></textarea>
      </div>
      <button onclick="createPost()" class="btn btn-primary btn-block">Post</button>
    </div>
  </div>

  <!-- 投稿一覧 -->
  <div id="postList" class="w-75 mx-auto mt-4"></div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
  let currentUser = null; // 現在のログインユーザー
  let users = []; // ユーザーの配列
  let posts = []; // 投稿の配列

  function login() {
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    const user = users.find(u => u.username === username && u.password === password);
    if (user) {
      currentUser = user;
      showProfile();
    } else {
      alert('Invalid username or password.');
    }
  }

  function logout() {
    currentUser = null;
    hideAll();
    document.getElementById('loginForm').style.display = 'block';
  }

  function registerForm() {
    hideAll();
    document.getElementById('registerForm').style.display = 'block';
  }

  function register() {
    const name = document.getElementById('registerName').value;
    const username = document.getElementById('registerUsername').value;
    const password = document.getElementById('registerPassword').value;
    users.push({ name, username, password });
    alert('Registration successful! Please login.');
    loginForm();
  }

  function loginForm() {
    hideAll();
    document.getElementById('loginForm').style.display = 'block';
  }

  function showProfile() {
    hideAll();
    document.getElementById('profile').style.display = 'block';
    document.getElementById('profileName').textContent = currentUser.name;
    document.getElementById('profileUsername').textContent = currentUser.username;
    document.getElementById('postForm').style.display = 'block';
    displayPosts();
  }

  function createPost() {
    const postContent = document.getElementById('postContent').value;
    if (postContent.trim() !== '') {
      const post = {
        id: Date.now(),
        content: postContent,
        author: currentUser.name,
        authorUsername: currentUser.username,
        likes: 0,
        comments: []
      };
      posts.unshift(post); // 最新の投稿を先頭に追加
      displayPosts();
      document.getElementById('postContent').value = ''; // 投稿後、入力欄を空にする
    }
  }

  function displayPosts() {
    const postList = document.getElementById('postList');
    postList.innerHTML = '';
    posts.forEach(post => {
      const postElement = document.createElement('div');
      postElement.innerHTML = `
        <div class="card mb-3">
          <div class="card-body">
            <p class="card-text">${post.content}</p>
            <small class="text-muted">Posted by ${post.author} (@${post.authorUsername}) at ${new Date(post.id).toLocaleString()}</small><br>
            <button onclick="likePost(${post.id})" class="btn btn-primary btn-sm mt-2">Like (${post.likes})</button>
            <button onclick="showComments(${post.id})" class="btn btn-secondary btn-sm mt-2">Comments</button>
          </div>
        </div>
      `;
      postList.appendChild(postElement);
    });
  }

  function likePost(postId) {
    const post = posts.find(p => p.id === postId);
    post.likes++;
    displayPosts();
  }

  function showComments(postId) {
    const post = posts.find(p => p.id === postId);
    const comments = prompt('Enter your comment:');
    if (comments !== null && comments.trim() !== '') {
      post.comments.push({ author: currentUser.name, content: comments });
      displayPosts();
    }
  }

  function hideAll() {
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('registerForm').style.display = 'none';
    document.getElementById('profile').style.display = 'none';
    document.getElementById('postForm').style.display = 'none';
  }

  users.push({ name: 'User One', username: 'user1', password: 'password1' });
  users.push({ name: 'User Two', username: 'user2', password: 'password2' });

  hideAll();
  document.getElementById('loginForm').style.display = 'block';
</script>

</body>
</html>

Javascript 文字列の整形

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My JavaScript</title>
</head>
<body>
  <script src="main.js"></script>
</body>
</html>

main.js

'use strict';

{
  const string = prompt('Name?');
  //if(string.toLowerCase() === 'taro'){
  if(string.toUpperCase().trim() === 'TARO'){
    console.log('Corrent!');
  }else{
    console.log('Wrong!');
  }
}