赞
踩
两个人比较大小的小游戏
- // 扑克牌小游戏
-
- enum SUIT {'黑桃','红桃','梅花','方块','王'}
- enum RANK {R2,R3,R4,R5,R6,R7,R8,R9,R10,RJ,RQ,RK,RA,R小,R大}
-
- // 声明一个类型, 描述一张扑克牌的信息
- class Card{
- suit:SUIT;
- rank:RANK;
- constructor(suit:SUIT, rank:RANK){
- this.suit =suit;
- this.rank =rank;
- }
- toString(){
- return SUIT[this.suit] + RANK[this.rank];
- }
- }
-
- // 声明一个类型, 描述一张扑克牌的信息
- let c1 = new Card(SUIT.黑桃, RANK.RA) //创建一张黑桃A
- console.log(c1.toString())
- let c2 = new Card(SUIT.王, RANK.R大) //大王
- console.log(c2.toString())
-
- // 通过循环, 创建52张牌
- let cards: Card[] =[]
- for(let suit = SUIT.黑桃; suit <= SUIT.方块; suit++){
- for(let rank = RANK.R2; rank<=RANK.RA; rank++){
- cards.push(new Card(suit, rank))
- }
- }
- cards.push(new Card(SUIT.王, RANK.R小))
- cards.push(new Card(SUIT.王, RANK.R大))
- console.log('牌:',cards.toString())
-
- // 将54张牌分配给2个玩家, 设计一个玩家类, 继续后续的游戏流程
- class Player{
- name:string;
- score:number;
- handCards: Card[];
- constructor(name:string){ // 构造函数用于 属性数据初始化
- this.name = name;
- this.score = 0;
- this.handCards = []
- }
- /**
- * 当前玩家从牌堆中随机抽一张牌. 最终牌堆会少一张, 玩家手牌会多一张
- * @param cards 牌堆 Card[]
- */
- choupai(cards:Card[]):void {
- let randomIndex = Math.floor(Math.random()*cards.length)
- let deletedCard = cards.splice(randomIndex, 1)[0]
- this.handCards.push(deletedCard)
- }
-
- // 返回一个字符串, 描述当前玩家对象的信息
- toString(){
- return `
- 姓名:${this.name},
- 得分:${this.score},
- 手牌:${this.handCards.toString()}
- `
- }
-
- /**
- * 与另外一个玩家: other 比较手中所有牌的大小, 且计分
- * @param other 另外一个玩家对象
- */
- pk(other:Player){
- for(let i = 0; i<this.handCards.length; i++){
- let myCard = this.handCards[i] //我的牌
- let otherCard = other.handCards[i] //对手的牌
- if(myCard.rank>otherCard.rank){
- this.score++ //我得分
- }else if(myCard.rank<otherCard.rank){
- other.score++ //对手得分
- }
- }
- }
- }
- let ming = new Player('小明')
- let hong = new Player('小红')
-
- // 不断抽牌, 抽到没牌为止
- while(cards.length != 0){
- ming.choupai(cards)
- hong.choupai(cards)
- }
-
-
- // 不断的按顺序比较俩人手牌大小, 大的得1分
- ming.pk(hong)
- console.log(ming.toString())
- console.log(hong.toString())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。