feat: Display Players

parent fe4f7dc4
<template>
<div id="app">
<h2 id="header">Salut {{ name }} !</h2>
<Sockets />
<Sockets v-on:message="newMessage($event)" />
<div id="players">
<p>{{ players.length }} en ligne :</p>
<div
v-for="player in players" v-bind:key="player + ''">
<Player :name="player"/>
</div>
</div>
<div id="game">
<Hand :cards="mockCards()" />
<label for="messages"> Choose a message:</label>
<select v-model="message" name="message" id="messages">
<option value="WAITING">J'attends</option>
......@@ -12,6 +18,7 @@
<option value="MENTEUR">Menteur !</option>
</select>
<button v-on:click="sendMessage(message)">Envoyer</button>
<Hand :cards="currentCards()" />
</div>
</div>
</template>
......@@ -22,6 +29,7 @@ import "es6-promise/auto"; // Needed for Promise polyfill
import VueSocketIO from "vue-socket.io";
import Vuex, { mapGetters, mapMutations } from "vuex";
import Hand from "./components/Hand";
import Player from "./components/Player";
import Sockets from "./Sockets";
import { store } from "./vuex-store";
import { BootstrapVue, IconsPlugin } from "bootstrap-vue";
......@@ -42,13 +50,14 @@ Vue.use(
mutationPrefix: "SOCKET_"
},
options: { path: "/socket.io/" } //Optional options
})
}), store
);
export default {
name: "App",
store: store,
components: {
Player,
Sockets,
Hand
},
......@@ -58,18 +67,42 @@ export default {
};
},
computed: {
...mapGetters(["isConnected", "name", "socketMessage"])
...mapGetters(["isConnected", "name", "text",
"cards", "players", "socketMessage"])
},
methods: {
sendMessage: function(message) {
console.log("User wants to send", message);
this.$socket.emit("message", message);
},
newMessage: function(data) {
console.log("App received new state:", data.data);
this.handleState(data);
},
handleState: function(data) {
console.log("hS: ", data);
if (data.message === "NewGame") {
console.log("New Game!");
}
},
currentCards() {
let currentState = this.socketMessage;
console.log("curCards! state now:", currentState);
if (currentState["data"]) {
if (currentState["data"]["cards"]) {
console.log("Setting cards...");
return this.cards;
} else return this.mockCards();
} else return this.mockCards();
// console.log("Current socket.sMs now:", Sockets.sockets.socketMessages);
},
mockCards() {
return [
{ value: "ace", color: "hearts" },
{ value: "ace", color: "clubs" },
{ value: "ace", color: "diamonds" },
// { value: "ace", color: "hearts" },
// { value: "ace", color: "clubs" },
// { value: "ace", color: "diamonds" },
{ value: "ace", color: "spades" }
];
},
......
......@@ -9,11 +9,14 @@
<p v-if="!isConnected">We're not connected yet...</p>
<div v-if="socketMessages.length >= 1">
<p>Messages from server"</p>
<p>Messages from server:</p>
<b-list-group horizontal="">
<b-list-group-item v-for="m in socketMessages.slice(-8)" :key="m + ''">
{{ m.data.state }}
<div v-if="m.data.extras">Extras: {{ m.data.extras }}</div>
</b-list-group-item>
</b-list-group>
<ul id="messages">
<li v-for="message in socketMessages.slice(-20)" :key="message">
{{ message }}
</li>
</ul>
</div>
</div>
......@@ -32,7 +35,7 @@ export default {
connect() {
// Fired when the socket connects.
this.isConnected = true;
console.log("login");
console.log(" login");
},
disconnect() {
this.isConnected = false;
......@@ -40,9 +43,12 @@ export default {
this.socketMessages = [];
},
// Fired when the server sends something on the "messageChannel" channel.
messageChannel(data) {
this.socketMessages.push(data);
console.log("Message received:", data, "!");
messageChannel(message) {
message = { data: JSON.parse(message), received: new Date().toISOString() };
console.log("S.mC| Message augmented:", message);
this.socketMessages.push(message);
this.$store.commit("message", message);
this.$emit("message", message);
}
},
......@@ -64,8 +70,13 @@ export default {
},
logOff() {
this.$socket.ondisconnect();
this.socketMessage = [];
this.socketMessages = [];
}
}
};
</script>
<style>
.list-group-item {
font-size: small;
}
</style>
\ No newline at end of file
<template>
<div id="hand">
<div id="hand" class="mr-5 ml-5">
<h3>Tu as <b>{{ count() }}</b> cartes en main.</h3>
<b-card-group deck>
<Card
......
<template>
<div id="player" class="mr-5 ml-5">
<b-badge :variant="Math.random() >= 0.5? 'dark' : 'danger'">
Player {{ name }}
</b-badge>
</div>
</template>
<script>
console.log("Init player!");
export default {
name: "Player",
components: {},
props: {
name: String
},
methods: {}
};
</script>
\ No newline at end of file
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
isConnected: false,
name: "Menteur inconnu",
text: "none",
socketMessage: "",
gameState: "RESET",
cards: [],
players: []
},
getters: {
isConnected: state => state.isConnected,
name: state => state.name,
socketMessage: state => state.socketMessage,
players: state => state.players,
gameState: state => state.gameState
},
mutations: {
SOCKET_CONNECT(state) {
state.isConnected = true;
},
SOCKET_DISCONNECT(state) {
state.isConnected = false;
},
SOCKET_MESSAGECHANNEL(state, message) {
state.socketMessage = message;
console.log("SMC| Current state now:", state.socketMessage);
},
name(state, name) {
state.name = name;
},
text(state, text) {
state.text = text;
},
gameState(state, gameState) {
state.gameState = gameState;
},
cards(state, cards) {
state.cards = cards;
},
message(state, message) {
state.socketMessage = message;
console.log("storeMess| Current message now:" + JSON.stringify(message));
if (message) {
if (message.data) {
let players = message.data.players;
let gameState = message.data.state;
let text = message.data.text;
let extras = message.data.extras;
if (players) {
console.log("Setting players:", players);
state.players = players;
}
if (gameState) {
console.log("Setting state:", gameState);
state.state = gameState;
}
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;
}
}
}
}
}
}
});
......@@ -2,7 +2,8 @@ from server.model.color import Color
from server.model.value import Value
def encode_value(v: Value):
def encode_value(v: Value, lang="en"):
if lang == "fr":
return {
"Two": "Deux",
"Three": "Trois",
......@@ -18,12 +19,33 @@ def encode_value(v: Value):
"King": "Roi",
"Ace": "As"
}[v.name]
else:
return {
"Two": "2",
"Three": "3",
"Four": "4",
"Five": "5",
"Six": "6",
"Seven": "7",
"Eight": "8",
"Nine": "9",
"Ten": "10",
"Jack": "jack",
"Queen": "queen",
"King": "king",
"Ace": "ace"
}[v.name]
def encode_color(c: Color):
def encode_color(c: Color, lang="en"):
return {
"Hearts": "Coeur",
"Spades": "Pique",
"Clubs": "Trèfle",
"Diamonds": "Carreau"
}[c.name] if lang == "fr" else {
"Hearts": "hearts",
"Spades": "spades",
"Clubs": "clubs",
"Diamonds": "diamonds"
}[c.name]
......@@ -38,12 +38,12 @@ class LobbyManager(ClientManager):
def players_ready(self):
return [self.lobby[k] for k, m in self.metadata.items() if m.ready]
def new_player(self, player: Player, sid: str) -> str:
async def new_player(self, player: Player, sid: str) -> None:
self.lobby[player.name] = player
self.players.append(player)
self.metadata[player.name] = Metadata(sid=sid)
print(f"Added {player} to a lobby with {len(self.lobby)} players.")
return f"Bienvenu, {player}! Il y a {len(self.lobby)} joueurs en ligne."
await self.send(to=player, message=MessageToPlayer.Welcome, extras={"name": player.name})
def wants_to_play(self, player: Player):
"""
......@@ -98,9 +98,10 @@ class LobbyManager(ClientManager):
async def send(self, to: Player, message: MessageToPlayer, extras=None):
sid = self.metadata[to.name].sid
data = {"message": str(message.name)}
data = {"state": str(message.name),
"players": [p.name for p in self.players]}
if extras:
data["extra"] = extras
data["extras"] = extras
print(f"MSGOUT|{sid} ({to.name}), {data}")
await self.sio.emit('messageChannel', json.dumps(data), room=sid)
......@@ -109,6 +110,9 @@ class LobbyManager(ClientManager):
message = None
extras = {"players": [p.name for p in self.players]}
sender = self.which_player(sid)
if not sender:
print(f"ERROR: Unrecognized sender {sid}")
return
print(f"MSGIN| {sid} ({sender.name}): {data}.")
......
......@@ -2,6 +2,7 @@ from enum import Enum
class MessageToPlayer(Enum):
Welcome = "WELCOME"
Waiting = "WAITING_ROOM"
ReadyToStart = "READY_ROOM"
NewGame = "NEW_GAME"
......
......@@ -39,8 +39,7 @@ class ClientPlayer(Player):
async def connect(sid, environ):
print("[WS] Connect ", sid, environ)
player = ClientPlayer(lobby)
reply: str = lobby.new_player(player, sid)
await sio.emit('messageChannel', reply, room=sid)
await lobby.new_player(player, sid)
@sio.event
......@@ -52,7 +51,7 @@ async def message(sid, data):
@sio.on("pingServer")
async def ping_server(sid, data):
print("[WS] Ping received:", data)
await sio.emit('messageChannel', "PONG", room=sid)
await sio.emit('messageChannel', '{"extras":{"message":"PONG"}}', room=sid)
@sio.event
......
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