- 前端 (React + JavaScript)gzrrgx.com
React组件 (TodoList.js)
jsx
import React, { useState } from ‘react’;
function TodoList() {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState(‘’);
const handleSubmit = (event) => {
event.preventDefault();
if (newTodo.trim() !== ‘’) {
setTodos([…todos, { id: Date.now(), text: newTodo, completed: false }]);
setNewTodo(‘’);
}
};
return (
<input
type=“text”
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
placeholder=“Add a new todo”
/>
Add Todo
{todos.map((todo) => (
- {todo.text}
))}
);
}
export default TodoList;
2. 后端 (Node.js + Express)
服务器端代码 (server.js)
javascript
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const app = express();
const PORT = 3001;
app.use(bodyParser.json());
let todos = [];
app.get(‘/todos’, (req, res) => {
res.json(todos);
});
app.post(‘/todos’, (req, res) => {
const newTodo = {
id: Date.now(),
text: req.body.text,
completed: false
};
todos.push(newTodo);
res.status(201).json(newTodo);
});
app.listen(PORT, () => {
console.log(Server running on port ${PORT}
);
});
3. 数据库 (MongoDB 示例)
如果你决定使用MongoDB作为数据库,你需要使用Mongoose(一个ODM库)来管理你的数据模型。
MongoDB 模型 (Todo.js)
javascript
const mongoose = require(‘mongoose’);
const TodoSchema = new mongoose.Schema({
text: String,
completed: Boolean,
createdAt: { type: Date, default: Date.now }
});
const Todo = mongoose.model(‘Todo’, TodoSchema);
module.exports = Todo;
然后,在你的Express应用中,你需要连接到MongoDB并更新你的路由以使用Mongoose模型。
- 跨平台移动App (Flutter)
虽然Flutter主要关注于UI,但你也可以用它来调用后端API。
Flutter 示例 (简单界面)
dart
import ‘package:flutter/material.dart’;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(‘Todo List’),
),
body: Center(
child: Text(‘Todo List will go here’),
),
),
);
}
}
Flutter与后端服务的交互通常会通过HTTP请求(如使用dio或http库)进行。
结论
这里只是每个部分的非常基础的入门示例。在实际开发中,你会需要处理更多的边缘情况、错误处理、用户认证、数据验证等。此外,构建一个完整的App还涉及到状态管理(如Redux在React中)、路由管理(如React Router或Flutter的Navigator)以及可能的测试(单元测试、集成测试等)。由于篇幅限制,我将为你提供用几种不同编程语言编写的简单游戏示例:猜数字游戏。这个游戏会随机生成一个1到100之间的数字,然后让用户猜测这个数是多少,直到猜对为止。
- Python
python
import random
def guess_number_game():
number_to_guess = random.randint(1, 100)
guess = None
tries = 0
print("欢迎来到猜数字游戏!")
print("我已经想好了一个1到100之间的数字。你能猜到是多少吗?")
while guess != number_to_guess:
try:
guess = int(input("请输入你的猜测:"))
tries += 1
if guess < number_to_guess:
print("太低了!")
elif guess > number_to_guess:
print("太高了!")
else:
print(f"恭喜你,猜对了!数字是{number_to_guess}。你总共猜了{tries}次。")
except ValueError:
print("请输入一个有效的数字!")
guess_number_game()
2. JavaScript (Node.js 环境)
javascript
const readline = require(‘readline’).createInterface({
input: process.stdin,
output: process.stdout
});
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let tries = 0;
console.log(“欢迎来到猜数字游戏!”);
console.log(“我已经想好了一个1到100之间的数字。你能猜到是多少吗?”);
function checkGuess() {
if (guess === null) {
console.log(“请输入你的猜测:”);
readline.question(‘’, (answer) => {
guess = parseInt(answer, 10);
if (isNaN(guess)) {
console.log(“请输入一个有效的数字!”);
checkGuess();
} else {
processGuess();
}
});
}
}
function processGuess() {
tries++;
if (guess < numberToGuess) {
console.log(“太低了!”);
} else if (guess > numberToGuess) {
console.log(“太高了!”);
} else {
console.log(恭喜你,猜对了!数字是${numberToGuess}。你总共猜了${tries}次。
);
readline.close();
}
guess = null; // Reset for next guess
checkGuess();
}
checkGuess();
3. Java
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
int guess = 0;
int tries = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到猜数字游戏!");
System.out.println("我已经想好了一个1到100之间的数字。你能猜到是多少吗?");
while (guess != numberToGuess) {
System.out.print("请输入你的猜测:");
if (scanner.hasNextInt()) {
guess = scanner.nextInt();
tries++;
if (guess < numberToGuess) {
System.out.println("太低了!");
} else if (guess > numberToGuess) {
System.out.println("太高了!");
} else {
System.out.println("恭喜你,猜对了!数字是" + numberToGuess + "。你总共猜了" + tries + "次。");
}
} else {
System.out.println("请输入一个有效的数字!");
scanner.next(); // consume input
}
}
scanner.close();
}
}
以上代码分别展示了如何用Python、JavaScript(Node.js环境)和Java编写一个简单的猜数字游戏。每种语言都有其独特的特性和语法,但核心逻辑是相似的。