Browse Source

improving game logic

Nicolas Winkler 4 năm trước cách đây
mục cha
commit
0e202c6bb6
4 tập tin đã thay đổi với 68 bổ sung17 xóa
  1. 6 2
      src/game.rs
  2. 23 2
      src/server.rs
  3. 13 3
      src/websocket.rs
  4. 26 10
      static/index.html

+ 6 - 2
src/game.rs

@@ -8,6 +8,7 @@ use crate::server;
 pub enum GameState {
     Creating,
     Guessing(usize),
+    Revealing
 }
 
 #[derive(Serialize, Deserialize, Clone)]
@@ -53,11 +54,11 @@ impl Game {
         self.players.iter_mut().find(|x| x.nick == nick)
     }
 
-    pub fn submit_creation(&mut self, player_nick: &str, word: &str) -> bool {
+    pub fn submit_creation(&mut self, player_nick: &str, word: String) -> bool {
         match self.state {
             GameState::Creating => {
                 if let Some(player) = self.get_player(player_nick) {
-                    player.submitted_word = Some(word.to_owned());
+                    player.submitted_word = Some(word);
                     true
                 }
                 else {
@@ -80,6 +81,9 @@ impl Game {
                 else {
                     self.state = GameState::Creating;
                 }
+            },
+            GameState::Revealing{} => {
+                
             }
         }
     }

+ 23 - 2
src/server.rs

@@ -7,6 +7,7 @@ use actix::prelude::*;
 use actix_web::{web, Error, HttpRequest, HttpResponse};
 use actix_web_actors::ws;
 use crate::game;
+use crate::websocket;
 use crate::websocket::*;
 
 const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
@@ -16,12 +17,15 @@ const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
 #[rtype(result = "Answer")]
 struct JoinRequest{ lobby_id: String, nick: String, p: Addr<GameConnection> }
 
-
 #[derive(Message)]
 #[rtype(result = "Answer")]
 struct CreateLobbyRequest{ lobby_id: String, p: Addr<GameConnection> }
 
 #[derive(Message)]
+#[rtype(result = "()")]
+struct SubmitWordMsg{ word: String, nick: String }
+
+#[derive(Message)]
 #[rtype(result = "Result<game::Game, ()>")]
 struct GetGame;
 
@@ -132,6 +136,13 @@ impl Handler<GetGame> for GameLobby {
     }
 }
 
+impl Handler<SubmitWordMsg> for GameLobby {
+    type Result = ();
+    fn handle(&mut self, swm: SubmitWordMsg, ctx: &mut Self::Context) -> Self::Result {
+        self.game.submit_creation(&swm.nick, swm.word);
+    }
+}
+
 impl GameLobby {
     pub fn new(gi: String) -> Self {
         GameLobby {
@@ -150,7 +161,7 @@ impl GameLobby {
 
     pub fn create_opaque_message(&self, nick: &str) -> GameData {
         GameData {
-            players: self.game.players.iter().map(|p| p.nick.clone()).collect::<Vec<_>>(),
+            players: self.game.players.iter().map(|p| websocket::PlayerData{ nick: p.nick.clone(), points: 0 }).collect::<Vec<_>>(),
             state_data: GameStateData::Creating{ available_chars: vec!['a', 'b', 'c'] }
         }
     }
@@ -278,6 +289,16 @@ impl GameConnection {
                         }
                     }*/
                 },
+                ClientMessage::SubmitWord{ word } => {
+                    if let Some(lobby) = &self.game_lobby {
+                        if let Some(nick) = &self.nick {
+                            lobby.do_send(SubmitWordMsg{ word: word, nick: nick.clone() });
+                        }
+                    }
+                },
+                ClientMessage::SubmitGuess{ guesses } => {
+                    
+                }
             }
         }
         else {

+ 13 - 3
src/websocket.rs

@@ -20,19 +20,29 @@ pub async fn ws_initiate(server: web::Data<Addr<server::Server>>, r: HttpRequest
 pub enum ClientMessage {
     CreateGame{ game_id: String, nick: String },
     Join{ game_id: String, nick: String },
+    SubmitWord{ word: String },
+    SubmitGuess{ guesses: Vec<(String, String)> },
 }
 
 #[derive(Serialize, Deserialize)]
 #[serde(rename_all = "snake_case")]
 pub enum GameStateData {
     Creating{ available_chars: Vec<char> },
-    Guessing()
+    Guessing{ submitted_words: Vec<String>, questions: Vec<String> },
+    Revealing{  },
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub struct PlayerData {
+    pub nick: String,
+    pub points: i32
 }
 
 #[derive(Serialize, Deserialize)]
 #[serde(rename_all = "snake_case")]
 pub struct GameData {
-    pub players: Vec<String>,
+    pub players: Vec<PlayerData>,
     pub state_data: GameStateData
 }
 
@@ -41,7 +51,7 @@ pub struct GameData {
 pub enum UpdateMessage {
     GameNotFound{ game_id: String },
     GameAlreadyExists{ game_id: String },
-    GameState(GameData)
+    GameState(GameData),
 }
 
 

+ 26 - 10
static/index.html

@@ -31,6 +31,16 @@
                 connect(msg);
             });
 
+            $('#submit').click(function() {
+                var word = $('#word').val();
+                var msg = {
+                    submit_word: {
+                        word: word
+                    }
+                };
+                connect(msg);
+            });
+
             function connect(initial_message) {
                 if (connection != null) {
                     disconnect();
@@ -45,10 +55,9 @@
                     onReceive(e);
                 };
                 connection.onclose = function() {
-                    connection = null;
                 };
             }
-            
+
             function disconnect() {
                 connection.close();
                 connection = null;
@@ -63,12 +72,18 @@
                     $('#status').html("Game \"" + obj.game_already_exists.game_id + "\" already exists");
                 }
                 else if (obj.game_state != null) {
-                    playerlist = "";
-                    for (var i = 0; i < obj.game_state.players.length; i++) {
-                        playerlist = playerlist + ", " + obj.game_state.players[i];
+                    var gs = obj.game_state;
+                    if (gs.state_data.creating != null) {
+                        var players = gs.players;
+                        playerlist = "";
+                        for (var i = 0; i < players.length; i++) {
+                            playerlist += players[i].nick + "(" + players[i].points + ")";
+                            if (i + 1 < players.length)
+                                playerlist += ", ";
+                        }
+                        $('#status').html("Players: " + playerlist);
+                        $('#createform').toggle();
                     }
-                    $('#status').html("Players: " + playerlist);
-                    $('#createform').toggle();
                 }
                 else {
                     $('#status').html("Unknown Message recieved");
@@ -88,9 +103,10 @@
 </form>
 
 <form id="createform" style="display:none">
-  <label for="word">Game ID:</label>
-  <input id="word" type="text" /><br>
-  <input id="submit" type="button" value="Submit Word" />
+    <label>Create a word with the following letters</label>
+    <label for="word">Word:</label>
+    <input id="word" type="text" /><br>
+    <input id="submit" type="button" value="Submit Word" />
 </form>
 <div id="status">
 </div>