32
Une carte à jouer
- import { defclass, sendmsg, supersend } from 'So-o';
- defclass('Card', null, 1,
- null,
- ['rank', 'suit'],
- null,
La classe Card ajoute les propriétés d'instance rank et suit, redéfinit les messages d'instance init et toString, ajoute les messages d'instance rank, suit et compare.
- { 'init':
- (self, rank, suit) => {
- sendmsg(self, 'set', 'rank', rank);
- sendmsg(self, 'set', 'suit', suit);
- return self;
- },
- 'rank':
- (self) => sendmsg(self, 'get', 'rank'),
- 'suit':
- (self) => sendmsg(self, 'get', 'suit'),
- 'compare':
- (self, card) => {
- let rank1 = sendmsg(self, 'get', 'rank');
- let rank2 = sendmsg(card, 'get', 'rank');
- return rank1 == rank2 ? 0 : rank1 > rank2 ? 1 : -1;
- },
- 'toString':
- (self) => Card.rank2s[sendmsg(self, 'get', 'rank')] + Card.suit2s[sendmsg(self, 'get', 'suit')]
- }
- );
- Card.TWO = 0;
- Card.THREE = 1;
- Card.FOUR = 2;
- Card.FIVE = 3;
- Card.SIX = 4;
- Card.SEVEN = 5;
- Card.EIGHT = 6;
- Card.NINE = 7;
- Card.TEN = 8;
- Card.JACK = 9;
- Card.QUEEN = 10;
- Card.KING = 11;
- Card.ACE = 12;
- Card.CLUBS = 0;
- Card.DIAMONDS = 1;
- Card.HEARTS = 2;
- Card.SPADES = 3;
- Card.rank2s = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'];
- Card.suit2s = ['c', 'd', 'h', 's'];
- import { sendmsg } from 'So-o';
- import 'Card';
- let card_2c = sendmsg(Card, 'new', Card.TWO, Card.CLUBS);
- let card_Td = sendmsg(Card, 'new', Card.TEN, Card.DIAMONDS);
- let card_Kh = sendmsg(Card, 'new', Card.KING, Card.HEARTS);
- let card_As = sendmsg(Card, 'new', Card.ACE, Card.SPADES);
- console.log('2c -> ' + sendmsg(card_2c, 'toString') + ' (two of clubs)');
- console.log('Td -> ' + sendmsg(card_Td, 'toString') + ' (ten of diamonds)');
- console.log('Kh -> ' + sendmsg(card_Kh, 'toString') + ' (king of hearts)');
- console.log('As -> ' + sendmsg(card_As, 'toString') + ' (ace of spades)');
- console.log('-1 -> ' + sendmsg(card_Kh, 'compare', card_As));
- console.log('0 -> ' + sendmsg(card_2c, 'compare', card_2c));
- console.log('1 -> ' + sendmsg(card_Kh, 'compare', card_Td));
$ ln poker/testCard.js testCard.mjs
$ nodejs --experimental-modules testCard
2c -> 2c (two of clubs)
Td -> Td (ten of diamonds)
Kh -> Kh (king of hearts)
As -> As (ace of spades)
-1 -> -1
0 -> 0
1 -> 1
Commentaires