فهرست منبع

still improving

Nicolas Winkler 4 سال پیش
والد
کامیت
d16da28824
5فایلهای تغییر یافته به همراه244 افزوده شده و 175 حذف شده
  1. 35 13
      src/game.rs
  2. 16 5
      src/server.rs
  3. 186 0
      static/comm.js
  4. 6 157
      static/index.html
  5. 1 0
      static/jquery-3.5.1.js

+ 35 - 13
src/game.rs

@@ -1,23 +1,22 @@
-use std::time::{Duration, Instant};
 use serde::{Serialize, Deserialize};
-use actix::{Actor, Addr, Context};
+use std::collections::BTreeMap;
 use crate::websocket;
 use crate::server;
 
-#[derive(Serialize, Deserialize, Clone, PartialEq)]
+#[derive(Serialize, Deserialize, Clone, PartialEq, Debug)]
 pub enum GameState {
     Starting,
     Creating,
     Guessing
 }
 
-#[derive(Serialize, Deserialize, Clone)]
+#[derive(Serialize, Deserialize, Clone, Debug)]
 pub struct CreatingEx {
     pub question: String,
     pub letters: Vec<char>
 }
 
-#[derive(Serialize, Clone)]
+#[derive(Serialize, Clone, Debug)]
 pub struct Player {
     pub nick: String,
     pub creating_exercise: Option<CreatingEx>,
@@ -25,7 +24,7 @@ pub struct Player {
     pub submitted_guess: Option<Vec<(String, String)>>
 }
 
-#[derive(Serialize, Clone)]
+#[derive(Serialize, Clone, Debug)]
 pub struct Game {
     pub players: Vec<Player>,
     pub round_number: i32,
@@ -49,19 +48,42 @@ impl Game {
         self.players.iter_mut().find(|x| x.nick == nick)
     }
 
+    pub fn check_letters(word: &str, letters: &Vec<char>) -> bool {
+        let mut countmap: BTreeMap<char, isize> = BTreeMap::new();
+        for c in letters {
+            countmap.insert(*c, countmap.get(c).unwrap_or(&0) + 1);
+        }
+        for c in word.chars() {
+            let count = countmap.get(&c);
+            if let Some(&v) = count {
+                if v < 0 {
+                    return false;
+                }
+                countmap.insert(c, v - 1);
+            }
+            else {
+                return false;
+            }
+        }
+
+        true
+    }
+
     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);
-                    true
-                }
-                else {
-                    false
+                    if let Some(ex) = &player.creating_exercise {
+                        if Self::check_letters(&word, &ex.letters) {
+                            player.submitted_word = Some(word);
+                            return true;
+                        }
+                    }
                 }
             },
-            _ => false
+            _ => {}
         }
+        false
     }
 
     pub fn submit_guess(&mut self, player_nick: &str, guess: Vec<(String, String)>) -> bool {
@@ -103,7 +125,7 @@ impl Game {
         self.clear_submissions();
 
         let mut exes = vec![
-            CreatingEx{ question: "An Alphabet".to_owned(), letters: vec!['a', 'b', 'c'] },
+            CreatingEx{ question: "Delikatessfutter für Hunde".to_owned(), letters: vec!['a', 'b', 'c'] },
             CreatingEx{ question: "A Betabet".to_owned(), letters: vec!['b', 'c', 'd'] },
             CreatingEx{ question: "A Gammaabet".to_owned(), letters: vec!['c', 'd', 'e'] },
             CreatingEx{ question: "A Deltaabet".to_owned(), letters: vec!['d', 'e', 'f'] },

+ 16 - 5
src/server.rs

@@ -151,7 +151,7 @@ pub struct GameLobby {
 impl Actor for GameLobby {
     type Context = Context<Self>;
     fn started(&mut self, ctx: &mut Self::Context) {
-        self.game.start_round();
+        self.lobby_state = LobbyState::Starting;
     }
 }
 
@@ -195,7 +195,7 @@ 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);
+        let correct = self.game.submit_creation(&swm.nick, swm.word);
         if self.game.all_words_submitted() {
             self.set_state(LobbyState::Guessing);
             self.game.next_state();
@@ -262,7 +262,9 @@ impl GameLobby {
                         .map(|p| p.submitted_word.clone().unwrap())
                         .collect::<Vec<_>>();
         let questions = self.game.players.iter()
-                        .map(|x| x.creating_exercise.clone().unwrap().question)
+                        .map(|x| x.creating_exercise.as_ref().unwrap())
+                        .chain(self.game.additional_questions.iter())
+                        .map(|x| x.question.clone())
                         .collect::<Vec<_>>();
         let solutions = words.iter()
                         .map(|x| x.clone())
@@ -287,6 +289,8 @@ impl GameLobby {
 
     pub fn create_opaque_message(&self, nick: &str) -> GameData {
 
+        let player = self.game.players.iter()
+                        .find(|p| p.nick == nick);
         GameData {
             players: self.game.players.iter()
                         .map(|p| websocket::PlayerData{ nick: p.nick.clone(), points: 0 })
@@ -298,8 +302,8 @@ impl GameLobby {
                     },
                     game::GameState::Creating => {
                         GameStateData::Creating{
-                            question: "Ein Gerät um Elche zu häuten".to_owned(),
-                            available_chars: vec!['a', 'b', 'c']
+                            question: player.unwrap().creating_exercise.as_ref().unwrap().question.clone(),
+                            available_chars: player.unwrap().creating_exercise.as_ref().unwrap().letters.clone()
                         }
                     },
                     game::GameState::Guessing => {
@@ -309,7 +313,14 @@ impl GameLobby {
         }
     }
 
+    pub fn check_optionals(&self) {
+        for p in &self.game.players {
+            println!("{:?}", p);
+        }
+    }
+
     pub fn create_guessing(&self) -> GameStateData {
+        self.check_optionals();
         let words_with_chars = self.game.players.iter()
             .map(|p|
                 (p.submitted_word.clone().unwrap(),

+ 186 - 0
static/comm.js

@@ -0,0 +1,186 @@
+$(function() {
+    var connection = null;
+
+    var wordlist = null;
+    var questionlist = null;
+
+    $('#join').click(function() {
+        var game_id = $('#gameId').val();
+        var nick = $('#nick').val();
+        var msg = {
+            join: {
+                game_id: game_id,
+                nick: nick,
+            }
+        };
+        connect(msg);
+    });
+
+    $('#create').click(function() {
+        var game_id = $('#gameId').val();
+        var nick = $('#nick').val();
+        var msg = {
+            create_game: {
+                game_id: game_id,
+                nick: nick,
+            }
+        };
+        connect(msg);
+    });
+
+    $('#ready').click(function() {
+        var game_id = $('#gameId').val();
+        var nick = $('#nick').val();
+        var msg = "ready";
+        send(msg);
+    });
+
+    $('#submit').click(function() {
+        var word = $('#word').val();
+        var msg = {
+            submit_word: {
+                word: word
+            }
+        };
+        send(msg);
+    });
+
+    $('#submitGuess').click(function() {
+        var list = [];
+        for(var i = 0; i < wordlist.length; i++) {
+            var field = "#g" + i;
+            var numTxt = $(field).val();
+            var number = parseInt(numTxt);
+            if (number > 0 && number <= questionlist.length) {
+                list.push([wordlist[i], questionlist[number - 1]]);
+            }
+            else {
+                $("#status").html("Please enter a valid number");
+                return;
+            }
+        }
+        var msg = {
+            submit_guess: {
+                guesses: list
+            }
+        };
+        send(msg);
+    });
+
+    function connect(initial_message) {
+        if (connection != null) {
+            disconnect();
+        }
+        var uri = 'ws://' + window.location.host + '/ws/';
+        connection = new WebSocket(uri);
+
+        connection.onopen = function() {
+            connection.send(JSON.stringify(initial_message));
+        };
+        connection.onmessage = function(e) {
+            onReceive(e);
+        };
+        connection.onclose = function() {
+        };
+    }
+
+    function send(message) {
+        if (connection != null) {
+            connection.send(JSON.stringify(message));
+        }
+    }
+
+    function disconnect() {
+        connection.close();
+        connection = null;
+    }
+
+    function onReceive(msg) {
+        var obj = jQuery.parseJSON(msg.data);
+        if (obj.game_not_found != null) {
+            $('#status').html("Game \"" + obj.game_not_found.game_id + "\" not found");
+        }
+        else if (obj.game_already_exists != null) {
+            $('#status').html("Game \"" + obj.game_already_exists.game_id + "\" already exists");
+        }
+        else if (obj.game_state != null) {
+            var gs = obj.game_state;
+            if (gs.state_data === "starting") {
+                $('#startingform').show();
+            }
+            else 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);
+
+                var creating = gs.state_data.creating;
+                var chars = creating.available_chars;
+                $('#question').val(creating.question);
+                $('#letters').val(chars.join());
+                $('#createform').show();
+            }
+            else if (gs.state_data.guessing != null) {
+                var guesses = gs.state_data.guessing;
+                var sub_words = guesses.submitted_words;
+                var questions = guesses.questions;
+                var questionsHtml = "";
+                for (var i = 0; i < questions.length; i++) {
+                    questionsHtml += (i + 1) + ": " + questions[i] + "<br>";
+                }
+                $('#guessingDynTable').html(questionsHtml);
+                $('#guessingDyn').html("");
+                for (var i = 0; i < sub_words.length; i++) {
+                    var $label = $("<label to='g" + i + "'>" + sub_words[i][0] + "</label>");
+                    var $field = $("<input id='g" + i + "' type='text' /><br>");
+                    $('#guessingDyn').append($label);
+                    $('#guessingDyn').append($field);
+                }
+
+                questionlist = questions;
+                wordlist = sub_words.map(pair => pair[0]);
+                
+                $('#createform').hide();
+                $('#guessing').show();
+            }
+        }
+        else if (obj.round_result != null) {
+            displayResult(obj.round_result);
+        }
+        else {
+            $('#status').html("Unknown Message recieved");
+        }
+    }
+
+    function displayResult(result) {
+        var $table = $('<table/>');
+
+        var wordline = "<tr><th></th>";
+        for(var i = 0; i < result.words.length; i++) {
+            wordline += "<th>" + result.words[i] + "</th>";
+        }
+        wordline += "</tr>";
+        $table.append(wordline);
+
+        for(var i = 0; i < result.questions.length; i++) {
+            var wordline = "<tr><th>" + result.questions[i] + "</th>";
+            for(var j = 0; j < result.words.length; j++) {
+                wordline += "<td>" + result.guesses[j][i] + "</td>";
+            }
+            wordline += "</tr>";
+            $table.append(wordline);
+        }
+
+        $('#results').append($table);
+
+
+        $('#createform').hide();
+        $('#guessing').hide();
+        $('#startingform').hide();
+        $('#results').show();
+    }
+});

+ 6 - 157
static/index.html

@@ -2,162 +2,8 @@
 <meta charset="utf-8" />
 <html>
 <head>
-    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
-    <script language="javascript" type="text/javascript">
-        $(function() {
-            var connection = null;
-
-            var wordlist = null;
-            var questionlist = null;
-
-            $('#join').click(function() {
-                var game_id = $('#gameId').val();
-                var nick = $('#nick').val();
-                var msg = {
-                    join: {
-                        game_id: game_id,
-                        nick: nick,
-                    }
-                };
-                connect(msg);
-            });
-
-            $('#create').click(function() {
-                var game_id = $('#gameId').val();
-                var nick = $('#nick').val();
-                var msg = {
-                    create_game: {
-                        game_id: game_id,
-                        nick: nick,
-                    }
-                };
-                connect(msg);
-            });
-
-            $('#ready').click(function() {
-                var game_id = $('#gameId').val();
-                var nick = $('#nick').val();
-                var msg = "ready";
-                send(msg);
-            });
-
-            $('#submit').click(function() {
-                var word = $('#word').val();
-                var msg = {
-                    submit_word: {
-                        word: word
-                    }
-                };
-                send(msg);
-            });
-
-            $('#submitGuess').click(function() {
-                var list = [];
-                for(var i = 0; i < wordlist.length; i++) {
-                    var number = parseInt($("g" + i).val());
-                    if (number == NaN) {
-                        $("#status").html("Please enter a valid number");
-                        return;
-                    }
-                    else if (number > 0 && number <= questionlist.length) {
-                        list.push([wordlist[i], questionlist[number - 1]]);
-                    }
-                }
-                var msg = {
-                    submit_guess: {
-                        guesses: list
-                    }
-                };
-                send(msg);
-            });
-
-            function connect(initial_message) {
-                if (connection != null) {
-                    disconnect();
-                }
-                var uri = 'ws://' + window.location.host + '/ws/';
-                connection = new WebSocket(uri);
-
-                connection.onopen = function() {
-                    connection.send(JSON.stringify(initial_message));
-                };
-                connection.onmessage = function(e) {
-                    onReceive(e);
-                };
-                connection.onclose = function() {
-                };
-            }
-
-            function send(message) {
-                if (connection != null) {
-                    connection.send(JSON.stringify(message));
-                }
-            }
-
-            function disconnect() {
-                connection.close();
-                connection = null;
-            }
-
-            function onReceive(msg) {
-                var obj = jQuery.parseJSON(msg.data);
-                if (obj.game_not_found != null) {
-                    $('#status').html("Game \"" + obj.game_not_found.game_id + "\" not found");
-                }
-                else if (obj.game_already_exists != null) {
-                    $('#status').html("Game \"" + obj.game_already_exists.game_id + "\" already exists");
-                }
-                else if (obj.game_state != null) {
-                    var gs = obj.game_state;
-                    if (gs.state_data === "starting") {
-                        $('#startingform').show();
-                    }
-                    else 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);
-
-                        var creating = gs.state_data.creating;
-                        var chars = creating.available_chars;
-                        $('#question').val(creating.question);
-                        $('#letters').val(chars.join());
-                        $('#createform').show();
-                    }
-                    else if (gs.state_data.guessing != null) {
-                        var guesses = gs.state_data.guessing;
-                        var sub_words = guesses.submitted_words;
-                        var questions = guesses.questions;
-                        var questionsHtml = "";
-                        for (var i = 0; i < questions.length; i++) {
-                            questionsHtml += (i + 1) + ": " + questions[i] + "<br>";
-                        }
-                        $('#guessingDynTable').html(questionsHtml);
-                        $('#guessingDyn').html("");
-                        for (var i = 0; i < sub_words.length; i++) {
-                            var $label = $("<label to='g" + i + "'>" + sub_words[i][0] + "</label>");
-                            var $field = $("<input name='g" + i + "' type='text' /><br>");
-                            $('#guessingDyn').append($label);
-                            $('#guessingDyn').append($field);
-                        }
-
-                        questionlist = questions;
-                        wordlist = sub_words.map(pair => pair[0]);
-                        
-                        $('#createform').hide();
-                        $('#guessing').show();
-                    }
-                }
-                else {
-                    $('#status').html("Unknown Message recieved");
-                }
-            }
-        });
-    </script>
+    <script src="jquery-3.5.1.js"></script>
+    <script src="comm.js"></script>
 </head>
 <body>
 <form id="loginform">
@@ -185,13 +31,16 @@
     You now have to guess!
     <div id="guessingDynTable">
     </div>
- 
+
     <form id="guessingform">
         <div id="guessingDyn">
         </div>
         <input id="submitGuess" type="button" value="Submit Guess" />
     </form>
 </div>
+<div id="results" style="display:none">
+
+</div>
 <div id="status">
 </div>
 </body>

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1 - 0
static/jquery-3.5.1.js


برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است