一、准备工作
1. 安装微信开发者工具,并登录微信小程序账号;
2. 准备斗地主游戏的图片资源;
3. 准备斗地主游戏的音效资源;
二、创建小程序
1. 打开微信开发者工具,点击“新建小程序”,输入小程序名称,选择小程序的项目目录,点击“创建”;
2. 在小程序的项目目录中,新建文件夹“images”,将准备好的斗地主游戏的图片资源放入“images”文件夹中;
3. 在小程序的项目目录中,新建文件夹“sounds”,将准备好的斗地主游戏的音效资源放入“sounds”文件夹中;
三、编写代码
1. 在小程序的项目目录中,新建文件“game.js”,编写斗地主游戏的逻辑代码;
// game.js
// 定义游戏状态
const GAME_STATE = {
WAITING: 0,// 等待状态
PLAYING: 1,// 游戏中状态
END: 2 // 游戏结束状态
};
// 定义游戏类
class Game {
constructor() {
this.state = GAME_STATE.WAITING; // 初始化游戏状态
this.players = []; // 玩家列表
this.cards = []; // 扑克牌
this.landlordCards = []; // 地主牌
}
// 开始游戏
start() {
// 初始化游戏状态
this.state = GAME_STATE.PLAYING;
// 初始化玩家
this.players = [
new Player('张三'),
new Player('李四'),
new Player('王五')
];
// 初始化扑克牌
this.cards = this.initCards();
// 发牌
this.dealCards();
// 叫地主
this.callLandlord();
// 发地主牌
this.dealLandlordCards();
// 开始游戏
this.play();
}
// 初始化扑克牌
initCards() {
let cards = [];
// 生成54张扑克牌
for (let i = 0; i < 54; i++) {
cards.push(new Card(i));
}
// 打乱牌顺序
cards.sort(() => Math.random() - 0.5);
return cards;
}
// 发牌
dealCards() {
// 每人发17张牌
for (let i = 0; i < 17; i++) {
for (let j = 0; j < 3; j++) {
this.players[j].cards.push(this.cards.pop());
}
}
}
// 叫地主
callLandlord() {
// 玩家叫地主
for (let i = 0; i < 3; i++) {
let player = this.players[i];
let isCall = player.callLandlord();
if (isCall) {
// 叫地主成功,设置地主
this.landlord = player;
break;
}
}
}
// 发地主牌
dealLandlordCards() {
// 将剩余的牌发给地主
this.landlord.cards = this.landlord.cards.concat(this.cards);
// 将地主牌排序
this.landlord.cards.sort((a,b) => a.value - b.value);
// 记录地主牌
this.landlordCards = this.landlord.cards;
}
// 开始游戏
play() {
// 玩家出牌
for (let i = 0; i < 3; i++) {
let player = this.players[i];
let card = player.play();
console.log(`${player.name}出牌:${card.name}`);
}
// 游戏结束
this.state = GAME_STATE.END;
}
}
// 定义玩家类
class Player {
constructor(name) {
this.name = name; // 玩家名称
this.cards = []; // 玩家手牌
}
// 叫地主
callLandlord() {
// 随机叫地主
let isCall = Math.random() > 0.5;
console.log(`${this.name}${isCall ? '叫' : '不叫'}地主`);
return isCall;
}
// 出牌
play() {
// 随机出牌
let card = this.cards[Math.floor(Math.random() * this.cards.length)];
// 从手牌中移除出的牌
this.cards.splice(this.cards.indexOf(card),1);
return card;
}
}
// 定义扑克牌类
class Card {
constructor(id) {
this.id = id; // 牌的id
this.name = this.getNameById(id); // 牌的名称
this.value = this.getValueById(id); // 牌的大小
}
// 根据id获取牌的名称
getNameById(id) {
let type = Math.floor(id / 13);
let number = id %!;(MISSING)
let types = ['黑桃','红桃','梅花','方块'];
let numbers = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
原文地址:https://blog.csdn.net/weixin_54226053/article/details/129067879
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。