import { Context, Random, Schema } from 'koishi'
export const name = 'who-is-baka'
export interface Config {
}
interface MyUser {
id: string;
nickname: string;
}
export const Config: Schema = Schema.object({})
export function apply(ctx: Context) {
// write your plugin here
const games = {};
class UndercoverGame {
channelId: any;
players: any[];
undercoverIndex: number;
word: string[];
votes: {};
voteCount: number;
started: boolean;
undercoverGuessed: boolean; // 新增属性,用来跟踪卧底是否已猜过词语
constructor(channelId) {
this.channelId = channelId;
this.players = [];
this.undercoverIndex = -1;
this.word = ['马桶', '卧底', '撤硕', '你好', '小猫牢底'];
this.votes = {};
this.voteCount = 0;
this.started = false;
this.undercoverGuessed = false; // 初始时卧底尚未猜过词语
}
async sendPrivateMessage(userId, message) {
await ctx.bots.sender.sendPrivateMessage(userId, message);
}
voteOut(session, voterUserId, voteTargetName) {
const voterIndex = this.players.findIndex(player => player.userId === voterUserId);
if (voterIndex === -1 || this.players[voterIndex].voted) {
return { success: false, message: '你未找到或已经投票。' }; // 玩家未找到或已经投票
}
// 查找被投票玩家的索引,可以通过昵称或 userId
const targetIndex = this.players.findIndex(player => {
// 首先尝试通过 userId 匹配
if (player.userId === voteTargetName) {
return true;
}
// 如果不是 userId,尝试通过昵称匹配
const member = session.guild?.members.get(player.userId);
return member?.nickname === voteTargetName || member?.username === voteTargetName;
});
if (targetIndex === -1) {
return { success: false, message: '投票对象不在游戏中,请重新投票。' }; // 被投票的玩家不在游戏中
}
this.votes[voterUserId] = this.players[targetIndex].userId;
this.players[voterIndex].voted = true;
this.voteCount++;
// 检查是否所有玩家都已投票
if (this.voteCount === this.players.length) {
// 所有玩家都已投票,进行计票
const finalResult = this.checkVotes();
return { success: true, finalResult };
}
return { success: true, message: '投票成功,等待其他玩家投票。' };
}
undercoverGuess(userId: any, guessWord: string) {
if (!this.started) {
return '游戏还没有开始!';
}
if (userId !== this.players[this.undercoverIndex].userId) {
return '只有卧底可以猜测词语!';
}
if (this.undercoverGuessed) {
return '卧底已经猜过一次,不能再猜了!';
}
// 设置卧底已经猜过词语
this.undercoverGuessed = true;
// 检查卧底的猜测是否正确
if (guessWord === this.word[1]) {
this.started = false;
return '卧底猜中词语,卧底获胜!';
} else {
this.started = false;
return '卧底猜错了,其他玩家获胜!';
}
}
addPlayer(userId: any) {
if (this.started || this.players.length >= 4) return false;
this.players.push({ userId, voted: false });
return true;
}
async startGame() {
if (this.players.length !== 4) return false;
this.started = true;
// 使用预设词组中的某个词作为游戏词汇
const secretWord = Random.pick(this.word);
this.undercoverIndex = Random.int(0, this.players.length - 1);
for (const [index, player] of this.players.entries()) {
// 卧底玩家不发送词汇
const wordToSend = index === this.undercoverIndex ? '' : secretWord;
// 使用 ctx.bots[0] 作为示例,实际中你可能需要选择正确的 bot
await ctx.bots[0].sendPrivateMessage(player.userId, `你的词语是: ${wordToSend}`);
}
return true;
}
castVote(voterId, voteId) {
if (!this.started || this.votes[voterId] || this.voteCount >= 2) return false;
this.votes[voterId] = voteId;
this.voteCount++;
return true;
}
checkVotes() {
const votes = Object.values(this.votes) as string[];
if (votes.length < 3) return null;
// 计算票数
const voteResult = votes.reduce((acc: Record<string, number>, vote: string) => (acc[vote] = (acc[vote] || 0) + 1, acc), {});
// 计算每位玩家的票数
const voteCounts = Object.values(this.votes).reduce((acc: Record<string, number>, vote: string) => {
acc[vote] = (acc[vote] || 0) + 1;
return acc;
}, {} as Record<string, number>);
// 找到得票最多的玩家和票数
let maxVotes = 0;
let votedOutUserId = null;
for (const [userId, count] of Object.entries(voteCounts)) {
if (count > maxVotes) {
maxVotes = count;
votedOutUserId = userId;
}
}
// 如果没有玩家得到超过一半以上的票数,则不能宣布结果
if (maxVotes <= Math.floor(this.players.length / 2)) {
return '票数不足以决定卧底,游戏继续。';
}
// 检查被投票出去的玩家是否是卧底
const isUndercoverVotedOut = this.players[this.undercoverIndex].userId === votedOutUserId;
this.started = false; // 结束游戏
if (isUndercoverVotedOut) {
return '卧底被投票踢出,其他玩家获胜!';
} else {
return '卧底未被踢出,卧底获胜!';
}
}
}
ctx.command('undercover', '开始《谁是卧底》游戏')
.channelFields(['id'])
.action(async ({ session }) => {
const channelId = session.channelId;
if (!games[channelId]) {
games[channelId] = new UndercoverGame(channelId);
}
const game = games[channelId];
if (game.started) return '游戏已经开始了!';
const success = await game.startGame(); // 不再传递 words 参数
if (!success) return '需要四位玩家才能开始游戏!';
return '游戏开始!';
});
ctx.command('undercover.join', '加入《谁是卧底》游戏')
.channelFields(['id'])
.action(async ({ session }) => {
const channelId = session.channelId;
if (!games[channelId]) {
games[channelId] = new UndercoverGame(channelId);
}
const game = games[channelId];
const success = game.addPlayer(session.userId);
if (!success) return '无法加入游戏,可能是因为游戏已经开始,或者玩家人数已满。';
return 玩家 ${session.username} 加入游戏成功,当前人数:${game.players.length}/4;
});
ctx.command('undercover.vote ', '投票踢出卧底')
.channelFields(['id'])
.userFields(['id'])
.action(async ({ session }, playerName) => {
const channelId = session.channelId;
if (!games[channelId]) {
return '游戏尚未开始!';
}
const game = games[channelId];
const voteResult = game.voteOut(session, session.userId, playerName);
// 如果 voteOut 返回字符串,则表示有投票结果,发送相应的消息
if (typeof voteResult === 'string') {
return voteResult;
}
return '投票已记录,等待其他玩家投票。';
});
ctx.command('undercover.guess ', '卧底猜测其他玩家的词语')
.channelFields(['id'])
.action(async ({ session }, word) => {
const channelId = session.channelId;
if (!games[channelId]) {
return '游戏尚未开始!';
}
const game = games[channelId];
const result = game.undercoverGuess(session.userId, word);
return result;
});
ctx.middleware(async (session, next) => {
await next();
const channelId = session.channelId;
const game = games[channelId];
if (!game || !game.started) return;
const result = game.checkVotes();
if (result === null) {
return; // 等待其他玩家投票
} else if (result) {
// 卧底被投票踢出,其他玩家获胜
await session.send('卧底被投票踢出,其他玩家获胜!');
} else {
// 投票未成功,继续游戏
await session.send('投票未成功,继续游戏。');
}
// 游戏结束,清理游戏状态
delete games[channelId];
})
try {
// your code here
} catch (error) {
console.error(error);
}
}
任意一方胜利时即为游戏结束,返回胜利方,重置插件