- Python (Flask 后端示例)meimiaomeimo.cn
python
from flask import Flask, request, jsonify
app = Flask(name)
假设的游戏商品数据
games = [
{‘id’: 1, ‘name’: ‘Game A’, ‘price’: 9.99},
{‘id’: 2, ‘name’: ‘Game B’, ‘price’: 19.99},
# … 更多商品
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
for game in games:
if game[‘id’] == game_id:
return jsonify(game)
return jsonify({‘error’: ‘Game not found’}), 404
启动 Flask 应用 (实际部署时会有更多配置)
if name == ‘main’:
app.run(debug=True)
2. JavaScript (Node.js + Express 后端示例)
javascript
const express = require(‘express’);
const app = express();
const games = [/* … 与上面 Python 示例中的数据类似 … */];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const gameId = parseInt(req.params.gameId);
const game = games.find(game => game.id === gameId);
if (game) {
res.json(game);
} else {
res.status(404).json({ error: ‘Game not found’ });
}
});
app.listen(3000, () => console.log(‘Server started on port 3000’));
3. Java (Spring Boot 后端示例,伪代码)
由于 Java 示例较长,这里仅提供一个伪代码和接口描述。
java
// 伪代码,仅表示接口和方法名
@RestController
@RequestMapping(“/games”)
public class GameController {
// 假设有一个 GameService 来处理游戏数据
private final GameService gameService;
// 构造方法注入 GameService
public GameController(GameService gameService) {
this.gameService = gameService;
}
@GetMapping("")
public List<Game> getAllGames() {
return gameService.getAllGames();
}
@GetMapping("/{gameId}")
public ResponseEntity<Game> getGame(@PathVariable Long gameId) {
Game game = gameService.getGameById(gameId);
if (game == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(game);
}
}
前端示例 (HTML + JavaScript 使用 Fetch API)
由于前端通常与后端通过 API 进行交互,这里仅提供一个简单的 HTML 页面和 JavaScript 代码来调用上面的 /games API。
html
Game Shop
Fetch Games<script>
async function fetchGames() {
try {
const response = await fetch('/games'); // 假设后端运行在相同的主机和端口上
const games = await response.json();
console.log(games); // 在控制台打印游戏列表
} catch (error) {
console.error('Error fetching games:', error);
}
}
</script>
由于编写一个完整的游戏商城代码涉及到许多方面(如前端、后端、数据库等),这里我将为您提供一个简化的示例,分别用几种不同的编程语言来描述游戏商城的核心部分。
- Python (Flask 后端示例)
python
from flask import Flask, request, jsonify
app = Flask(name)
假设的游戏商品数据
games = [
{‘id’: 1, ‘name’: ‘Game A’, ‘price’: 9.99},
{‘id’: 2, ‘name’: ‘Game B’, ‘price’: 19.99},
# … 更多商品
]
@app.route(‘/games’, methods=[‘GET’])
def get_games():
return jsonify(games)
@app.route(‘/games/int:game_id’, methods=[‘GET’])
def get_game(game_id):
for game in games:
if game[‘id’] == game_id:
return jsonify(game)
return jsonify({‘error’: ‘Game not found’}), 404
启动 Flask 应用 (实际部署时会有更多配置)
if name == ‘main’:
app.run(debug=True)
2. JavaScript (Node.js + Express 后端示例)
javascript
const express = require(‘express’);
const app = express();
const games = [/* … 与上面 Python 示例中的数据类似 … */];
app.get(‘/games’, (req, res) => {
res.json(games);
});
app.get(‘/games/:gameId’, (req, res) => {
const gameId = parseInt(req.params.gameId);
const game = games.find(game => game.id === gameId);
if (game) {
res.json(game);
} else {
res.status(404).json({ error: ‘Game not found’ });
}
});
app.listen(3000, () => console.log(‘Server started on port 3000’));
3. Java (Spring Boot 后端示例,伪代码)
由于 Java 示例较长,这里仅提供一个伪代码和接口描述。
java
// 伪代码,仅表示接口和方法名
@RestController
@RequestMapping(“/games”)
public class GameController {
// 假设有一个 GameService 来处理游戏数据
private final GameService gameService;
// 构造方法注入 GameService
public GameController(GameService gameService) {
this.gameService = gameService;
}
@GetMapping("")
public List<Game> getAllGames() {
return gameService.getAllGames();
}
@GetMapping("/{gameId}")
public ResponseEntity<Game> getGame(@PathVariable Long gameId) {
Game game = gameService.getGameById(gameId);
if (game == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(game);
}
}
前端示例 (HTML + JavaScript 使用 Fetch API)
由于前端通常与后端通过 API 进行交互,这里仅提供一个简单的 HTML 页面和 JavaScript 代码来调用上面的 /games API。
html
Game Shop
Fetch Games<script>
async function fetchGames() {
try {
const response = await fetch('/games'); // 假设后端运行在相同的主机和端口上
const games = await response.json();
console.log(games); // 在控制台打印游戏列表
} catch (error) {
console.error('Error fetching games:', error);
}
}
</script>