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 へアクセスして動作確認ができます。

ゲームの企画書タイトル: 運命の剣 (Sword of Fate)

1. 企画概要

•『運命の剣』は、選ばれし勇者が運命に導かれ、古代の剣を手にして世界を救うための冒険に挑むファンタジーRPGです。プレイヤーは広大な世界を探索し、強力な敵と戦い、数々の謎を解き明かしながら、壮大な物語を体験します。

2. ゲームコンセプト

世界観: 中世ヨーロッパ風のファンタジー世界。各地には古代文明の遺跡や魔法の力が残されている。

プレイヤーの目的: 運命の剣を見つけ、世界を脅かす闇の勢力を打倒する。

プレイスタイル: オープンワールド探索と、ターン制バトルを組み合わせたシステム。探索中に隠されたアイテムやサイドクエストを発見し、成長要素を深める。

3. メイン要素

運命の剣システム: プレイヤーが進むルートや選択によって、剣の能力や形状が変化する。異なる進化を遂げた剣がストーリーに影響を与える。

カスタマイズ要素: 装備やスキルを自由にカスタマイズ可能。プレイヤーの好みに応じて戦闘スタイルを変更できる。

マルチエンディング: 物語の進行や選択によって、結末が変化する複数のエンディングを用意。

4. キャラクター

主人公: 幼少期に運命の剣のビジョンを見せられた若き勇者。物語の中で成長し、剣の真の力を覚醒させる。

仲間キャラクター: プレイヤーの冒険を助ける個性豊かなキャラクターが登場。魔法使い、盗賊、騎士など様々な役割を持つ。

5. ゲームの進行

メインストーリー: 世界を救うための運命的な旅を中心にした直線的なストーリー展開。

サブクエスト: 各地に点在する住民やギルドから依頼を受け、報酬を得る。サブクエストは世界観の深堀りに繋がる。

6. ターゲット層

•15歳以上のファンタジーRPG愛好者

•長時間プレイできる深い物語や戦略的なバトルを好むプレイヤー

7. マネタイズ

無料プレイ+アプリ内課金モデル: 装備アイテム、キャラクターカスタマイズ、ストーリー進行を助けるアイテムの購入。

広告収入: 一定のプレイ時間後に広告を表示し、広告非表示機能を課金で解除可能にする。

Rust Todo-list

1. プロジェクトの作成と依存関係の追加

まず、Rustプロジェクトを作成し、必要なクレートを追加します。

bashコードをコピーする
argo new advanced_todo_list
cd advanced_todo_list

Cargo.tomlに以下の依存関係を追加します。

tomlコードをコピーする
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
clap = { version = "4.0", features = ["derive"] }

2. コード全体の実装

次に、src/main.rsに以下のコードを記述します。clapを使ってコマンドライン引数を処理するように変更しています。

use clap::{Parser, Subcommand};
use serde::{Serialize, Deserialize};
use std::fs::OpenOptions;
use std::io::{self, Read, Write};
use std::time::SystemTime;

#[derive(Serialize, Deserialize, Debug)]
struct TodoItem {
id: usize,
task: String,
description: String,
priority: String, // e.g., "High", "Medium", "Low"
due_date: Option<String>, // Due date in "YYYY-MM-DD" format
completed: bool,
created_at: SystemTime,
}

impl TodoItem {
fn new(id: usize, task: String, description: String, priority: String, due_date: Option<String>) -> Self {
TodoItem {
id,
task,
description,
priority,
due_date,
completed: false,
created_at: SystemTime::now(),
}
}

fn mark_as_completed(&mut self) {
self.completed = true;
}
}

#[derive(Parser)]
#[command(name = "Todo List")]
#[command(about = "A simple todo list application", long_about = None)]
struct Cli {
#[command(subcommand)]
command: Option<Command>,
}

#[derive(Subcommand)]
enum Command {
Add {
task: String,
description: String,
priority: String,
due_date: Option<String>,
},
List,
Edit {
id: usize,
},
Delete {
id: usize,
},
Complete {
id: usize,
},
}

fn load_todos() -> Vec<TodoItem> {
let mut file = match OpenOptions::new().read(true).open("todos.json") {
Ok(file) => file,
Err(_) => return Vec::new(),
};
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
serde_json::from_str(&content).unwrap_or(Vec::new())
}

fn save_todos(todos: &Vec<TodoItem>) {
let content = serde_json::to_string_pretty(todos).unwrap();
let mut file = OpenOptions::new().write(true).create(true).truncate(true).open("todos.json").unwrap();
file.write_all(content.as_bytes()).unwrap();
}

fn add_todo(task: String, description: String, priority: String, due_date: Option<String>) {
let mut todos = load_todos();
let id = if todos.is_empty() { 1 } else { todos.last().unwrap().id + 1 };
let new_todo = TodoItem::new(id, task, description, priority, due_date);
todos.push(new_todo);
save_todos(&todos);
println!("Task added!");
}

fn list_todos() {
let mut todos = load_todos();
todos.sort_by(|a, b| a.priority.cmp(&b.priority)); // Sort by priority

for todo in &todos {
println!(
"[{}] {} - {} (Priority: {}, Due: {}, Completed: {})",
todo.id,
todo.task,
todo.description,
todo.priority,
todo.due_date.as_deref().unwrap_or("N/A"),
if todo.completed { "Yes" } else { "No" }
);
}
}

fn edit_todo(id: usize) {
let mut todos = load_todos();

if let Some(todo) = todos.iter_mut().find(|t| t.id == id) {
println!("Editing task: {}", todo.task);

let mut new_description = String::new();
println!("Enter new description (leave blank to keep current):");
io::stdin().read_line(&mut new_description).unwrap();
if !new_description.trim().is_empty() {
todo.description = new_description.trim().to_string();
}

let mut new_priority = String::new();
println!("Enter new priority (High, Medium, Low, leave blank to keep current):");
io::stdin().read_line(&mut new_priority).unwrap();
if !new_priority.trim().is_empty() {
todo.priority = new_priority.trim().to_string();
}

save_todos(&todos);
println!("Task updated!");
} else {
println!("Task not found!");
}
}

fn delete_todo(id: usize) {
let mut todos = load_todos();
todos.retain(|todo| todo.id != id);
save_todos(&todos);
println!("Task deleted!");
}

fn complete_todo(id: usize) {
let mut todos = load_todos();

if let Some(todo) = todos.iter_mut().find(|t| t.id == id) {
todo.mark_as_completed();
save_todos(&todos);
println!("Task marked as completed!");
} else {
println!("Task not found!");
}
}

fn main() {
let args = Cli::parse();

match args.command {
Some(Command::Add { task, description, priority, due_date }) => {
add_todo(task, description, priority, due_date);
}
Some(Command::List) => {
list_todos();
}
Some(Command::Edit { id }) => {
edit_todo(id);
}
Some(Command::Delete { id }) => {
delete_todo(id);
}
Some(Command::Complete { id }) => {
complete_todo(id);
}
None => {
println!("No command provided. Use --help for available commands.");
}
}
}

3. 実行方法

UTF-8で保存されたこのファイルをコンパイルして実行します。コマンドの例は以下の通りです。

  • 新しいタスクの追加:bashコードをコピーするcargo run -- add "Buy groceries" "Buy milk, eggs, and bread" "High" "2024-10-10"
  • タスクのリスト表示:bashコードをコピーするcargo run -- list
  • タスクの編集:bashコードをコピーするcargo run -- edit 1
  • タスクの削除:bashコードをコピーするcargo run -- delete 1
  • タスクの完了:bashコードをコピーするcargo run -- complete 1

説明

  • clapクレートを使用してコマンドライン引数のパースを行います。これにより、タスクの追加や表示、編集、削除、完了などの操作をコマンドラインから行うことができます。
  • UTF-8エンコーディングmain.rsを保存し、エンコーディングエラーを回避しています。

これで、タスクの管理を行うためのコマンドラインTODOリストアプリケーションが完成しました。

PHP Todo-list

<?php
// タスクを保存するファイル
$tasks_file = 'tasks.txt';

// タスクを追加
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_task'])) {
    $new_task = trim($_POST['new_task']);
    if (!empty($new_task)) {
        $task_entry = $new_task . '|0'; // 0は未完了ステータスを示す
        file_put_contents($tasks_file, $task_entry . PHP_EOL, FILE_APPEND);
    }
}

// タスクの完了ステータスを変更
if (isset($_GET['toggle'])) {
    $tasks = file($tasks_file, FILE_IGNORE_NEW_LINES);
    $index = $_GET['toggle'];
    if (isset($tasks[$index])) {
        $task_data = explode('|', $tasks[$index]);
        $task_data[1] = $task_data[1] == '0' ? '1' : '0'; // ステータスを切り替える
        $tasks[$index] = implode('|', $task_data);
        file_put_contents($tasks_file, implode(PHP_EOL, $tasks) . PHP_EOL);
    }
}

// タスクを削除
if (isset($_GET['remove'])) {
    $tasks = file($tasks_file, FILE_IGNORE_NEW_LINES);
    unset($tasks[$_GET['remove']]);
    file_put_contents($tasks_file, implode(PHP_EOL, $tasks) . PHP_EOL);
}

// 現在のタスクを取得
$tasks = file_exists($tasks_file) ? file($tasks_file, FILE_IGNORE_NEW_LINES) : [];
?>

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>TODOリスト</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 20px;
        }
        h1 {
            text-align: center;
        }
        form {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }
        input[type="text"] {
            width: 300px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }
        button {
            padding: 10px 20px;
            border: none;
            background-color: #5cb85c;
            color: white;
            border-radius: 5px;
            cursor: pointer;
        }
        button:hover {
            background-color: #4cae4c;
        }
        ul {
            list-style-type: none;
            padding: 0;
        }
        li {
            background-color: #fff;
            margin: 5px 0;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .completed {
            text-decoration: line-through;
            color: gray;
        }
        a {
            text-decoration: none;
            color: #d9534f;
            margin-left: 10px;
        }
        a:hover {
            color: #c9302c;
        }
    </style>
</head>
<body>
    <h1>TODOリスト</h1>

    <!-- タスクを追加するフォーム -->
    <form method="post" action="">
        <input type="text" name="new_task" placeholder="新しいタスクを入力" required>
        <button type="submit">追加</button>
    </form>

    <!-- タスクを表示 -->
    <ul>
        <?php foreach ($tasks as $index => $task): ?>
            <?php list($task_text, $status) = explode('|', $task); ?>
            <li>
                <span class="<?php echo $status == '1' ? 'completed' : ''; ?>">
                    <?php echo htmlspecialchars($task_text); ?>
                </span>
                <div>
                    <a href="?toggle=<?php echo $index; ?>">
                        <?php echo $status == '0' ? '完了にする' : '未完了に戻す'; ?>
                    </a>
                    <a href="?remove=<?php echo $index; ?>">削除</a>
                </div>
            </li>
        <?php endforeach; ?>
    </ul>
</body>
</html>