
鸿蒙古诗接龙游戏开发指南 原创
鸿蒙古诗接龙游戏开发指南
一、系统架构设计
基于HarmonyOS的AI能力和分布式技术,我们设计了一套古诗接龙游戏系统,主要功能包括:
古诗生成:AI根据上下文生成符合格律的古诗
多人对战:支持多玩家实时对战
积分排行:记录玩家成绩和排名
多设备协同:跨设备同步游戏状态和数据
学习模式:提供古诗学习和赏析功能
!https://example.com/harmony-poetry-game-arch.png
二、核心代码实现
古诗生成服务
// PoetryGenerationService.ets
import http from ‘@ohos.net.http’;
class PoetryGenerationService {
private static instance: PoetryGenerationService;
private httpClient: http.HttpRequest;
private apiKey = ‘YOUR_POETRY_API_KEY’;
private constructor() {
this.httpClient = http.createHttp();
public static getInstance(): PoetryGenerationService {
if (!PoetryGenerationService.instance) {
PoetryGenerationService.instance = new PoetryGenerationService();
return PoetryGenerationService.instance;
public async generateNextLine(context: string, style: PoetryStyle = ‘五言绝句’): Promise<PoetryLine> {
return new Promise((resolve, reject) => {
this.httpClient.request(
'https://poetry-api.example.com/generate',
method: ‘POST’,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify({
context,
style,
api_key: this.apiKey
})
},
(err, data) => {
if (err) {
reject(err);
else {
const result = JSON.parse(data.result);
resolve(this.processPoetryResult(result));
}
);
});
private processPoetryResult(rawData: any): PoetryLine {
return {
text: rawData.text || '',
pinyin: rawData.pinyin || '',
meaning: rawData.meaning || '',
style: rawData.style || '五言绝句',
confidence: rawData.confidence || 0,
timestamp: Date.now()
};
public async evaluatePoetry(line: string, context: string): Promise<PoetryEvaluation> {
return new Promise((resolve, reject) => {
this.httpClient.request(
'https://poetry-api.example.com/evaluate',
method: ‘POST’,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify({
line,
context,
api_key: this.apiKey
})
},
(err, data) => {
if (err) {
reject(err);
else {
const result = JSON.parse(data.result);
resolve(this.processEvaluationResult(result));
}
);
});
private processEvaluationResult(rawData: any): PoetryEvaluation {
return {
score: rawData.score || 0,
pros: rawData.pros || [],
cons: rawData.cons || [],
suggestions: rawData.suggestions || [],
timestamp: Date.now()
};
}
export const poetryService = PoetryGenerationService.getInstance();
游戏状态管理
// GameStateService.ets
import distributedData from ‘@ohos.data.distributedData’;
class GameStateService {
private static instance: GameStateService;
private kvManager: distributedData.KVManager;
private kvStore: distributedData.KVStore;
private constructor() {
this.initKVStore();
private async initKVStore(): Promise<void> {
const config = {
bundleName: 'com.example.poetryGame',
userInfo: { userId: 'currentUser' }
};
this.kvManager = distributedData.createKVManager(config);
this.kvStore = await this.kvManager.getKVStore('game_state', {
createIfMissing: true
});
this.kvStore.on('dataChange', (data) => {
this.handleRemoteUpdate(data);
});
public static getInstance(): GameStateService {
if (!GameStateService.instance) {
GameStateService.instance = new GameStateService();
return GameStateService.instance;
public async createGame(settings: GameSettings): Promise<string> {
const gameId = generateId();
const gameState: GameState = {
id: gameId,
players: [{
id: 'currentUser',
name: settings.playerName,
avatar: settings.avatar,
score: 0
}],
currentLine: settings.initialLine || '床前明月光',
history: [{
line: settings.initialLine || '床前明月光',
player: 'system',
timestamp: Date.now()
}],
status: 'waiting',
createdAt: Date.now(),
settings
};
await this.kvStore.put(game_${gameId}, JSON.stringify(gameState));
return gameId;
public async joinGame(gameId: string, player: PlayerInfo): Promise<void> {
const game = await this.getGame(gameId);
if (!game) throw new Error('Game not found');
if (!game.players.some(p => p.id === player.id)) {
game.players.push({
id: player.id,
name: player.name,
avatar: player.avatar,
score: 0
});
await this.kvStore.put(game_${gameId}, JSON.stringify(game));
}
public async submitLine(gameId: string, playerId: string, line: string): Promise<void> {
const game = await this.getGame(gameId);
if (!game) throw new Error(‘Game not found’);
game.history.push({
line,
player: playerId,
timestamp: Date.now()
});
game.currentLine = line;
// 更新玩家分数
const player = game.players.find(p => p.id === playerId);
if (player) {
player.score += 10; // 基础分
await this.kvStore.put(game_${gameId}, JSON.stringify(game));
public async getGame(gameId: string): Promise<GameState | null> {
const value = await this.kvStore.get(game_${gameId});
return value ? JSON.parse(value) : null;
public async listGames(): Promise<GameState[]> {
const entries = await this.kvStore.getEntries('game_');
return Array.from(entries)
.map(([_, value]) => JSON.parse(value))
.filter(game => game.status === 'waiting');
private handleRemoteUpdate(data: distributedData.ChangeInfo): void {
if (data.deviceId === deviceInfo.deviceId) return;
const key = data.key as string;
if (key.startsWith('game_')) {
const game = JSON.parse(data.value);
EventBus.emit('gameStateUpdated', game);
}
export const gameStateService = GameStateService.getInstance();
玩家服务管理
// PlayerService.ets
import preferences from ‘@ohos.data.preferences’;
class PlayerService {
private static instance: PlayerService;
private constructor() {}
public static getInstance(): PlayerService {
if (!PlayerService.instance) {
PlayerService.instance = new PlayerService();
return PlayerService.instance;
public async getPlayerProfile(): Promise<PlayerProfile> {
const prefs = await preferences.getPreferences('player_profile');
const profile = await prefs.get('profile', '');
return profile ? JSON.parse(profile) : this.getDefaultProfile();
public async updatePlayerProfile(profile: PlayerProfile): Promise<void> {
const prefs = await preferences.getPreferences('player_profile');
await prefs.put('profile', JSON.stringify(profile));
await prefs.flush();
public async getPlayerStats(): Promise<PlayerStats> {
const prefs = await preferences.getPreferences('player_stats');
const stats = await prefs.get('stats', '');
return stats ? JSON.parse(stats) : this.getDefaultStats();
public async updatePlayerStats(stats: PlayerStats): Promise<void> {
const prefs = await preferences.getPreferences('player_stats');
await prefs.put('stats', JSON.stringify(stats));
await prefs.flush();
public async recordGameResult(result: GameResult): Promise<void> {
const stats = await this.getPlayerStats();
stats.totalGames++;
stats.totalScore += result.score;
if (result.won) {
stats.wins++;
else {
stats.losses++;
stats.history.push({
gameId: result.gameId,
score: result.score,
timestamp: Date.now()
});
// 只保留最近50条记录
if (stats.history.length > 50) {
stats.history.shift();
await this.updatePlayerStats(stats);
private getDefaultProfile(): PlayerProfile {
return {
id: generateId(),
name: '新玩家',
avatar: 'default_avatar.png',
level: 1,
preferences: {
theme: 'light',
notification: true
};
private getDefaultStats(): PlayerStats {
return {
totalGames: 0,
wins: 0,
losses: 0,
totalScore: 0,
history: []
};
}
export const playerService = PlayerService.getInstance();
三、主界面实现
游戏大厅界面
// GameLobbyView.ets
@Component
struct GameLobbyView {
@State games: GameState[] = [];
@State playerName: string = ‘’;
@State isCreating: boolean = false;
@State newGameSettings: GameSettings = {
playerName: ‘’,
initialLine: ‘床前明月光’,
timeLimit: 30,
maxPlayers: 4
};
aboutToAppear() {
this.loadPlayerProfile();
this.loadGames();
EventBus.on(‘gameStateUpdated’, () => this.loadGames());
build() {
Column() {
Text('古诗接龙')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 16 })
if (this.playerName) {
Text(欢迎, ${this.playerName})
.fontSize(16)
.margin({ top: 8 })
Row() {
Button('创建房间')
.onClick(() => this.isCreating = true)
.margin({ right: 16 })
Button('刷新列表')
.onClick(() => this.loadGames())
.margin({ top: 16 })
if (this.isCreating) {
NewGameDialog({
settings: this.newGameSettings,
onCreate: (settings) => this.createGame(settings),
onCancel: () => this.isCreating = false
})
if (this.games.length === 0) {
Text('暂无游戏房间')
.fontSize(16)
.margin({ top: 32 })
else {
List({ space: 10 }) {
ForEach(this.games, (game) => {
ListItem() {
GameItem({ game })
.onClick(() => this.joinGame(game.id))
})
.layoutWeight(1)
}
.padding(16)
private async loadPlayerProfile(): Promise<void> {
const profile = await playerService.getPlayerProfile();
this.playerName = profile.name;
this.newGameSettings.playerName = profile.name;
private async loadGames(): Promise<void> {
this.games = await gameStateService.listGames();
private async createGame(settings: GameSettings): Promise<void> {
const gameId = await gameStateService.createGame(settings);
router.push({ url: pages/game?gameId=${gameId} });
this.isCreating = false;
private async joinGame(gameId: string): Promise<void> {
const profile = await playerService.getPlayerProfile();
await gameStateService.joinGame(gameId, {
id: profile.id,
name: profile.name,
avatar: profile.avatar
});
router.push({ url: pages/game?gameId=${gameId} });
}
@Component
struct GameItem {
private game: GameState;
build() {
Row() {
Column() {
Text(房间: ${game.id.substring(0, 6)})
.fontSize(18)
Text(玩家: {game.players.length}/{game.settings.maxPlayers})
.fontSize(14)
.fontColor('#666666')
.margin({ top: 4 })
.layoutWeight(1)
Column() {
Text(game.settings.initialLine)
.fontSize(16)
.fontStyle(FontStyle.Italic)
Text(${game.settings.timeLimit}秒/回合)
.fontSize(12)
.fontColor('#666666')
.margin({ top: 4 })
}
.padding(12)
}
@Component
struct NewGameDialog {
private settings: GameSettings;
private onCreate: (settings: GameSettings) => void;
private onCancel: () => void;
build() {
Column() {
Text(‘创建新游戏’)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 16 })
TextInput({ placeholder: '起始诗句', text: this.settings.initialLine })
.onChange((value: string) => this.settings.initialLine = value)
.margin({ bottom: 8 })
Row() {
Text('时间限制(秒):')
.fontSize(16)
.margin({ right: 8 })
Slider({
value: this.settings.timeLimit,
min: 10,
max: 60,
step: 5,
style: SliderStyle.SLIDER_OUTSET
})
.onChange((value: number) => this.settings.timeLimit = value)
.layoutWeight(1)
Text(this.settings.timeLimit.toString())
.fontSize(16)
.margin({ left: 8 })
.margin({ bottom: 8 })
Row() {
Text('最大玩家数:')
.fontSize(16)
.margin({ right: 8 })
Picker({ range: [2, 3, 4, 5, 6], selected: this.settings.maxPlayers - 2 })
.onChange((index: number) => this.settings.maxPlayers = index + 2)
.margin({ bottom: 16 })
Row() {
Button('取消')
.onClick(() => this.onCancel())
.layoutWeight(1)
Button('创建')
.onClick(() => this.onCreate(this.settings))
.layoutWeight(1)
.margin({ left: 16 })
}
.padding(16)
.backgroundColor('#FFFFFF')
.borderRadius(8)
.shadow({ radius: 4, color: '#00000020' })
}
游戏主界面
// GameView.ets
@Component
struct GameView {
@State gameId: string = ‘’;
@State game: GameState | null = null;
@State playerInput: string = ‘’;
@State isSubmitting: boolean = false;
@State countdown: number = 0;
@State timer: number | null = null;
@State currentPlayer: Player | null = null;
onInit() {
this.gameId = router.getParams()?.gameId || ‘’;
aboutToAppear() {
this.loadGame();
EventBus.on('gameStateUpdated', (game) => {
if (game.id === this.gameId) {
this.game = game;
this.startTurnTimer();
});
build() {
Column() {
if (!this.game) {
LoadingProgress()
.width(50)
.height(50)
.margin({ top: 32 })
else {
// 游戏信息
Row() {
Text(房间: ${this.game.id.substring(0, 6)})
.fontSize(16)
Text(回合: ${this.game.history.length})
.fontSize(16)
.margin({ left: 16 })
.margin({ top: 16 })
// 玩家列表
PlayerListView({ players: this.game.players })
.margin({ top: 16 })
// 当前诗句
Text(this.game.currentLine)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.textAlign(TextAlign.Center)
.margin({ top: 32 })
// 倒计时
if (this.countdown > 0 && this.isCurrentPlayer()) {
Text(${this.countdown}秒)
.fontSize(18)
.fontColor('#F44336')
.margin({ top: 8 })
// 历史记录
Scroll() {
Column() {
ForEach(this.game.history.slice().reverse(), (entry, index) => {
HistoryItem({ entry, isLatest: index === 0 })
.margin({ top: index === 0 ? 0 : 8 })
})
.padding(8)
.height(150)
.margin({ top: 16 })
// 输入框
if (this.isCurrentPlayer()) {
Column() {
TextInput({ placeholder: '输入下一句...', text: this.playerInput })
.onChange((value: string) => this.playerInput = value)
.margin({ top: 16 })
Button('提交')
.onClick(() => this.submitLine())
.margin({ top: 8 })
.enabled(this.playerInput.length > 0 && !this.isSubmitting)
} else {
Text('等待其他玩家...')
.fontSize(16)
.margin({ top: 32 })
}
.padding(16)
private async loadGame(): Promise<void> {
this.game = await gameStateService.getGame(this.gameId);
if (this.game) {
this.startTurnTimer();
}
private startTurnTimer(): void {
if (this.timer) {
clearInterval(this.timer);
if (this.isCurrentPlayer()) {
this.countdown = this.game?.settings.timeLimit || 30;
this.timer = setInterval(() => {
this.countdown--;
if (this.countdown <= 0) {
clearInterval(this.timer!);
this.timeout();
}, 1000);
}
private isCurrentPlayer(): boolean {
if (!this.game || !this.game.players.length) return false;
const profile = playerService.getPlayerProfile();
const lastEntry = this.game.history[this.game.history.length - 1];
return lastEntry.player !== profile.id;
private async submitLine(): Promise<void> {
if (!this.game || !this.playerInput) return;
this.isSubmitting = true;
try {
const profile = await playerService.getPlayerProfile();
await gameStateService.submitLine(this.game.id, profile.id, this.playerInput);
this.playerInput = '';
finally {
this.isSubmitting = false;
}
private timeout(): void {
// 超时处理逻辑
if (!this.game) return;
const profile = playerService.getPlayerProfile();
const randomLine = this.getRandomLine();
gameStateService.submitLine(this.game.id, profile.id, randomLine);
private getRandomLine(): string {
const lines = [
'举头望明月',
'低头思故乡',
'春风又绿江南岸',
'明月何时照我还',
'白日依山尽',
'黄河入海流'
];
return lines[Math.floor(Math.random() * lines.length)];
}
@Component
struct PlayerListView {
private players: Player[];
build() {
Scroll({ scrollable: ScrollDirection.Horizontal }) {
Row() {
ForEach(this.players, (player) => {
Column() {
Image(player.avatar)
.width(40)
.height(40)
.borderRadius(20)
Text(player.name)
.fontSize(14)
.margin({ top: 4 })
Text(${player.score}分)
.fontSize(12)
.fontColor('#4CAF50')
.margin({ top: 2 })
.margin({ right: 12 })
})
.padding(8)
}
@Component
struct HistoryItem {
private entry: HistoryEntry;
private isLatest: boolean;
build() {
Row() {
if (this.entry.player === ‘system’) {
Text(‘系统’)
.fontSize(12)
.fontColor(‘#666666’)
.width(40)
else {
Image(this.getPlayerAvatar(this.entry.player))
.width(24)
.height(24)
.borderRadius(12)
.margin({ right: 8 })
Text(this.entry.line)
.fontSize(this.isLatest ? 18 : 16)
.fontWeight(this.isLatest ? FontWeight.Bold : FontWeight.Normal)
.fontColor(this.isLatest ? '#000000' : '#666666')
.layoutWeight(1)
.padding(8)
.backgroundColor(this.isLatest ? '#FFF9C4' : 'transparent')
.borderRadius(4)
private getPlayerAvatar(playerId: string): string {
// 简化实现,实际应从玩家服务获取
return 'default_avatar.png';
}
游戏结果界面
// GameResultView.ets
@Component
struct GameResultView {
@State gameId: string = ‘’;
@State game: GameState | null = null;
@State playerStats: PlayerStats | null = null;
onInit() {
this.gameId = router.getParams()?.gameId || ‘’;
aboutToAppear() {
this.loadGame();
this.loadPlayerStats();
build() {
Column() {
if (!this.game || !this.playerStats) {
LoadingProgress()
.width(50)
.height(50)
.margin({ top: 32 })
else {
Text('游戏结束')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 16 })
// 获胜者
const winner = this.getWinner();
Text(获胜者: ${winner.name})
.fontSize(20)
.fontColor('#4CAF50')
.margin({ top: 16 })
// 玩家排名
List({ space: 10 }) {
ForEach(this.getRankedPlayers(), (player, index) => {
ListItem() {
PlayerRankItem({ player, rank: index + 1 })
})
.margin({ top: 16 })
.layoutWeight(1)
// 游戏历史
Text('游戏记录')
.fontSize(18)
.fontWeight(FontWeight.Bold)
.margin({ top: 16 })
Scroll() {
Column() {
ForEach(this.game.history, (entry) => {
HistoryItem({ entry })
.margin({ top: 8 })
})
.padding(8)
.height(200)
.margin({ top: 8 })
// 操作按钮
Button('返回大厅')
.onClick(() => router.back())
.margin({ top: 16 })
}
.padding(16)
private async loadGame(): Promise<void> {
this.game = await gameStateService.getGame(this.gameId);
private async loadPlayerStats(): Promise<void> {
this.playerStats = await playerService.getPlayerStats();
private getWinner(): Player {
if (!this.game) return { id: '', name: '未知', avatar: '', score: 0 };
return this.game.players.reduce((prev, current) =>
current.score > prev.score ? current : prev
);
private getRankedPlayers(): Player[] {
if (!this.game) return [];
return [...this.game.players].sort((a, b) => b.score - a.score);
private async recordResult(): Promise<void> {
if (!this.game) return;
const profile = await playerService.getPlayerProfile();
const player = this.game.players.find(p => p.id === profile.id);
if (player) {
const winner = this.getWinner();
await playerService.recordGameResult({
gameId: this.game.id,
score: player.score,
won: winner.id === profile.id,
timestamp: Date.now()
});
}
@Component
struct PlayerRankItem {
private player: Player;
private rank: number;
build() {
Row() {
Text(this.rank.toString())
.fontSize(18)
.fontWeight(FontWeight.Bold)
.width(30)
Image(this.player.avatar)
.width(40)
.height(40)
.borderRadius(20)
.margin({ left: 8 })
Column() {
Text(this.player.name)
.fontSize(16)
Text(${this.player.score}分)
.fontSize(14)
.fontColor('#666666')
.margin({ top: 4 })
.margin({ left: 8 })
.layoutWeight(1)
if (this.rank === 1) {
Image('gold_medal.png')
.width(30)
.height(30)
else if (this.rank === 2) {
Image('silver_medal.png')
.width(30)
.height(30)
else if (this.rank === 3) {
Image('bronze_medal.png')
.width(30)
.height(30)
}
.padding(12)
}
四、高级功能实现
多设备游戏同步
// GameSyncService.ets
import deviceManager from ‘@ohos.distributedHardware.deviceManager’;
class GameSyncService {
private static instance: GameSyncService;
private constructor() {}
public static getInstance(): GameSyncService {
if (!GameSyncService.instance) {
GameSyncService.instance = new GameSyncService();
return GameSyncService.instance;
public async invitePlayerToGame(deviceId: string, gameId: string): Promise<void> {
const ability = await featureAbility.startAbility({
bundleName: 'com.example.poetryGame',
abilityName: 'GameInvitationAbility',
deviceId
});
await ability.call({
method: 'receiveGameInvitation',
parameters: [gameId]
});
public async syncGameStateToDevice(deviceId: string, game: GameState): Promise<void> {
const ability = await featureAbility.startAbility({
bundleName: 'com.example.poetryGame',
abilityName: 'GameStateSyncAbility',
deviceId
});
await ability.call({
method: 'receiveGameState',
parameters: [game]
});
public async broadcastGameUpdate(game: GameState): Promise<void> {
const devices = await deviceManager.getTrustedDevices();
await Promise.all(devices.map(device =>
this.syncGameStateToDevice(device.id, game)
));
public async syncPlayerMove(deviceId: string, move: PlayerMove): Promise<void> {
const ability = await featureAbility.startAbility({
bundleName: 'com.example.poetryGame',
abilityName: 'PlayerMoveAbility',
deviceId
});
await ability.call({
method: 'receivePlayerMove',
parameters: [move]
});
}
export const gameSyncService = GameSyncService.getInstance();
AI辅助模式
// AIAssistantService.ets
class AIAssistantService {
private static instance: AIAssistantService;
private constructor() {}
public static getInstance(): AIAssistantService {
if (!AIAssistantService.instance) {
AIAssistantService.instance = new AIAssistantService();
return AIAssistantService.instance;
public async getHint(currentLine: string, difficulty: number = 1): Promise<string[]> {
const response = await poetryService.generateNextLine(currentLine);
const lines: string[] = [];
// 根据难度级别提供不同提示
if (difficulty >= 3) {
lines.push(response.text);
else if (difficulty >= 2) {
lines.push(response.text.substring(0, response.text.length / 2) + '...');
else {
lines.push(尝试使用 ${response.pinyin} 押韵);
lines.push(主题: ${response.meaning});
return lines;
public async evaluatePlayerLine(line: string, context: string): Promise<EvaluationResult> {
const evaluation = await poetryService.evaluatePoetry(line, context);
return {
score: evaluation.score,
feedback: [
...evaluation.pros.map(pro => 优点: ${pro}),
...evaluation.cons.map(con => 改进: ${con}),
...evaluation.suggestions.map(sug => 建议: ${sug})
};
public async generateChallenge(level: number): Promise<PoetryChallenge> {
const challenges: PoetryChallenge[] = [
id: ‘challenge1’,
description: '完成这首五言绝句',
initialLines: ['白日依山尽', '黄河入海流'],
targetRhyme: 'ou',
timeLimit: 60
},
id: ‘challenge2’,
description: '以"春"为主题创作一句诗',
initialLines: [],
targetTheme: 'spring',
timeLimit: 45
},
id: ‘challenge3’,
description: '接龙这句七言诗',
initialLines: ['两个黄鹂鸣翠柳'],
targetStyle: '七言',
timeLimit: 30
];
return challenges[level % challenges.length];
}
export const aiAssistantService = AIAssistantService.getInstance();
学习模式服务
// LearningService.ets
import http from ‘@ohos.net.http’;
class LearningService {
private static instance: LearningService;
private httpClient: http.HttpRequest;
private apiKey = ‘YOUR_LEARNING_API_KEY’;
private constructor() {
this.httpClient = http.createHttp();
public static getInstance(): LearningService {
if (!LearningService.instance) {
LearningService.instance = new LearningService();
return LearningService.instance;
public async getPoemAnalysis(poemId: string): Promise<PoemAnalysis> {
return new Promise((resolve, reject) => {
this.httpClient.request(
https://poetry-api.example.com/poems/${poemId},
method: ‘GET’,
header: { 'X-API-Key': this.apiKey }
},
(err, data) => {
if (err) {
reject(err);
else {
const result = JSON.parse(data.result);
resolve(this.processAnalysisResult(result));
}
);
});
private processAnalysisResult(rawData: any): PoemAnalysis {
return {
id: rawData.id,
title: rawData.title,
author: rawData.author,
dynasty: rawData.dynasty,
content: rawData.content,
translation: rawData.translation,
explanation: rawData.explanation,
appreciation: rawData.appreciation,
tags: rawData.tags || []
};
public async searchPoems(query: string): Promise<PoemBrief[]> {
return new Promise((resolve, reject) => {
this.httpClient.request(
'https://poetry-api.example.com/search',
method: ‘POST’,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify({
query,
api_key: this.apiKey
})
},
(err, data) => {
if (err) {
reject(err);
else {
const result = JSON.parse(data.result);
resolve(this.processSearchResult(result));
}
);
});
private processSearchResult(rawData: any): PoemBrief[] {
if (!rawData || !rawData.poems) return [];
return rawData.poems.map((poem: any) => ({
id: poem.id,
title: poem.title,
author: poem.author,
dynasty: poem.dynasty,
excerpt: poem.excerpt,
matchScore: poem.matchScore
}));
public async getRandomPoem(): Promise<PoemBrief> {
return new Promise((resolve, reject) => {
this.httpClient.request(
'https://poetry-api.example.com/random',
method: ‘GET’,
header: { 'X-API-Key': this.apiKey }
},
(err, data) => {
if (err) {
reject(err);
else {
const result = JSON.parse(data.result);
resolve(this.processPoemBrief(result));
}
);
});
private processPoemBrief(rawData: any): PoemBrief {
return {
id: rawData.id,
title: rawData.title,
author: rawData.author,
dynasty: rawData.dynasty,
excerpt: rawData.excerpt || rawData.content.substring(0, 20) + '...'
};
public async getPoemsByAuthor(author: string): Promise<PoemBrief[]> {
return new Promise((resolve, reject) => {
this.httpClient.request(
https://poetry-api.example.com/authors/${encodeURIComponent(author)},
method: ‘GET’,
header: { 'X-API-Key': this.apiKey }
},
(err, data) => {
if (err) {
reject(err);
else {
const result = JSON.parse(data.result);
resolve(this.processAuthorPoems(result));
}
);
});
private processAuthorPoems(rawData: any): PoemBrief[] {
if (!rawData || !rawData.poems) return [];
return rawData.poems.map(this.processPoemBrief);
}
export const learningService = LearningService.getInstance();
五、总结
本古诗接龙游戏实现了以下核心价值:
文化传承:通过游戏形式传播中国古典诗词文化
智能生成:AI辅助生成符合格律的诗句
多人互动:支持多玩家实时对战
学习功能:提供诗词学习和赏析功能
跨设备体验:无缝切换不同设备继续游戏
扩展方向:
增加更多诗词风格和朝代
开发诗词创作社区
集成语音识别和朗读功能
增加AR诗词展示功能
注意事项:
需要网络连接以使用AI生成功能
诗句生成质量受模型训练数据影响
多设备游戏需保持网络连接
首次使用建议完成教程
部分高级功能可能需要订阅服务
