python バケモン

import random

class Bakemon:
    def __init__(self, name, hp, attack):
        self.name = name
        self.hp = hp
        self.attack = attack

    def is_alive(self):
        return self.hp > 0

    def take_damage(self, damage):
        self.hp -= damage
        if self.hp < 0:
            self.hp = 0

    def attack_opponent(self, opponent):
        damage = random.randint(1, self.attack)
        opponent.take_damage(damage)
        return damage

def create_bakemon():
    bakemon_list = [
        Bakemon("Bakachu", 50, 10),
        Bakemon("Charabak", 60, 12),
        Bakemon("Bakasaur", 55, 11),
        Bakemon("Squirtlemon", 50, 10)
    ]
    return bakemon_list

def choose_bakemon(bakemon_list):
    print("Choose your Bakemon:")
    for idx, bakemon in enumerate(bakemon_list):
        print(f"{idx + 1}. {bakemon.name} (HP: {bakemon.hp}, Attack: {bakemon.attack})")
    choice = int(input("Enter the number of your choice: ")) - 1
    return bakemon_list[choice]

def battle(player_bakemon, enemy_bakemon):
    print(f"A wild {enemy_bakemon.name} appeared!")
    while player_bakemon.is_alive() and enemy_bakemon.is_alive():
        print(f"\n{player_bakemon.name} (HP: {player_bakemon.hp}) vs {enemy_bakemon.name} (HP: {enemy_bakemon.hp})")
        action = input("Do you want to attack (a) or run (r)? ").lower()
        if action == 'a':
            damage = player_bakemon.attack_opponent(enemy_bakemon)
            print(f"{player_bakemon.name} dealt {damage} damage to {enemy_bakemon.name}!")
            if enemy_bakemon.is_alive():
                damage = enemy_bakemon.attack_opponent(player_bakemon)
                print(f"{enemy_bakemon.name} dealt {damage} damage to {player_bakemon.name}!")
            else:
                print(f"{enemy_bakemon.name} is defeated!")
                break
        elif action == 'r':
            print("You ran away!")
            break
        else:
            print("Invalid action. Please choose again.")
    
    if not player_bakemon.is_alive():
        print(f"{player_bakemon.name} is defeated! Game over.")
        return False
    return True

def main():
    print("Welcome to the Bakemon game!")
    bakemon_list = create_bakemon()
    player_bakemon = choose_bakemon(bakemon_list)
    
    while True:
        enemy_bakemon = random.choice(bakemon_list)
        if enemy_bakemon == player_bakemon:
            continue
        if not battle(player_bakemon, enemy_bakemon):
            break
        play_again = input("Do you want to battle again? (y/n): ").lower()
        if play_again != 'y':
            print("Thanks for playing! Goodbye.")
            break

if __name__ == "__main__":
    main()

GPT-2 ChatBot

import nltk
from transformers import pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import numpy as np
import spacy

# nltkのセットアップ(初回のみ)
nltk.download('punkt')

# spaCyのセットアップ
nlp = spacy.load("en_core_web_sm")

# サンプルデータ(インテントとそのサンプル文)
training_sentences = [
    "Hello", "Hi", "Hey", "Good morning", "Good evening",
    "How are you?", "What's up?", "How's it going?",
    "Bye", "Goodbye", "See you later", "Take care",
    "Thank you", "Thanks", "I appreciate it",
    "What's your name?", "Who are you?",
    "What can you do?", "Tell me a joke", "Make me laugh",
    "What's the weather like?", "How's the weather?",
    "Book a flight", "I need to book a flight", "Can you book a flight for me?"
]

intents = [
    "greeting", "greeting", "greeting", "greeting", "greeting",
    "how_are_you", "how_are_you", "how_are_you",
    "goodbye", "goodbye", "goodbye", "goodbye",
    "thanks", "thanks", "thanks",
    "name", "name",
    "capabilities", "joke", "joke",
    "weather", "weather",
    "book_flight", "book_flight", "book_flight"
]

# 特徴抽出器と分類器のセットアップ
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(training_sentences)
classifier = LogisticRegression()
classifier.fit(X, intents)

# GPT-2 を使用したテキスト生成パイプラインの作成
chatbot = pipeline("text-generation", model="gpt2")

# インテントに基づく応答
responses = {
    "greeting": ["Hello! How can I help you?", "Hi there! What can I do for you?"],
    "how_are_you": ["I'm just a bot, but I'm here to help you!", "I'm fine, thank you! How can I assist you today?"],
    "goodbye": ["Goodbye! Have a great day!", "See you later!"],
    "thanks": ["You're welcome!", "No problem!"],
    "name": ["I am your friendly chatbot.", "I'm an AI created to assist you."],
    "capabilities": ["I can chat with you and help answer your questions!", "I'm here to assist you with various tasks."],
    "joke": ["Why did the scarecrow win an award? Because he was outstanding in his field!"],
    "weather": ["The weather is nice today!", "It's a bit cloudy, but still good."],
    "book_flight": ["Sure, I can help you with that. Where would you like to go?"]
}

# 未知のインテントに対するエラーレスポンス
default_responses = ["I'm not sure I understand. Can you please rephrase?", "Sorry, I don't have an answer for that."]

# インテント認識
def get_intent(user_input):
    X_test = vectorizer.transform([user_input])
    intent = classifier.predict(X_test)[0]
    return intent

# エンティティ認識
def get_entities(user_input):
    doc = nlp(user_input)
    entities = {ent.label_: ent.text for ent in doc.ents}
    return entities

# 応答生成
def get_response(user_input):
    intent = get_intent(user_input)
    entities = get_entities(user_input)
    
    if intent in responses:
        response = np.random.choice(responses[intent])
        if intent == "book_flight" and "GPE" in entities:
            response = f"Sure, I can help you book a flight to {entities['GPE']}. When would you like to travel?"
        return response
    else:
        response = chatbot(user_input, max_length=50, num_return_sequences=1)
        return response[0]['generated_text']

# メイン関数
def main():
    print("Chatbot: Hello! How can I help you today? (Type 'exit' to quit)")
    
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'exit':
            print("Chatbot: Goodbye!")
            break
        response = get_response(user_input)
        print(f"Chatbot: {response}")

if __name__ == "__main__":
    main()

CSS transition-delay

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 Animation</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="box"></div>
</body>

</html>

style.css

@charset "utf-8";

.box {
    width: 80px;
    height: 80px;
    background: pink;
    transition-property: transform;
    transition-duration: 500ms;
    transition-delay: 1s;
}

.box:hover {
    transform: translateX(100px);
}

java 数当てゲーム

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        boolean playAgain = true;
        int highScore = 0;

        System.out.println("数当てゲームへようこそ!");

        while (playAgain) {
            int minRange = 1;
            int maxRange = 100;
            int randomNumber = (int) (Math.random() * (maxRange - minRange + 1)) + minRange;
            int attempts = 0;

            System.out.println("1から100までの数を当ててください!");

            while (true) {
                System.out.print("予想した数字を入力してください: ");
                if (!scanner.hasNextInt()) {
                    System.out.println("無効な入力です。数値を入力してください。");
                    scanner.next(); // 不正な入力をクリア
                    continue;
                }
                int guessedNumber = scanner.nextInt();
                attempts++;

                if (guessedNumber < randomNumber) {
                    System.out.println("もっと大きい数字です。");
                } else if (guessedNumber > randomNumber) {
                    System.out.println("もっと小さい数字です。");
                } else {
                    System.out.println("おめでとうございます!正解です!");
                    System.out.println("あなたの試行回数: " + attempts);
                    if (attempts < highScore || highScore == 0) {
                        highScore = attempts;
                        System.out.println("新しいハイスコア!試行回数: " + highScore);
                    } else {
                        System.out.println("ハイスコアは" + highScore + "回です。");
                    }
                    break;
                }
            }

            System.out.print("もう一度プレイしますか? (y/n): ");
            String playChoice = scanner.next();
            playAgain = playChoice.equalsIgnoreCase("y");
        }

        System.out.println("ゲームを終了します。");
        System.out.println("最終ハイスコア: " + highScore);
        scanner.close();
    }
}

CSS ブレイクポイント

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 Media Queries</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  
</body>
</html>

style.css

@charset "utf-8";

body {
    background: pink;
}

/* width >= 600px */
@media (min-width: 600px) {
    body {
        background: skyblue;
    }
}

@media (min-width: 800px) {
    body {
        background: orange;
    }
}

動画共有サイト

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>動画共有サイト</title>
    <style>
        /* スタイルは省略 */
    </style>
</head>
<body>
    <header>
        <h1>動画共有サイト</h1>
    </header>
    <main>
        <section id="video-container">
            <!-- 動画を表示 -->
            <iframe width="560" height="315" src="https://www.youtube.com/embed/Qkls4DCX_9I" frameborder="0" allowfullscreen></iframe>
        </section>
        <section id="comments-container">
            <!-- コメントを表示 -->
        </section>
        <section id="comment-form-container">
            <!-- コメントを投稿するフォーム -->
            <form id="comment-form">
                <textarea id="comment-input" rows="3" placeholder="コメントを入力してください"></textarea>
                <button type="submit">コメントを投稿</button>
            </form>
        </section>
        <section id="categories">
            <!-- カテゴリ一覧 -->
            <h2>カテゴリ</h2>
            <ul>
                <li><a href="#">音楽</a></li>
                <li><a href="#">スポーツ</a></li>
                <li><a href="#">ゲーム</a></li>
                <li><a href="#">ニュース</a></li>
            </ul>
        </section>
    </main>
    <footer>
        <!-- お気に入りボタン -->
        <button id="favorite-button">お気に入り</button>
        <!-- 検索フォーム -->
        <input type="text" id="search-input" placeholder="動画を検索">
        <button id="search-button">検索</button>
    </footer>
    <script>
        // コメントを追加する関数
        function addComment(comment) {
            var commentsContainer = document.getElementById('comments-container');
            var commentElement = document.createElement('div');
            commentElement.textContent = comment;
            commentsContainer.appendChild(commentElement);
        }

        // フォームの送信イベントを処理する
        document.getElementById('comment-form').addEventListener('submit', function(event) {
            event.preventDefault(); // フォームのデフォルトの動作を停止

            var commentInput = document.getElementById('comment-input');
            var commentText = commentInput.value.trim(); // 入力されたコメントを取得

            if (commentText !== '') {
                addComment(commentText); // コメントを追加
                commentInput.value = ''; // 入力欄をクリア
            }
        });

        // お気に入りボタンのクリックイベントを処理する
        document.getElementById('favorite-button').addEventListener('click', function() {
            alert('動画をお気に入りに追加しました!');
        });

        // 検索ボタンのクリックイベントを処理する
        document.getElementById('search-button').addEventListener('click', function() {
            var searchInput = document.getElementById('search-input').value.trim();
            alert('「' + searchInput + '」で検索しました!');
        });
    </script>
</body>
</html>

Pinterest風サイト

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pintrest風サイト</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f0f0f0;
        }

        header {
            background-color: #333;
            color: #fff;
            padding: 20px;
            text-align: center;
        }

        .container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            padding: 20px;
            margin: 0 auto;
            max-width: 1200px;
        }

        .card {
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 5px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
            cursor: pointer;
        }

        .card:hover {
            transform: translateY(-5px);
        }

        .card img {
            width: 100%;
            display: block;
            border-top-left-radius: 5px;
            border-top-right-radius: 5px;
        }

        .card-content {
            padding: 15px;
        }

        .card h2 {
            font-size: 18px;
            margin: 10px 0;
            color: #333;
        }

        .card p {
            font-size: 14px;
            color: #666;
            margin-top: 0;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 999;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.7);
        }

        .modal-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff;
            padding: 20px;
            border-radius: 5px;
        }

        .modal img {
            max-width: 100%;
            display: block;
            margin: 0 auto;
        }

        footer {
            background-color: #333;
            color: #fff;
            text-align: center;
            padding: 10px 0;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <header>
        <h1>Pintrest風サイト</h1>
    </header>

    <main>
        <div class="container">
            <div class="card" onclick="openModal('https://via.placeholder.com/800x600', 'Beautiful Sunset', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.')">
                <img src="https://via.placeholder.com/400x250" alt="Image 1">
                <div class="card-content">
                    <h2>Beautiful Sunset</h2>
                    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
                </div>
            </div>
            <div class="card" onclick="openModal('https://via.placeholder.com/800x600', 'Cute Kittens', 'Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.')">
                <img src="https://via.placeholder.com/400x300" alt="Image 2">
                <div class="card-content">
                    <h2>Cute Kittens</h2>
                    <p>Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.</p>
                </div>
            </div>
            <!-- More cards -->
        </div>
    </main>

    <div id="myModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeModal()">&times;</span>
            <img src="" alt="Modal Image" id="modalImage">
            <div id="caption"></div>
        </div>
    </div>

    <footer>
        <p>&copy; 2024 Pintrest風サイト</p>
    </footer>

    <script>
        function openModal(imageSrc, title, description) {
            document.getElementById("modalImage").src = imageSrc;
            document.getElementById("caption").innerHTML = "<h2>" + title + "</h2><p>" + description + "</p>";
            document.getElementById("myModal").style.display = "block";
        }

        function closeModal() {
            document.getElementById("myModal").style.display = "none";
        }
    </script>
</body>
</html>

HTMLCSS 画像付きの記事一覧を作る

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 Flexbox</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <article>
    <img src="forest.png" width="240" height="160">
    <div class="text">
      <h1>タイトル</h1>
      <p>こんにちは。こんにちは。</p>
    </div>
  </article>
</body>

</html>

style.css

@charset "utf-8";

article {
  display: flex;
  gap: 16px;
}

.text {
  background: pink;
  flex: 1;
}

CSS align-self、autoキーワード

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 Flexbox</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div class="item-1">1</div>
    <div class="item-2">2</div>
    <div class="item-3">3</div>
  </div>
</body>

</html>

style.css

@charset "utf-8";

.container {
  border: 8px solid blue;
  display: flex;
  height: 240px;
}

.item-1 {
  width: 80px;
  height: 80px;
  background-color: pink;
  align-self: center;
}

.item-2 {
  width: 80px;
  height: 80px;
  background-color: skyblue;
  margin-left: auto;
}

.item-3 {
  width: 80px;
  height: 80px;
  background-color: orange;
}

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>