I have been working on a BlackJack game. I am trying to simulate the dealer dispatching a card from the deck to the player when they request a card to be drawn.
My code is around 300 lines at this time, so for the sake of clarity I’ll try to only include the relevant portions related to the topic.
renderPlayers() {
this.players.forEach(player => {
player.template.id = player.name;
player.template.style.margin = "10px";
$('game-table').appendChild(player.template);
const placeholder = QS({ p: $(player.name),
s: '.player-position .placeholder' }).getBoundingClientRect();
player.setPlaceholder(placeholder);
});
}
renderDeck() {
this.gameInstance.deck.cards.forEach(card => {
const styles = [
{ 'position': 'absolute' },
{ 'top': '4px' },
{ 'left': '4px' }
];
applyStyles(styles, card);
QS({ p: $('game-deck'),
s: '.placeholder' }).appendChild(card.template);
});
}
deal() {
this.players.forEach(player => {
const card = this.gameInstance.deal();
player.hit(card.template);
});
}
}
class Player {
constructor(playerName) {
this.template = new clonePlayerTemplate();
this.name = playerName;
this.cards = [];
}
setPlaceholder(placeholder) {
this.placeholder = placeholder;
}
hit(card) {
this.cards.push(card);
const dest = this.placeholder;
this.renderCards();
animateCard(card, dest);
}
renderCards() {
this.cards.forEach((card, index) => {
// Stagger the cards
const offset = index * 20;
const styles = [
{ 'position': 'absolute' },
{ 'top': '4px' },
{ 'left': `${(offset + 4)}px` }, /* +4 for visual... assuming border width */
{ 'z-index': 1 }
];
applyStyles(styles, card);
QS({
p: $(this.name),
s: '.player-position .placeholder'
}).appendChild(card);
});
}
}
function animateCard(card, dest) {
// get the position of the card "on the deck"
const origin = card.getBoundingClientRect();
const styles = [
{ 'position': 'absolute' },
{ 'top': origin.top + 'px' },
{ 'left': origin.left + 'px' }
];
// determine the destination
const new_styles = [
{ 'top': dest.top + 'px' },
{ 'left': dest.left + 'px' }
];
// Apply initial styles
applyStyles(styles, card);
// Attempt to dispatch the card to the player, utilizing CSS transition
requestAnimationFrame(() => {
applyStyles(new_styles, card);
});
}
Currently, when a card is drawn… it positions considerably far away from the placeholder. However when another card is drawn it positions appropriately and staggers as expected.