Javascript map()

<!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>
'use strict';

{
  const prices = [100, 150, 200];

  // const pricesWithTax = [];
  // prices.forEach((price) => {
  //   pricesWithTax.push(price * 1.1);
  // });

  const pricesWithTax = prices.map((price) => {
    return price * 1.1;
  });

  console.log(pricesWithTax);
}

Javascript join()、split()

imdex.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 names = ['Taro', 'Jiro', 'Saburo'];

  // // Taro|Jiro|Saburo
  // console.log(names.join('|'));
  // console.log(names.join());
  // console.log(names.join(''));

  const names = 'Taro|Jiro|Saburo';
  console.log(names.split('|'));
}

Javascript 配列の値

<!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 scores = [
    70, 
    95, 
    80, 
    85,
  ];
  let sum = 0;
// console.log(scores[0]);
// console.log(scores[1]);
// console.log(scores[2]);
// console.log(scores[3]);

scores.forEach((score, index) => {
 // console.log(score);
 sum += score;
 console.log(`${index}: ${score}`);
});

console.log(`Sum: ${sum}`);
console.log(`Average: ${sum / scores.length}`);
}

Javascript forEach()

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>
'use strict';

{
  const scores = [
    70, 
    95, 
    80, 
    85,
  ];

// console.log(scores[0]);
// console.log(scores[1]);
// console.log(scores[2]);
// console.log(scores[3]);

scores.forEach((score, index) => {
 // console.log(score);
 console.log(`${index}: ${score}`);
});
}

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 scores = [
    70, 
    95, 
    80, 
    85,
  ];

// console.log(scores[0]);
// console.log(scores[1]);
// console.log(scores[2]);
// console.log(scores[3]);

scores.push(77, 88);

for(let i = 0; i <= 4; i++){
  console.log(scores[i]);
}
}

マルチプレイヤー数当てゲーム

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>マルチプレイヤー数当てゲーム</title>
</head>
<body>
<header>
  <h1>マルチプレイヤー数当てゲーム</h1>
</header>

<div class="player-registration">
  <input type="text" id="playerName" placeholder="プレイヤー名">
  <input type="file" id="profileImage" accept="image/*">
  <button id="submitPlayer">プレイヤー登録</button>
</div>

<!-- モーダルウィンドウの追加 -->
<div id="modal" class="modal">
  <div class="modal-content">
    <span class="close-button">×</span>
    <p id="modalMessage"></p>
  </div>
</div>

<section class="game-rules">
  <h2>ゲームのルール</h2>
  <p>1から100までの数字を10回以内に当ててください。正解するとポイントが獲得できます。</p>
</section>

<div class="game-container">
  <div class="user-stats">
    <p>総プレイゲーム数: <span id="totalGamesPlayed">0</span></p>
    <p>正解総数: <span id="totalCorrectGuesses">0</span></p>
  </div>

  <div class="live-feedback" id="liveFeedback"></div>

  <input type="number" id="guessInput" min="1" max="100" placeholder="あなたの予想">
  <button id="guessButton">予想する</button>
  <p id="message"></p>
  <p>残り予想回数: <span id="remainingGuesses">10</span></p>
</div>

<div class="leaderboard">
  <h2>トッププレイヤー</h2>
  <ul id="topPlayers"></ul>
</div>

<footer>
  <p>© 2023 数当てゲーム開発者</p>
  <p>お問い合わせ: <a href="mailto:contact:tyosuke2010@gmail.com">contact:tyosuke2010@gmail.com</a></p>
</footer>

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

script.js

document.addEventListener('DOMContentLoaded', () => {
    let secretNumber = Math.floor(Math.random() * 100) + 1;
    let guessesRemaining = 10;
    let gamesPlayed = 0;
    let correctGuesses = 0;

    const playerNameInput = document.getElementById('playerName');
    const submitPlayerButton = document.getElementById('submitPlayer');
    const guessInput = document.getElementById('guessInput');
    const guessButton = document.getElementById('guessButton');
    const message = document.getElementById('message');
    const totalGamesPlayed = document.getElementById('totalGamesPlayed');
    const totalCorrectGuesses = document.getElementById('totalCorrectGuesses');
    const remainingGuesses = document.getElementById('remainingGuesses');
    const liveFeedback = document.getElementById('liveFeedback');

    submitPlayerButton.addEventListener('click', () => {
        const playerName = playerNameInput.value;
        if (playerName) {
            alert(`ようこそ、${playerName}さん!`);
            playerNameInput.disabled = true;
            submitPlayerButton.disabled = true;
        } else {
            alert('プレイヤー名を入力してください。');
        }
    });

    guessButton.addEventListener('click', () => {
        const userGuess = parseInt(guessInput.value);
        if (!userGuess || userGuess < 1 || userGuess > 100) {
            alert('1から100までの数字を入力してください。');
            return;
        }

        guessesRemaining--;
        remainingGuesses.textContent = guessesRemaining;

        if (userGuess === secretNumber) {
            correctGuesses++;
            totalCorrectGuesses.textContent = correctGuesses;
            message.textContent = `正解! ${userGuess} が正しい数字です!`;
            resetGame();
        } else if (guessesRemaining === 0) {
            message.textContent = `ゲームオーバー!正しい数字は ${secretNumber} でした。`;
            resetGame();
        } else {
            message.textContent = userGuess > secretNumber ? 'もっと低い数字です!' : 'もっと高い数字です!';
            liveFeedback.textContent = `あなたの予想: ${userGuess}`;
        }
    });

    function resetGame() {
        secretNumber = Math.floor(Math.random() * 100) + 1;
        guessesRemaining = 10;
        remainingGuesses.textContent = guessesRemaining;
        guessInput.value = '';
        gamesPlayed++;
        totalGamesPlayed.textContent = gamesPlayed;
    }
});

style.css

body {
    font-family: 'Arial', sans-serif;
    background-color: #f4f4f4;
    color: #333;
    line-height: 1.6;
    padding: 0;
    margin: 0;
    text-align: center;
}

header {
    background: #333;
    color: #fff;
    padding: 1rem 0;
    margin-bottom: 15px;
}

header h1 {
    margin: 0;
}

.player-registration, .game-container, .game-rules, .leaderboard {
    max-width: 600px;
    margin: 20px auto;
    padding: 20px;
    border: 1px solid #ddd;
    background: #fff;
    border-radius: 10px;
    box-shadow: 2px 2px 5px rgba(0,0,0,0.3);
}

input[type='text'], input[type='number'], input[type='file'], button {
    display: block;
    width: 90%;
    padding: 10px;
    margin: 10px auto;
    border-radius: 5px;
    border: 1px solid #ddd;
}

button {
    background-color: #5f9ea0;
    color: #fff;
    border: none;
    cursor: pointer;
}

button:hover {
    background-color: #486f70;
}

footer {
    background: #333;
    color: #fff;
    text-align: center;
    padding: 1rem 0;
    position: absolute;
    bottom: 0;
    width: 100%;
}

footer p {
    margin: 0;
}

/* 追加スタイル */
ul {
    list-style-type: none;
    padding: 0;
}

li {
    margin-bottom: 5px;
    
}

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';

{
  console.log(double(10));
  //関数宣言
  function double(num){
    return num * 2;
  }

  // //関数式
  // const double = function(num){
  //   return num * 2;
  // };
}

Javascirpt 引数のスコープ

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';

{
  function double(num){
    return num * 2;
  }
  function triple(num){
    return num * 3;
  }
  console.log(double(10));
  //console.log(num);
  console.log(triple(20));
}

Javascirpt カレンダー

<!DOCTYPE html>style.css
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>Calendar</title>
  <link rel="stylesheet" href="css/styles.css">
</head>
<body>
  <table>
    <thead>
      <tr>
        <th id="prev">«</th>
        <th id="title" colspan="5">2020/05</th>
        <th id="next">»</th>
      </tr>
      <tr>
        <th>Sun</th>
        <th>Mon</th>
        <th>Tue</th>
        <th>Wed</th>
        <th>Thu</th>
        <th>Fri</th>
        <th>Sat</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
    <tfoot>
      <tr>
        <td id="today" colspan="7">Today</td>
      </tr>
    </tfoot>
  </table>

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

style.css

body {
  font-family: 'Courier New', monospace;
  font-size: 14px;
}

table {
  border-collapse: collapse;
  border: 2px solid #eee;
}

thead,
tfoot {
  background: #eee;
}

th,
td {
  padding: 8px;
  text-align: center;
}

tbody td:first-child {
  color: red;
}

tbody td:last-child {
  color: blue;
}

tfoot {
  font-weight: bold;
}

td.disabled {
  opacity: 0.3;
}

td.today {
  font-weight: bold;
}

#prev,
#next,
#today {
  cursor: pointer;
  user-select: none;
}
'use strict';

console.clear();

{
  const today = new Date();
  let year = today.getFullYear();
  let month = today.getMonth();

  function getCalendarHead() {
    const dates = [];
    const d = new Date(year, month, 0).getDate();
    const n = new Date(year, month, 1).getDay();

    for (let i = 0; i < n; i++) {
      // 30
      // 29, 30
      // 28, 29, 30
      dates.unshift({
        date: d - i,
        isToday: false,
        isDisabled: true,
      });
    }

    return dates;
  }

  function getCalendarBody() {
    const dates = []; // date: 日付, day: 曜日
    const lastDate = new Date(year, month + 1, 0).getDate();

    for (let i = 1; i <= lastDate; i++) {
      dates.push({
        date: i,
        isToday: false,
        isDisabled: false,
      });
    }

    if (year === today.getFullYear() && month === today.getMonth()) {
      dates[today.getDate() - 1].isToday = true;
    }

    return dates;
  }

  function getCalendarTail() {
    const dates = [];
    const lastDay = new Date(year, month + 1, 0).getDay();

    for (let i = 1; i < 7 - lastDay; i++) {
      dates.push({
        date: i,
        isToday: false,
        isDisabled: true,
      });
    }

    return dates;
  }

  function clearCalendar() {
    const tbody = document.querySelector('tbody');

    while (tbody.firstChild) {
      tbody.removeChild(tbody.firstChild);
    }
  }

  function renderTitle() {
    const title = `${year}/${String(month + 1).padStart(2, '0')}`;
    document.getElementById('title').textContent = title;
  }

  function renderWeeks() {
    const dates = [
      ...getCalendarHead(),
      ...getCalendarBody(),
      ...getCalendarTail(),
    ];
    const weeks = [];
    const weeksCount = dates.length / 7;

    for (let i = 0; i < weeksCount; i++) {
      weeks.push(dates.splice(0, 7));
    }

    weeks.forEach(week => {
      const tr = document.createElement('tr');
      week.forEach(date => {
        const td = document.createElement('td');

        td.textContent = date.date;
        if (date.isToday) {
          td.classList.add('today');
        }
        if (date.isDisabled) {
          td.classList.add('disabled');
        }

        tr.appendChild(td);
      });
      document.querySelector('tbody').appendChild(tr);
    });
  }

  function createCalendar() {
    clearCalendar();
    renderTitle();
    renderWeeks();
  }

  document.getElementById('prev').addEventListener('click', () => {
    month--;
    if (month < 0) {
      year--;
      month = 11;
    }

    createCalendar();
  });

  document.getElementById('next').addEventListener('click', () => {
    month++;
    if (month > 11) {
      year++;
      month = 0;
    }

    createCalendar();
  });

  document.getElementById('today').addEventListener('click', () => {
    year = today.getFullYear();
    month = today.getMonth();

    createCalendar();
  });

  createCalendar();
}

python タスク

import os
import json
from datetime import datetime

class Task:
    def __init__(self, description, deadline=None, completed=False):
        self.description = description
        self.deadline = deadline
        self.completed = completed

    def to_dict(self):
        return {
            "description": self.description,
            "deadline": self.deadline.strftime("%Y-%m-%d %H:%M") if self.deadline else None,
            "completed": self.completed
        }

    @classmethod
    def from_dict(cls, task_dict):
        deadline_str = task_dict.get("deadline")
        deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
        return cls(task_dict["description"], deadline, task_dict["completed"])

class TaskList:
    def __init__(self, filename):
        self.filename = filename
        self.tasks = []
        self.load_tasks()

    def load_tasks(self):
        if os.path.exists(self.filename):
            with open(self.filename, 'r') as file:
                task_data = json.load(file)
                self.tasks = [Task.from_dict(task_dict) for task_dict in task_data]

    def save_tasks(self):
        with open(self.filename, 'w') as file:
            task_data = [task.to_dict() for task in self.tasks]
            json.dump(task_data, file, indent=4)

    def add_task(self, description, deadline_str=None):
        deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
        task = Task(description, deadline)
        self.tasks.append(task)
        self.save_tasks()
        print("タスクを追加しました")

    def edit_task(self, task_index, description=None, deadline_str=None):
        if 1 <= task_index <= len(self.tasks):
            task = self.tasks[task_index - 1]
            if description:
                task.description = description
            if deadline_str:
                task.deadline = datetime.strptime(deadline_str, "%Y-%m-%d %H:%M") if deadline_str else None
            self.save_tasks()
            print("タスクを編集しました")
        else:
            print("無効なタスク番号です")

    def display_tasks(self):
        if not self.tasks:
            print("タスクはありません")
        else:
            print("タスク一覧:")
            for i, task in enumerate(self.tasks, 1):
                status = "完了" if task.completed else "未完了"
                deadline = task.deadline.strftime("%Y-%m-%d %H:%M") if task.deadline else "なし"
                print(f"{i}. [{status}] {task.description} (締切: {deadline})")

    def mark_task_completed(self, task_index):
        if 1 <= task_index <= len(self.tasks):
            task = self.tasks[task_index - 1]
            task.completed = True
            self.save_tasks()
            print(f"タスク '{task.description}' を完了にしました")
        else:
            print("無効なタスク番号です")

    def delete_task(self, task_index):
        if 1 <= task_index <= len(self.tasks):
            deleted_task = self.tasks.pop(task_index - 1)
            self.save_tasks()
            print(f"タスク '{deleted_task.description}' を削除しました")
        else:
            print("無効なタスク番号です")

def main():
    filename = "tasks.json"
    task_list = TaskList(filename)

    while True:
        print("\n操作を選択してください:")
        print("1. タスクを追加")
        print("2. タスクを編集")
        print("3. タスク一覧を表示")
        print("4. タスクを完了にする")
        print("5. タスクを削除する")
        print("6. 終了")

        choice = input("選択 (1/2/3/4/5/6): ")

        if choice == '6':
            break
        elif choice == '1':
            description = input("新しいタスクの説明を入力してください: ")
            deadline_str = input("締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力可): ")
            task_list.add_task(description, deadline_str)
        elif choice == '2':
            task_list.display_tasks()
            task_index = int(input("編集するタスクの番号を入力してください: "))
            description = input("新しい説明を入力してください (未入力で変更なし): ")
            deadline_str = input("新しい締切日時 (YYYY-MM-DD HH:MM) を入力してください (未入力で変更なし): ")
            task_list.edit_task(task_index, description, deadline_str)
        elif choice == '3':
            task_list.display_tasks()
        elif choice == '4':
            task_list.display_tasks()
            task_index = int(input("完了にするタスクの番号を入力してください: "))
            task_list.mark_task_completed(task_index)
        elif choice == '5':
            task_list.display_tasks()
            task_index = int(input("削除するタスクの番号を入力してください: "))
            task_list.delete_task(task_index)
        else:
            print("無効な選択です")

if __name__ == "__main__":
    main()