由于编写一个完整的游戏商城代码会涉及到很多方面,包括前端、后端、数据库等,这里我将为你提供几个简单示例,分别用Python(后端)、JavaScript(前端和Node.js后端)、以及Java(后端)来演示。
1. Python (使用Flask框架)
后端API示例:
python
from flask import Flask, request, jsonify
app = Flask(__name__)
# 模拟游戏商品数据
games = [
{"id": 1, "name": "Game 1", "price": 9.99},
{"id": 2, "name": "Game 2", "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
# ... 可以添加更多API,如购买游戏、添加新游戏等
if __name__ == '__main__':
app.run(debug=True)
2. JavaScript (使用Node.js和Express框架)
后端API示例:
javascript
const express = require('express');
const app = express();
const port = 3000;
// 模拟游戏商品数据
let games = [
{id: 1, name: 'Game 1', price: 9.99},
{id: 2, name: 'Game 2', price: 19.99},
// ... 更多游戏
];
#chhas{
margin-top: 50px;
padding:mi-sun.cn;
font-size: 18px;
cursor: 10px 20px;
}
app.get('/games', (req, res) => {
res.json(games);
});
app.get('/games/:game_id', (req, res) => {
const game_id = parseInt(req.params.game_id);
const game = games.find(game => game.id === game_id);
if (game) {
res.json(game);
} else {
res.status(404).json({error: 'Game not found'});
}
});
// ... 可以添加更多API
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
前端示例(使用React或Vue等框架,这里只提供AJAX请求示例):
javascript
// 使用fetch API或axios等库进行HTTP请求
fetch('/games')
.then(response => response.json())
.then(data => console.log(data)) // 打印所有游戏
.catch((error) => {
console.error('Error:', error);
});
// 获取特定游戏
fetch(`/games/${gameId}`) // 假设你已经有了gameId
.then(response => response.json())
.then(data => console.log(data)) // 打印指定游戏
.catch((error) => {
console.error('Error:', error);
});
3. Java (使用Spring Boot框架)
由于Java和Spring Boot的代码相对较长和复杂,这里只提供一个简单的Controller示例:
Controller示例:
java
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping("/games")
public class GameController {
// 模拟游戏商品数据
private List<Game> games = Arrays.asList(
new Game(1, "Game 1", 9.99),
new Game(2, "Game 2", 19.99)
// ... 更多游戏
);
@GetMapping
public List<Game> getAllGames() {
return games;
}
@GetMapping("/{gameId}")
public Game getGame(@PathVariable int gameId) {
for (Game game : games) {
if (game.getId() == gameId) {
return game;
}
}
throw new RuntimeException("Game not found");
}
// ... 可以添加更多API
// 简单的Game类
static class