This repository has been archived on 2021-10-15. You can view files and clone it, but cannot push or open issues or pull requests.
2020-coding-projects/uno/client/Player.js
2020-05-05 22:35:48 +02:00

90 lines
2.5 KiB
JavaScript

export class Player {
constructor(game, id, name) {
this.game = game;
this.id = id;
this.name = name;
this.hand = [];
this.isTurn = false;
this.highlightedCard = null;
this.cardArea = {
currentWidth: 0.5,
allowedWidth: 0.5,
currentCard: null,
cardWidth: 0.1,
};
}
init() {
this.registerEventListeners();
}
registerEventListeners() {
this.game.registerListener('hover', event => {
const width = this.cardArea.currentWidth;
const left = 0.5 - width / 2;
const right = left + width - this.cardArea.cardWidth;
this.highlightedCard = Math.min(Math.max(Math.floor((event.relX - left) / (right - left) * this.hand.length), 0), this.hand.length - 1);
}, 0, 0.8, 1, 0.2);
this.game.registerListener('click', event => {
console.log('clicked card');
if (!this.isTurn) {
return;
}
if (this.highlightedCard !== null) {
this.playCard(this.highlightedCard);
}
});
}
addCard(card) {
this.hand.push(card);
}
setHand(cards) {
this.hand = cards
.sort((a, b) => a.value.localeCompare(b.value))
.sort((a, b) => a.color.localeCompare(b.color));
}
playCard(index) {
console.log('played', this.name);
const card = this.hand[index];
this.game.playCard(card);
}
getCardOffset() {
const width = 800;
const offset = Math.min((width - 100) / this.hand.length, 60);
return offset;
}
getWidth(offset) {
return offset * (this.hand.length - 1) + 100;
}
draw(renderer) {
const offset = this.getCardOffset();
const width = this.getWidth(offset);
let x = -width / 2;
this.cardArea.currentWidth = width / this.game.renderer.width;
this.cardArea.cardWidth = 100 / this.game.renderer.width;
this.hand.forEach((card, index) => {
if (this.highlightedCard === index) {
this.cardArea.currentCard = x / this.game.renderer.width;
card.draw(renderer, x);
x += 100;
} else {
card.draw(renderer, x);
x += offset;
}
});
renderer.pop();
}
}