feat(Cards): Display yours and other counts

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