包含了TS的一些常见用法
目录结构
... /src
......./index.ts
......./deck.ts
......./enums.ts
......./type.d.ts
enums.ts
export enum Color {
heart = "♥",
spade = "♠",
club = "♣",
diamond = "♦",
}
export enum Mark {
A = "A",
two = "2",
three = "3",
four = "4",
five = "5",
six = "6",
seven = "7",
eight = "8",
nine = "9",
ten = "10",
eleven = "J",
twelve = "Q",
king = "K",
}
type.d.ts
import { Color, Mark } from "./enums";
export interface Card {
color: Color;
mark: Mark;
getString(): string;
}
export interface Joker {
type: "big" | "small";
getString(): string;
}
export interface PublishResult {
player1: Deck;
player2: Deck;
player3: Deck;
left: Deck;
}
deck.ts
import { Mark, Color } from "./enums";
import { Card, PublishResult } from "./type";
export class Deck {
private cards: Card[] = [];
constructor(cards?: Card[]) {
if (cards) {
this.cards = cards;
} else {
this.init();
}
}
private init() {
for (const mark of Object.values(Mark)) {
for (const color of Object.values(Color)) {
const card = {
color,
mark,
getString() {
return this.color + this.mark;
},
};
this.cards.push(card);
}
}
let joker: Card = {
color: Color.heart,
mark: "jo" as Mark,
getString() {
return "jo";
},
};
this.cards.push(joker);
joker = {
color: Color.heart,
mark: "JO" as Mark,
getString() {
return "JO";
},
};
this.cards.push(joker);
}
print() {
let result = "\n";
this.cards.forEach((card, i) => {
result += card.getString() + "\t";
if ((i + 1) % 6 === 0) {
result += "\n";
}
});
console.log(result);
}
public shuffle() {
this.cards.sort(() => Math.random() - 0.6);
}
private takeCards(num: number = 17): Deck {
const cards = this.cards.splice(0, num);
return new Deck(cards);
}
public publish(): PublishResult {
const player1 = this.takeCards();
const player2 = this.takeCards();
const player3 = this.takeCards();
const left = this.takeCards();
return {
player1,
player2,
player3,
left,
};
}
}
index.ts
import { Deck } from "./deck";
const deck = new Deck();
deck.shuffle();
console.log("=========洗牌之后======= ");
deck.print();
const result = deck.publish();
console.log("===========玩家1========");
result.player1.print();
console.log("===========玩家2========");
result.player2.print();
console.log("===========玩家3========");
result.player3.print();
console.log("===========底牌========");
result.left.print();
package.json
{
"name": "demo001",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {},
"devDependencies": {
"@types/node": "^20.5.9"
},
"scripts": {
"dev": "nodemon --watch src -e ts --exec ts-node src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC"
}
tsconfig.json
{
"compilerOptions": {
"target": "ES2016" ,
"module": "commonjs" ,
"lib": ["ES2016"] ,
"outDir": "./dist" ,
"strictNullChecks": true,
"removeComments": true,
"esModuleInterop": true,
"noEmitOnError": true,
"moduleResolution": "node",
"strictPropertyInitialization": true
},
"include": ["./src"]
}