feat(Cards): Display yours and other counts

parent b43278a5
# Credits # Credits
- Byron Knoll - Byron Knoll for the card fronts
\ No newline at end of file
- [DDara](https://www.flaticon.com/authors/ddara) for the back card SVG
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<p>{{ players.length }} en ligne :</p> <p>{{ players.length }} en ligne :</p>
<div <div
v-for="player in players" v-bind:key="player + ''"> v-for="player in players" v-bind:key="player + ''">
<Player :name="player"/> <Player :name="player.name" :nb-cards="player.nbCards"/>
</div> </div>
</div> </div>
<div id="game"> <div id="game">
......
<template> <template>
<div id="player" class="mr-5 ml-5"> <div id="player" class="mr-5 ml-5">
<b-badge :variant="Math.random() >= 0.5? 'dark' : 'danger'"> <b-badge :variant="Math.random() >= 0.5? 'dark' : 'danger'">
Player {{ name }} Player {{ name }} ({{nbCards}})
</b-badge> </b-badge>
<b-img class="icon-card" v-for="index in nbCards" :key="index" fluid src="/img/unknown.svg" />
</div> </div>
</template> </template>
<script> <script>
console.log("Init player!");
export default { export default {
name: "Player", name: "Player",
components: {},
props: { props: {
name: String name: String,
nbCards: Number
}, },
methods: {} methods: {}
}; };
</script> </script>
\ No newline at end of file <style>
img.icon-card {
max-width: 20px;
}
</style>
\ No newline at end of file
...@@ -17,8 +17,9 @@ export const store = new Vuex.Store({ ...@@ -17,8 +17,9 @@ export const store = new Vuex.Store({
isConnected: state => state.isConnected, isConnected: state => state.isConnected,
name: state => state.name, name: state => state.name,
socketMessage: state => state.socketMessage, socketMessage: state => state.socketMessage,
players: state => state.players, gameState: state => state.gameState,
gameState: state => state.gameState cards: state => state.cards,
players: state => state.players
}, },
mutations: { mutations: {
SOCKET_CONNECT(state) { SOCKET_CONNECT(state) {
...@@ -50,6 +51,7 @@ export const store = new Vuex.Store({ ...@@ -50,6 +51,7 @@ export const store = new Vuex.Store({
if (message) { if (message) {
if (message.data) { if (message.data) {
let players = message.data.players; let players = message.data.players;
let cards = message.data.cards;
let gameState = message.data.state; let gameState = message.data.state;
let text = message.data.text; let text = message.data.text;
let extras = message.data.extras; let extras = message.data.extras;
...@@ -61,18 +63,22 @@ export const store = new Vuex.Store({ ...@@ -61,18 +63,22 @@ export const store = new Vuex.Store({
console.log("Setting state:", gameState); console.log("Setting state:", gameState);
state.state = gameState; state.state = gameState;
} }
if (cards) {
console.log("Setting cards:", cards);
state.cards = cards;
}
if (text) { if (text) {
console.log("Setting text:", text); console.log("Setting text:", text);
state.text = text; state.text = text;
} }
if (extras) { if (extras) {
console.log("Extras: ", extras); console.log("Extras: ", extras);
let name = extras.name; let name = extras.name;
if (name) { if (name) {
console.log("Setting name:", name); console.log("Setting name:", name);
state.name = name; state.name = name;
}
} }
}
} }
} }
......
...@@ -115,8 +115,12 @@ class LobbyManager(ClientManager): ...@@ -115,8 +115,12 @@ class LobbyManager(ClientManager):
async def send(self, to: Player, message: MessageToPlayer, extras=None): async def send(self, to: Player, message: MessageToPlayer, extras=None):
sid = self.metadata[to.name].sid sid = self.metadata[to.name].sid
data = {"state": str(message.name),
"players": [p.name for p in self.players]} data = to.hand.json() # Start with "cards": []
data = json.loads(data) # JSONEncode and decode, starting with dict would miss `json()` encoders
data["state"] = str(message.name)
data["players"] = [{"name": p.name, "nbCards": len(p.hand)} for p in self.players]
if extras: if extras:
data["extras"] = extras data["extras"] = extras
...@@ -158,7 +162,6 @@ class LobbyManager(ClientManager): ...@@ -158,7 +162,6 @@ class LobbyManager(ClientManager):
message = MessageToPlayer.ReadyToStart message = MessageToPlayer.ReadyToStart
extras["playersReady"] = [p.name for p in self.players_ready] extras["playersReady"] = [p.name for p in self.players_ready]
elif option == MessageFromPlayer.Bet: elif option == MessageFromPlayer.Bet:
# FIXME vraie annonce, pas juste carre d'as lol # FIXME vraie annonce, pas juste carre d'as lol
announce = Announce(bet=CARRE_ACE) announce = Announce(bet=CARRE_ACE)
...@@ -174,12 +177,16 @@ class LobbyManager(ClientManager): ...@@ -174,12 +177,16 @@ class LobbyManager(ClientManager):
extras["youBet"] = False extras["youBet"] = False
if message: if message:
print("Creating game task...") if message == MessageToPlayer.NewGame:
game = asyncio.create_task(self.maybe_start_game()) print("Creating game task...")
game = asyncio.create_task(self.maybe_start_game())
print("Awaiting game...")
await game
print("Sending message...") print("Sending message...")
await self.send(sender, message, extras) await self.send(sender, message, extras)
print("Awaiting game...") print("Message sent.")
await game
print("LOBBY: Message handled.") print("LOBBY: Message handled.")
...@@ -207,6 +214,9 @@ class LobbyManager(ClientManager): ...@@ -207,6 +214,9 @@ class LobbyManager(ClientManager):
# MSGIN| 3c5e8962c4db465aaf2fd916bea2acc9 (Chihuahua): MENTEUR. # MSGIN| 3c5e8962c4db465aaf2fd916bea2acc9 (Chihuahua): MENTEUR.
# LOBBY: Message handled. # LOBBY: Message handled.
# received # received
await self.send(player, MessageToPlayer.YourTurn, extras={"bet": game.current_bet.json()}) extras = {"bet": game.current_bet.json()}
await self.send(player, MessageToPlayer.YourTurn, extras)
extras["waitingFor"] = player.name
for p in [p for p in game.players if p != player]: for p in [p for p in game.players if p != player]:
await self.send(p, MessageToPlayer.Waiting, extras={"waitingFor": p.name}) await self.send(p, MessageToPlayer.Waiting, extras)
...@@ -20,7 +20,7 @@ class ClientManager(ABC): ...@@ -20,7 +20,7 @@ class ClientManager(ABC):
@abstractmethod @abstractmethod
async def send(self, async def send(self,
to: Player, to: Player,
message: MessageToPlayer, message: MessageToPlayer,
extra=None): extras=None):
raise NotImplementedError("Send a message to clients ") raise NotImplementedError("Send a message to clients ")
...@@ -8,4 +8,4 @@ class Color(Enum): ...@@ -8,4 +8,4 @@ class Color(Enum):
Diamonds = "♦" Diamonds = "♦"
def json(self): def json(self):
return self.value return self.value
\ No newline at end of file
...@@ -28,13 +28,13 @@ class Game: ...@@ -28,13 +28,13 @@ class Game:
async def message(self, message: MessageToPlayer, async def message(self, message: MessageToPlayer,
*to: Player, *to: Player,
extra=None extras=None
) -> None: ) -> None:
if self.manager: if self.manager:
if not to: if not to:
to = self.players to = self.players
for player in to: for player in to:
await self.manager.send(player, message, extra) await self.manager.send(player, message, extras)
@property @property
def global_hand(self) -> Hand: def global_hand(self) -> Hand:
...@@ -57,7 +57,7 @@ class Game: ...@@ -57,7 +57,7 @@ class Game:
winner = self.players[0] winner = self.players[0]
await self.message(MessageToPlayer.Win, winner) await self.message(MessageToPlayer.Win, winner)
await self.message(MessageToPlayer.WinnerIs, extra=winner) await self.message(MessageToPlayer.WinnerIs, extras=winner)
print(f"Game over - {winner.name} wins with {len(winner.hand)} cards!") print(f"Game over - {winner.name} wins with {len(winner.hand)} cards!")
async def new_turn(self) -> Player: async def new_turn(self) -> Player:
...@@ -66,10 +66,13 @@ class Game: ...@@ -66,10 +66,13 @@ class Game:
:return: the player that lost this turn. :return: the player that lost this turn.
""" """
print("New turn!")
# Distribution # Distribution
self.deck.reset() self.deck.reset()
await self.message(MessageToPlayer.WaitTurn) await self.message(MessageToPlayer.WaitTurn)
print("Told players to wait!")
for current_player in self.players: for current_player in self.players:
current_player.clear() current_player.clear()
count_player_cards = self.defeats[current_player] + 1 count_player_cards = self.defeats[current_player] + 1
...@@ -77,9 +80,10 @@ class Game: ...@@ -77,9 +80,10 @@ class Game:
for i in range(count_player_cards): for i in range(count_player_cards):
card = self.deck.random_card() card = self.deck.random_card()
current_player.give(card) current_player.give(card)
print(f"{card}") print(",".join([str(c) for c in current_player.hand.cards]))
await self.message(MessageToPlayer.GiveHand, current_player, extra=current_player.hand.json()) print("Sending cards...")
await self.message(MessageToPlayer.GiveHand, current_player)
print(f"Cards sent.") print(f"Cards sent.")
# Tour # Tour
...@@ -90,7 +94,7 @@ class Game: ...@@ -90,7 +94,7 @@ class Game:
if loser is not None: if loser is not None:
self.players.remove(loser) self.players.remove(loser)
self.players.insert(0, loser) self.players.insert(0, loser)
await self.message(MessageToPlayer.LoseRound, extra=loser.name) await self.message(MessageToPlayer.LoseRound, extras=loser.name)
return loser return loser
last_player = current_player last_player = current_player
...@@ -145,7 +149,7 @@ class Game: ...@@ -145,7 +149,7 @@ class Game:
if not self.current_bet: # First player, has to bet something if not self.current_bet: # First player, has to bet something
print("Game: First awaiting current bet") print("Game: First awaiting current bet")
await self.message(MessageToPlayer.YourTurn, current_player, extra=self.current_bet) await self.message(MessageToPlayer.YourTurn, current_player, extras=self.current_bet)
while not self.current_bet: # Ask a valid bet while not self.current_bet: # Ask a valid bet
print("Game: While no bet, awaiting") print("Game: While no bet, awaiting")
announce = await current_player.announce(self.current_bet) announce = await current_player.announce(self.current_bet)
...@@ -154,7 +158,7 @@ class Game: ...@@ -154,7 +158,7 @@ class Game:
print(f"{current_player} starts the round: {self.current_bet}") print(f"{current_player} starts the round: {self.current_bet}")
print("Game: Awaiting start announce") print("Game: Awaiting start announce")
await self.message(MessageToPlayer.Announce, await self.message(MessageToPlayer.Announce,
extra={"player": current_player.name, "announce": announce.json()}) extras={"player": current_player.name, "announce": announce.json()})
else: else:
print(f"You cannot say Menteur on first round, {current_player}!") print(f"You cannot say Menteur on first round, {current_player}!")
...@@ -166,7 +170,7 @@ class Game: ...@@ -166,7 +170,7 @@ class Game:
announce = Announce() # MENTEUR obligatoire announce = Announce() # MENTEUR obligatoire
else: else:
print("Game: Awaiting bet") print("Game: Awaiting bet")
await self.message(MessageToPlayer.YourTurn, current_player, extra=self.current_bet) await self.message(MessageToPlayer.YourTurn, current_player, extras=self.current_bet)
announce = await current_player.announce(self.current_bet) announce = await current_player.announce(self.current_bet)
if announce.bet: if announce.bet:
...@@ -177,7 +181,7 @@ class Game: ...@@ -177,7 +181,7 @@ class Game:
# Valid bet: # Valid bet:
print(f" {current_player} bets {self.current_bet}.") print(f" {current_player} bets {self.current_bet}.")
self.message(MessageToPlayer.Announce, extra={"player": current_player, "announce": announce}) self.message(MessageToPlayer.Announce, extras={"player": current_player, "announce": announce})
else: # Menteur! Who lost the round? else: # Menteur! Who lost the round?
menteur = self.is_menteur(self.current_bet) menteur = self.is_menteur(self.current_bet)
......
...@@ -17,4 +17,4 @@ class Value(Enum): ...@@ -17,4 +17,4 @@ class Value(Enum):
Ace = 13 Ace = 13
def json(self): def json(self):
return self.value return self.value
\ No newline at end of file
...@@ -31,8 +31,8 @@ class MockPlayer(Player): ...@@ -31,8 +31,8 @@ class MockPlayer(Player):
async def announce(self, current_bet: Optional[Hand]) -> Announce: async def announce(self, current_bet: Optional[Hand]) -> Announce:
return Announce(bet=self.bets.pop() if self.bets else CARRE_ACE) return Announce(bet=self.bets.pop() if self.bets else CARRE_ACE)
def receive(self, message: MessageToPlayer, extra: Optional[Any] = None): def receive(self, message: MessageToPlayer, extras: Optional[Any] = None):
self.messages.append((message, extra)) self.messages.append((message, extras))
def print_msgs(self) -> str: def print_msgs(self) -> str:
return '|'.join([f"{m}[{e}]" if e else str(m) for (m, e) in self.messages]) return '|'.join([f"{m}[{e}]" if e else str(m) for (m, e) in self.messages])
...@@ -43,10 +43,10 @@ class MockManager(ClientManager): ...@@ -43,10 +43,10 @@ class MockManager(ClientManager):
super().__init__() super().__init__()
self.players = players self.players = players
def send(self, to: Player, message: MessageToPlayer, extra=None): def send(self, to: Player, message: MessageToPlayer, extras=None):
if isinstance(to, MockPlayer): if isinstance(to, MockPlayer):
to.receive(message, extra) to.receive(message, extras)
print(f"Sent {message} {'(' + str(extra) + ') ' if extra else ''}to {to}") print(f"Sent {message} {'(' + str(extras) + ') ' if extras else ''}to {to}")
class TestManager(TestCase): class TestManager(TestCase):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment