Last active
February 12, 2019 14:09
-
-
Save lukeburford/ffaa43354ce2845743326b40ea7d00d8 to your computer and use it in GitHub Desktop.
Dart OOP Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
var deck = new Deck(); | |
print(deck); | |
// Shuffle the deck | |
deck.shuffle(); | |
print(deck.cardsWithSuit('Banana')); | |
print(deck.deal(5)); | |
// this deck should have the ones from the deal above omitted - see the deal() function | |
print(deck); | |
deck.removeCard('Spade', 'Two'); | |
print(deck); | |
} | |
class Deck { | |
// Properties | |
List<Card> cards = []; | |
// Constructor | |
Deck() { | |
var ranks = ['Ace', 'Two', 'Three', 'Four']; | |
var suits = ['Banana', 'Spade', 'Hand', 'Foot']; | |
for (var suit in suits) { | |
for (var rank in ranks) { | |
var card = new Card(suit: suit, rank: rank); | |
cards.add(card); | |
} | |
} | |
} | |
// return string method | |
toString() { | |
return cards.toString(); | |
} | |
// Shuffle method (comes from the Dart stdlib) | |
shuffle() { | |
cards.shuffle(); | |
} | |
// Get all cards in a suit. Make it require one arg, of type String. | |
cardsWithSuit(String suit) { | |
// Nuts to 'for' loops - we can use List's 'where' method, from the stdlib | |
// using fat arrow version here | |
return cards.where((card) => card.suit == suit); | |
} | |
// Deal, punk | |
deal(int handSize) { | |
// run the stdlib sublist method on our cards list the first time | |
var hand = cards.sublist(0, handSize); | |
/* | |
ok so now we have sliced the first 'handSize' amount of cards from the List | |
But, remember, this has *not* removed them from the original cards List though, as | |
we might expect. This is because each item is really a >Reference< to a card, | |
not the card itself. So the following takes the remaining cards, and overwrites the | |
original List with this new set. | |
*/ | |
cards = cards.sublist(handSize); | |
/* unlike in JS or similar, we don't need to use a second param with .length etc to specify the end | |
of the range in sublist; if we just provide it one param, Dart presumes we mean 'to | |
the end of the List' */ | |
return hand; | |
} | |
// Remove a Card | |
removeCard(String suit, String rank) { | |
cards.removeWhere((card) => (card.suit == suit) && (card.rank == rank)); | |
} | |
} | |
class Card { | |
// Properties | |
String suit; | |
String rank; | |
// Constructor | |
Card({this.suit, this.rank}); | |
// return string method | |
toString() { | |
return '$rank of $suit'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment