/// <summary> /// Starts a new boggle game once a second player has joined and the first player has not left. /// </summary> /// <param name="two">The second player.</param> /// <param name="time">The number of seconds the game will last.</param> /// <param name="letters">A string of 16 letters used for the boggle board. If left empty, a random board is created.</param> /// <param name="dictionary">A reference to the set of legal words.</param> public void startGame(Player two, int time, string letters, ref HashSet<string> dictionary) { gameIsRunning = true; this.player2 = two; // Create the board. if (letters == "") board = new BoggleBoard(); else board = new BoggleBoard(letters); this.dictionary = dictionary; commonWords = new HashSet<string>(); // Send START messages to the clients, and begin listening for words. player1.ss.BeginSend("START " + board.ToString() + " " + time.ToString() + " " + player2.name + "\n", (ee, pp) => { }, player1.ss); player2.ss.BeginSend("START " + board.ToString() + " " + time.ToString() + " " + player1.name + "\n", (ee, pp) => { }, player2.ss); player2.ss.BeginReceive(WordReceived, player2); // Start the game timer. Thread timer = new Thread(updateClock); timer.Start(time); }
/// <summary> /// Starts a new boggle game once a second player has joined and the first player has not left. /// </summary> /// <param name="two">The second player.</param> /// <param name="time">The number of seconds the game will last.</param> /// <param name="letters">A string of 16 letters used for the boggle board. If left empty, a random board is created.</param> /// <param name="dictionary">A reference to the set of legal words.</param> public void startGame(Player two, int time, string letters, ref HashSet <string> dictionary) { gameIsRunning = true; timeLimit = time; this.player2 = two; // Create the board. if (letters == "") { board = new BoggleBoard(); } else { board = new BoggleBoard(letters); } this.dictionary = dictionary; commonWords = new HashSet <string>(); // Send START messages to the clients, and begin listening for words. player1.ss.BeginSend("START " + board.ToString() + " " + time.ToString() + " " + player2.name + "\n", (ee, pp) => { }, player1.ss); player2.ss.BeginSend("START " + board.ToString() + " " + time.ToString() + " " + player1.name + "\n", (ee, pp) => { }, player2.ss); player2.ss.BeginReceive(WordReceived, player2); // Start the game timer. Thread timer = new Thread(updateClock); timer.Start(time); }
public void BoggleUniqueWordCount() { var english = new HashSet <string> { "cat", "cow", "car", "arc", "tack", "tap", "crass", "rat", "caw", "carat", "tar" }; var threeBoard = new BoggleBoard(3); var chars = new List <char> { 'c', 'a', 't', 'o', 'r', 'f', 'w', 'a', 'c' }; threeBoard.Initialize(chars); var count = 0; var strings = new HashSet <string>(); threeBoard.ApplyAllCombinations((string word) => { if (!english.Contains(word)) { return(""); } count++; strings.Add(word); return(word); }); Assert.AreEqual(8, count); Assert.AreEqual(7, strings.Count); }
private Board CreateBoard(BoggleBoard boggleBoard) { Board board = new Board(); // Flatten the board matrix into a single-dimension list List <Letter> letters = new List <Letter>(); for (int y = 0; y < boggleBoard.BoardSize; y++) { for (int x = 0; x < boggleBoard.BoardSize; x++) { letters.Add(new Letter { X = x, Y = y, C = boggleBoard.Letters[x, y] }); } } // Loop over the letters and identify the adjacent letters for (int i = 0; i < letters.Count; i++) { Letter letter = letters[i]; letter.AdjacentLetters = GetAdjacentIndexes(i, boggleBoard.BoardSize).Select(x => letters[x]).ToList(); } board.Letters = letters; return(board); }
protected async void OnGameOver() { BoggleBoard.GameOver(); await DisableInput(); _roomStatus = RoomStatus.Initialized; StateHasChanged(); }
public void BoggleCombinations() { var twoBoard = new BoggleBoard(2); var chars = new List <char> { 'h', 'o', 'e', 'l' }; twoBoard.Initialize(chars); var count = 0; var strings = new List <string>(); twoBoard.ApplyAllCombinations((string word) => { count++; strings.Add(word); return(word); }); Assert.AreEqual(28, count); Assert.AreEqual(count, strings.Count); Assert.AreEqual(count, strings.Distinct().Count()); var threeBoard = new BoggleBoard(3); chars = new List <char> { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }; threeBoard.Initialize(chars); count = 0; strings = new List <string>(); threeBoard.ApplyAllCombinations((string word) => { count++; strings.Add(word); return(word); }); Assert.AreEqual(653, count); Assert.AreEqual(count, strings.Count); Assert.AreEqual(count, strings.Distinct().Count()); var fourBoard = new BoggleBoard(4); chars = new List <char> { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' }; fourBoard.Initialize(chars); count = 0; strings = new List <string>(); fourBoard.ApplyAllCombinations((string word) => { count++; strings.Add(word); return(word); }); Assert.AreEqual(28512, count); Assert.AreEqual(count, strings.Count); Assert.AreEqual(count, strings.Distinct().Count()); //var fiveBoard = new BoggleBoard(5); //chars = new List<char> { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y' }; //fiveBoard.Initialize(chars); //count = 0; //strings = new List<string>(); //fiveBoard.ApplyAllCombinations((string word) => { count++; strings.Add(word); return word; }); //Assert.AreEqual(3060417, count); //Assert.AreEqual(count, strings.Count); //Assert.AreEqual(count, strings.Distinct().Count()); }
static void Main(string[] args) { const int boardSize = 5; BoggleBoard board = new BoggleBoard(boardSize: boardSize); Console.WriteLine("Board:"); Console.WriteLine(board); Console.WriteLine("Press any key to exit. "); Console.ReadKey(); }
private async Task InitializeRoom(RoomViewModel room) { this.room = room; if (room.GameStatus == RoomStatus.PlayMode) { BoggleBoard.Peek(room); inputDisabled = false; StateHasChanged(); } await Api.UsersInRoom(RoomId); //UsersInRoom(); }
private List <string> GetAllDictionaryWords(BoggleBoard board) { // Ignore board, just try every word in dictionary Hashtable wordHashtable = BoggleRules.Instance.GetWordDictionary().BaseWords; List <string> words = new List <string>(); foreach (Word word in wordHashtable.Values) { words.Add(word.Text); } return(words); }
private IEnumerable <string> EnumerateWords(BoggleBoard boggleBoard) { // Create structure to manage adjacent letters Board board = CreateBoard(boggleBoard); // Find all the words WordBuilder builder = new WordBuilder(); foreach (string word in EnumerateWords(board.Letters, builder)) { yield return(word); } }
public void BoggleAccessLetters() { var board = new BoggleBoard(3); var chars = new List <char> { 'h', 'e', 'l', 't', 'o', 'l', 'a', 'c', 'c' }; board.Initialize(chars); for (var i = 0; i < chars.Count; i++) { Assert.AreEqual(chars[i], board.GetChar(i / 3, i % 3)); Assert.AreEqual(chars[i], board.GetChar(new Point <int>(i / 3, i % 3))); } }
/// <summary> /// overload for user specified board with preset dice results. /// </summary> /// <param name="_p1Sock"> player one's socket (ss)</param> /// <param name="_p2Sock">player two's socket (ss)</param> /// <param name="_time">the game time</param> /// <param name="boardLetters">the optional string params for the console running emacs stuff</param> public game(BoggleServer _parent,Tuple<StringSocket, string> _p1Sock, Tuple<StringSocket, string> _p2Sock, int _time, string boardLetters) { parent = _parent; player1 = new player(_p1Sock.Item1, _p1Sock.Item2); player2 = new player(_p2Sock.Item1, _p2Sock.Item2); time = _time; board = new BoggleBoard(boardLetters); secondsTimer = new Timer(1000); common = new HashSet<string>(); processingKey = new object(); StartGame(); }
/// <summary> /// Given a board configuration, returns all the valid words. /// </summary> private static List <string> AllValidWords(string board) { BoggleBoard bb = new BoggleBoard(board); List <string> validWords = new List <string>(); foreach (string word in dictionary) { if (word.Length > 2 && bb.CanBeFormed(word)) { validWords.Add(word); } } return(validWords); }
public void BoggleExceptions() { Assert.ThrowsException <ArgumentException>(() => new BoggleBoard(-1)); Assert.ThrowsException <ArgumentException>(() => new BoggleBoard(0)); Assert.ThrowsException <ArgumentException>(() => new BoggleBoard(1)); var board = new BoggleBoard(2); IList <char> chars = null; Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); chars = new List <char>(); Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); Assert.ThrowsException <InvalidOperationException>(() => board.GetChar(0, 0)); chars.Add('a'); Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); Assert.ThrowsException <InvalidOperationException>(() => board.GetChar(0, 0)); chars.Add('d'); Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); chars.Add('d'); Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); Assert.ThrowsException <InvalidOperationException>(() => board.GetChar(0, 0)); chars.Add('d'); board.Initialize(chars); Assert.AreEqual('a', board.GetChar(0, 0)); chars.Add('a'); Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); chars = new List <char> { '1', 'a', 'b', 'd' }; Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); chars = new List <char> { '@', 'a', 'b', 'd' }; Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); chars = new List <char> { '\n', 'a', 'b', 'd' }; Assert.ThrowsException <ArgumentException>(() => board.Initialize(chars)); Assert.ThrowsException <IndexOutOfRangeException>(() => board.GetChar(-1, 0)); Assert.ThrowsException <IndexOutOfRangeException>(() => board.GetChar(0, -1)); Assert.ThrowsException <IndexOutOfRangeException>(() => board.GetChar(board.Size, 0)); Assert.ThrowsException <IndexOutOfRangeException>(() => board.GetChar(0, board.Size)); }
protected override async Task OnInitializedAsync() { Api.OnUsersInRoom((users) => { usersInGroup.Clear(); usersInGroup.AddRange(users); StateHasChanged(); }); Api.OnShuffled(async(onshuffledResponse) => { await BoggleBoard.InitializeBoard(onshuffledResponse.Letters); OnShuffled(onshuffledResponse.RoomStatus); }); Api.OnTimeLeft((timeRemained) => { GameTicker.WriteRemainingTime(int.Parse(timeRemained)); }); user = await UserContext.GetUser(); username = user?.Username; if (user == null || string.IsNullOrEmpty(user?.Username)) { NavigationManager.NavigateToIndex(); } else { if (!Api.IsConnected) { await Api.JoinRoom(user.Id, room.Id, true); } var roomResult = await Api.GetRoom(user.Id, RoomId); if (roomResult.IsValid) { await InitializeRoom(roomResult.Value); StateHasChanged(); } else { NavigationManager.NavigateToIndex(); } } }
/// <summary> /// Constructs a new game of boggle. /// </summary> /// <param name="validWords"></param> /// <param name="gameLength"></param> /// <param name="gameBoard"></param> public BoggleGame(SortedSet <string> validWords, int gameLength, BoggleBoard gameBoard) { legalWords = validWords; duration = gameLength; board = gameBoard; player1Name = null; player2Name = null; player1Score = 0; player2Score = 0; p1Illegal = new HashSet <string>(); p2Illegal = new HashSet <string>(); p1Legal = new HashSet <string>(); p2Legal = new HashSet <string>(); }
public void Solve(BoggleBoard boggleBoard) { Console.WriteLine("Board:\n{0}", boggleBoard); foreach (string word in EnumerateWords(boggleBoard)) { // QUESITON: What happens if a word is duplicated on the board? int score = BoggleServer.Instance.Score(Id, boggleBoard.Id, word); if (score >= 1) { Console.WriteLine("{0,4:+#;-#;0}: {1}", score, word); } } Console.WriteLine(); }
public void BoggleNeighbors() { var board = new BoggleBoard(3); var chars = new List <char> { 'h', 'e', 'l', 't', 'o', 'l', 'a', 'c', 'c' }; board.Initialize(chars); for (var i = 0; i < board.Size * board.Size; i++) { var x = i / board.Size; var y = i % board.Size; var thisPoint = new Point <int>(x, y); IList <Point <int> > neighbors = board.NeighborsOf(thisPoint); var above = new Point <int>(x - 1, y); var below = new Point <int>(x + 1, y); var left = new Point <int>(x, y - 1); var right = new Point <int>(x, y + 1); foreach (var position in new List <Point <int> > { above, below, left, right }) { var contained = board.Contains(position); if (position.X >= 0 && position.X < board.Size && position.Y >= 0 && position.Y < board.Size) { Assert.IsTrue(contained); } else { Assert.IsFalse(contained); } if (contained) { Assert.IsTrue(neighbors.Contains(position)); } else { Assert.IsFalse(neighbors.Contains(position)); } } } }
/// <summary> /// This is a seven parameter constructor for the Game class. /// </summary> /// <param name="player1Name"> The name passed by Player 1</param> /// <param name="player2Name"> The name passed by Player 2</param> /// <param name="p1Socket"> The Client socket for Player 1</param> /// <param name="p2Socket"> The Client socket for Player 2</param> /// <param name="wordDictionary"> The dictionary of legal words contained in a hash set</param> /// <param name="gameTime"> The amount of Game Time that the game is going to go. </param> /// <param name="gameBoard"> A game board that is specified by the server when it is created</param> public Game(string player1Name, string player2Name, StringSocket p1Socket, StringSocket p2Socket, HashSet <string> wordDictionary, int gameTime, string gameBoard) { // player 1 and player 2 names are set to the names that were passed p1Name = player1Name; p2Name = player2Name; // Player scores are initialized to 0 p1Score = 0; p2Score = 0; // Time is set to the game time passed time = gameTime; timeGame = gameTime; // Legal Dictionary is set to the word dictionary that was passed. All words // are converted into ToLower form legalDictionary = new HashSet <string>(); foreach (string word in wordDictionary) { legalDictionary.Add(word.ToLower()); } // Sockets are set to the sockets that were passed p1 = p1Socket; p2 = p2Socket; // Board is created using the letters passed to the game class board = new BoggleBoard(gameBoard); // Hash sets are initialized for all the word lists that need to be updated as they change p1Words = new HashSet <string>(); p2Words = new HashSet <string>(); playedWords = new HashSet <string>(); p1Illegal = new HashSet <string>(); p2Illegal = new HashSet <string>(); // Start message is sent to both of the clients to start the game p1.BeginSend("START " + board.ToString() + " " + gameTime + " " + player2Name + "\n", (a, b) => { }, null); p2.BeginSend("START " + board.ToString() + " " + gameTime + " " + player1Name + "\n", (a, b) => { }, null); // Countdown is started on a new thread. System.Threading.ThreadPool.QueueUserWorkItem(func => gameTimeCountdown()); }
public void Solve(BoggleBoard board) { Console.WriteLine("Board:\n{0}", board); //List<string> words = GetAllDictionaryWords(board); List <string> words = GetPresolvedWords(board, RandomSeed); foreach (string word in words) { int score = BoggleServer.Instance.Score(Id, board.Id, word); if (score >= 1) { Console.WriteLine("{0,4:+#;-#;0}: {1}", score, word); } } Console.WriteLine(); }
/// <summary> /// This is a 6 parameter constructor for the Game class. It does not take in a predefined board. /// </summary> /// <param name="player1Name"> The name passed by Player 1</param> /// <param name="player2Name"> The name passed by Player 2</param> /// <param name="p1Socket"> The Client socket for Player 1</param> /// <param name="p2Socket"> The Client socket for Player 2</param> /// <param name="wordDictionary"> The dictionary of legal words contained in a hash set</param> /// <param name="gameTime"> The amount of Game Time that the game is going to go. </param> public Game(string player1Name, string player2Name, StringSocket p1Socket, StringSocket p2Socket, HashSet <string> wordDictionary, int gameTime) { // Player 1 and player 2 usernames are set to the usernames passed p1Name = player1Name; p2Name = player2Name; // Player 1 and player 2 scores are set to 0 p1Score = 0; p2Score = 0; // Time is sent to the gametime that was passed to the server time = gameTime; timeGame = gameTime; // Legal Dictionary is set to the word dictionary that was passed. All words // are converted into ToLower form legalDictionary = new HashSet <string>(); foreach (string word in wordDictionary) { legalDictionary.Add(word.ToLower()); } // player1 and player2 sockets are set to the client sockets that were passed p1 = p1Socket; p2 = p2Socket; // Board is created with a random set of letters board = new BoggleBoard(); // Hash sets are initialized p1Words = new HashSet <string>(); p2Words = new HashSet <string>(); playedWords = new HashSet <string>(); p1Illegal = new HashSet <string>(); p2Illegal = new HashSet <string>(); // Start command is sent to both of the clients p1.BeginSend("START " + board.ToString() + " " + gameTime + " " + player2Name + "\n", (a, b) => { }, false); p2.BeginSend("START " + board.ToString() + " " + gameTime + " " + player1Name + "\n", (a, b) => { }, false); // Countdown is started on a new thread System.Threading.ThreadPool.QueueUserWorkItem(func => gameTimeCountdown()); }
/// <summary> /// New game helper. Adds first player to game and then returns the Game ID /// </summary> private string NewGame(Player p) { if (p == null) { SetResponse("NF"); return(null); } SetResponse("Success"); Guid gameToken = Guid.NewGuid(); BoggleBoard b = new BoggleBoard(); Dictionary <string, int> player1w = new Dictionary <string, int>(); Dictionary <string, int> player2w = new Dictionary <string, int>(); //Creates a game in waiting for Player 1 Game game = new Game(gameToken.ToString(), "Waiting", p, b.ToString(), player1w, player2w); Games.Add(gameToken.ToString(), game); return(gameToken.ToString()); }
/// <summary> /// Creates a new GameSession, given the first player to join, /// the second player to join and a specific BoggleBoard to use. /// </summary> /// <param name="p1">The first player to join</param> /// <param name="p2">The second player to join</param> /// <param name="board">A BoggleServer Board consisting of 16 letters</param> public GameSession(Player p1, Player p2, BoggleBoard board, int seconds, HashSet <string> dictionary) { String debugMsg = "Starting GameSession " + p1.Name + " and " + p2.Name; System.Diagnostics.Debug.WriteLine(debugMsg); scoreLock = new Object(); Player1 = p1; Player2 = p2; secondsLeft = seconds; Board = board; this.dictionary = dictionary; sendGreeting(); //Start receiving information Player1.Socket.BeginReceive(wordPlayed, Player1); Player2.Socket.BeginReceive(wordPlayed, Player2); //Start the countdown in its own thread. ThreadPool.QueueUserWorkItem((x) => startCountdown()); }
/// <summary> /// Constructor for a new game of boggle /// </summary> /// <param name="playerOne"></param> /// <param name="playerTwo"></param> /// <param name="gameLength"></param> /// <param name="initialBoardSetup"></param> /// <param name="legalWordsDictionary"></param> public Game(Player playerOne, Player playerTwo, int gameLength, string initialBoardSetup, HashSet <string> legalWordsDictionary) { //Initialize the game. if (ReferenceEquals(initialBoardSetup, null)) { board = new BoggleBoard(); } else { board = new BoggleBoard(initialBoardSetup); } this.playerOne = playerOne; this.playerTwo = playerTwo; this.timeRemaining = gameLength; this.timer = new System.Timers.Timer(1000); timer.Elapsed += OnTimedEvent; timer.AutoReset = true; this.dictionary = legalWordsDictionary; this.commonWords = new HashSet <string>(); }
/// <summary> /// Given a board configuration, returns all the valid words. /// </summary> private static IList <string> AllValidWords(string board) { ISet <string> dictionary = new HashSet <string>(); using (StreamReader words = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"/dictionary.txt")) { string word; while ((word = words.ReadLine()) != null) { dictionary.Add(word.ToUpper()); } } BoggleBoard bb = new BoggleBoard(board); List <string> validWords = new List <string>(); foreach (string word in dictionary) { if (bb.CanBeFormed(word)) { validWords.Add(word); } } return(validWords); }
public async Task Shuffle() { bool forceReload = _roomStatus == RoomStatus.PlayMode; await BoggleBoard.Shuffle(forceReload); }
/// <summary> /// Constructor. Also sends players the information regarding the game ("START", game duration, and opponent's name) /// </summary> /// <param name="playerA">Player</param> /// <param name="playerB">Player</param> /// <param name="duration">Game Length</param> /// <param name="lettersOnBoard">16 Letters used for Board</param> /// <param name="dictionary">Dictionary used for Game</param> public Game(Player playerA, Player playerB, int duration, string lettersOnBoard, HashSet<string> dictionary) { if (lettersOnBoard == null) _bb = new BoggleBoard(); else _bb = new BoggleBoard(lettersOnBoard); _playerA = playerA; _playerB = playerB; _gameDuration = duration; _dictionary = dictionary; _commonWords = new SortedSet<string>(); SendMessage(_playerA, "START " + _bb.ToString() + " " + duration + " " + _playerB.PlayerName + "\n"); SendMessage(_playerB, "START " + _bb.ToString() + " " + duration + " " + _playerA.PlayerName + "\n"); TimeAndScoreUpdater timeAndScoreUpdater = new TimeAndScoreUpdater(_gameDuration); _playerA.MyGame = this; _playerB.MyGame = this; _playerA.PlayingGame = true; _playerB.PlayingGame = true; _gameClock = new Timer(timeAndScoreUpdater.UpdateTime, this, 0, 1000); _playerA.SS.BeginReceive((string s, Exception e, object p) => IncomingWordsCallBackPlayer(s, e, p, _playerA, _playerB), null); _playerB.SS.BeginReceive((string s, Exception e, object p) => IncomingWordsCallBackPlayer(s, e, p, _playerB, _playerA), null); }
private List <string> GetPresolvedWords(BoggleBoard board, int randomSeed) { if (randomSeed != 1) { throw new NotSupportedException("These words are only valid for the board with random seed = 1"); } return(new List <string> { "emir", "idem", "same", "lame", "salvo", "edit", "ilia", "omit", "pilot", "soma", "tide", "aloft", "some", "amide", "sift", "lift", "trim", "flam", "alto", "media", "lamed", "SALT", "Milt", "hilt", "film", "flirt", "Diem", "idea", "Palm", "alias", "Pail", "sail", "mail", "flap", "limit", "tried", "lied", "Ride", "hide", "limo", "maid", "demo", "toil", "moil", "foil", "flip", "aide", "rime", "time", "lime", "dime", "flit", "email", "dirt", "asap", "loft", "malt", "soap", "volt", "heir", "emit", "Alma", "demit", "molt", "amid", "flame", "lama", "diam" }); }
private GameToken joinGameQuery(Player p) { string queryGameToken = ""; /////Query for asking if the user is in the Users Table MySqlConnection conn = new MySqlConnection(connectionString); TransactionQuery TQ = new TransactionQuery(conn); TQ.addCommand("select count(*) from users where UserToken=?UserToken"); TQ.addParms(new string[] { "UserToken" }, new string[] { p.userToken }); TQ.addReadParms(new string[] { "count(*)" }, new bool[] { true }); TQ.addConditions((result, command) => { if (result.Dequeue().Equals("0")) { SetResponse("player"); return(false); } else { return(true); } }); TQ.addCommand("select count(*) from games where GameState=?GameState"); TQ.addParms(new string[] { "GameState" }, new string[] { "waiting" }); TQ.addReadParms(new string[] { "count(*)" }, new bool[] { true }); TQ.addConditions((result, command) => { if (result.Dequeue() == "0") { queryGameToken = Guid.NewGuid().ToString(); command.CommandText = "insert into games (GameToken, Player1Token, GameState)" + "values(?gameToken, ?UserToken,?GameState)"; command.Parameters.AddWithValue("gameToken", queryGameToken); //Execute Query if (command.ExecuteNonQuery() == 0) { throw new Exception("Did not insert player into new game"); } return(false); } else { return(true); } }); TQ.addCommand("select GameToken, Player1Token from games where GameState=?GameState"); TQ.addParms(new string[] {}, new string[] {}); TQ.addReadParms(new string[] { "GameToken", "Player1Token" }, new bool[] { false, true }); TQ.addConditions((result, command) => { queryGameToken = result.Dequeue(); if (result.Dequeue() == p.userToken) { SetResponse("same"); //409 Conflict Response(player already in game) return(false); } else { command.CommandText = "update games set GameState = ?gs where GameToken = ?gt"; command.Parameters.AddWithValue("gs", "playing"); command.Parameters.AddWithValue("gt", queryGameToken); if (command.ExecuteNonQuery() == 0) { throw new Exception("update gamestate failed"); } BoggleBoard b; if (String.IsNullOrEmpty(initial)) { b = new BoggleBoard(initial); } else { b = new BoggleBoard(); } command.CommandText = "insert into pairedGames (GameToken, Player2Token, Score1, Score2, Board, Duration, StartTime)" + " values(?gt, ?Player2Token, 0, 0, ?Board, 0, ?StartTime)"; command.Parameters.AddWithValue("Player2Token", p.userToken); command.Parameters.AddWithValue("Board", b.ToString()); command.Parameters.AddWithValue("StartTime", DateTime.Now.ToString()); if (command.ExecuteNonQuery() == 0) { throw new Exception("update gamestate failed"); } return(true); } }); if (!TQ.Transaction()) { SetResponse("ISE"); return(null); } return(new GameToken() { gameToken = queryGameToken }); }
public int PutPlayWord([FromUri] string gameID, PutWordRequest request) { // Check for all of the possible errors that could occur according to the API string UserToken = request.UserToken; string Word = request.Word.ToUpper(); BoggleBoard currentBoard; // Can't have a null word. if (Word == null) { throw new HttpResponseException(HttpStatusCode.Forbidden); } // Can't have no word or a word that's too long. else if (Word.Trim().Length == 0 || Word.Trim().Length > 30) { throw new HttpResponseException(HttpStatusCode.Forbidden); } // Start the process for querying the SQL database. using (SqlConnection conn = new SqlConnection(DBConnection)) { conn.Open(); using (SqlTransaction trans = conn.BeginTransaction()) { //Checks if the User is even registered in Users using (SqlCommand checkValidRegistration = new SqlCommand("SELECT Nickname from Users where UserID = @UserID", conn, trans)) { checkValidRegistration.Parameters.AddWithValue("@UserID", UserToken); using (SqlDataReader readResult = checkValidRegistration.ExecuteReader()) { readResult.Read(); if (!readResult.HasRows) { throw new HttpResponseException(HttpStatusCode.Forbidden); } } } //Checks if the UserID is Player1 or Player2 in a game that matches the GameID and if the game is pending. using (SqlCommand checkUserInGame = new SqlCommand("SELECT Player1, Player2 from Games WHERE GameID = @GameID", conn, trans)) { checkUserInGame.Parameters.AddWithValue("@GameID", gameID); using (SqlDataReader readResult = checkUserInGame.ExecuteReader()) { while (readResult.Read()) { // If the reader doesn't have any rows, then the game ID isn't valid. if (!readResult.HasRows) { throw new HttpResponseException(HttpStatusCode.Forbidden); } // If the user token isn't either player, they can't play a word. else if (!(readResult.GetString(0).Equals(UserToken) || readResult.GetString(1).Equals(UserToken))) { throw new HttpResponseException(HttpStatusCode.Forbidden); } } } } // Check to see if the game is actually active, completed, or pending. using (SqlCommand getGameStatus = new SqlCommand("SELECT StartTime, TimeLimit FROM Games WHERE GameID = @GameID AND Player2 IS NOT NULL", conn, trans)) { getGameStatus.Parameters.AddWithValue("@GameID", gameID); using (SqlDataReader readGameStatus = getGameStatus.ExecuteReader()) { readGameStatus.Read(); // If the reader doesn't have rows, the game is pending, as there isn't a // second player. if (!readGameStatus.HasRows) { throw new HttpResponseException(HttpStatusCode.Conflict); } // If the time left is less than zero, the game is completed and no new // words can be played. int timeLeft = computeTimeLeft(readGameStatus.GetDateTime(0), readGameStatus.GetInt32(1)); if (timeLeft < 0) { throw new HttpResponseException(HttpStatusCode.Conflict); } } } //Gets the game's board using (SqlCommand getGameBoard = new SqlCommand("SELECT Board from Games where GameID = @GameID", conn, trans)) { getGameBoard.Parameters.AddWithValue("@GameID", gameID); using (SqlDataReader readResult = getGameBoard.ExecuteReader()) { readResult.Read(); if (!readResult.HasRows) { throw new DatabaseException("It should never hit this since the last SQLCommand checked if the User was in a game. You messed up you twig."); } else { currentBoard = new BoggleBoard(readResult.GetString(0)); } } } WordAndScore wordBeingPlayed = new WordAndScore() { Word = Word }; // If the word isn't in the dictionary, or can't be played on the board, it's score // should be negative one. // TODO: POSSIBLE SCORING BUG. KEEP AN EYE ON IT if (Word.Length > 2 && (!dictionary.Contains(Word) || !currentBoard.CanBeFormed(Word))) { wordBeingPlayed.Score = -1; } else { // Otherwise, assign a point value to the word based on its length. switch (Word.Length) { case 1: case 2: wordBeingPlayed.Score = 0; break; case 3: case 4: wordBeingPlayed.Score = 1; break; case 5: wordBeingPlayed.Score = 2; break; case 6: wordBeingPlayed.Score = 3; break; case 7: wordBeingPlayed.Score = 5; break; default: wordBeingPlayed.Score = 11; break; } } // Tests to see if the user has already played this word in the current game. using (SqlCommand testIfPlayedWord = new SqlCommand("SELECT Score FROM Words WHERE Player = @Player AND Word = @Word AND GameID = @GameID", conn, trans)) { testIfPlayedWord.Parameters.AddWithValue("@Player", UserToken); testIfPlayedWord.Parameters.AddWithValue("@Word", Word); testIfPlayedWord.Parameters.AddWithValue("@GameID", gameID); if (testIfPlayedWord.ExecuteScalar() != null) { wordBeingPlayed.Score = 0; } } using (SqlCommand playWord = new SqlCommand("INSERT INTO Words (Word, GameID, Player, Score) VALUES (@Word, @GameID, @Player, @Score)", conn, trans)) { playWord.Parameters.AddWithValue("@Word", wordBeingPlayed.Word); playWord.Parameters.AddWithValue("@GameID", gameID); playWord.Parameters.AddWithValue("@Player", UserToken); playWord.Parameters.AddWithValue("@Score", wordBeingPlayed.Score); if (playWord.ExecuteNonQuery() != 1) { throw new DatabaseException("Failed to add the played word to the database."); } } trans.Commit(); return(wordBeingPlayed.Score); } } }
public BoggleServer(String letters, int seconds, string filepath) : this(seconds, filepath) { universalBoard = new BoggleBoard(letters); }
/// <summary> /// Constructor for a boggle game. Initializes the member variables and starts the game /// between two given sockets (player1 and player2). /// </summary> /// <param name="player1"></param> /// <param name="player2"></param> /// <param name="time"></param> /// <param name="filepath"></param> /// <param name="initBoard"></param> public BoggleGame(StringSocket player1, StringSocket player2, int time, string filepath, string initBoard) { //Initialize member variables this.player1 = player1; player1Name = player1.Name; this.player2 = player2; player2Name = player2.Name; p2Words = new HashSet<string>(); p2IllegalWords = new HashSet<string>(); p1Words = new HashSet<string>(); p1IllegalWords = new HashSet<string>(); commonWords = new HashSet<string>(); validWords = new HashSet<String>(); this.time = time; this.filepath = filepath; p1Score = 0; p2Score = 0; Console.WriteLine("Starting game between " + player1Name + " and " + player2Name); string line; // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader(filepath); while ((line = file.ReadLine()) != null) { //For each line in the file, add it to the valid words list validWords.Add(line); } //Close the file file.Close(); //Create the board, if given an initialization, then initialize the board, //otherwise create a random start if (initBoard != null) bb = new BoggleBoard(initBoard); else bb = new BoggleBoard(); //Send the START command to both players, showing the letters, time, and opponents name player1.BeginSend("START " + bb.ToString() + " " + time.ToString() + " " + player2.Name +"\n", (o, e) => { }, null); player2.BeginSend("START " + bb.ToString() + " " + time.ToString() + " " + player1.Name + "\n", (o, e) => { }, null); //Create a timer to keep track of the time with a 1 second interval System.Timers.Timer gameTimer = new System.Timers.Timer(1000); //Add the event handler to the timer gameTimer.Elapsed += new System.Timers.ElapsedEventHandler(gameTimer_Elapsed); //If we've run out of time if (time != 0) { //receive stuff from player 1 player1.BeginReceive(Player1Input, null); //receive stuff fromp player 2 player2.BeginReceive(Player2Input, null); } }
/// <summary> /// Takes a word and adds it to a players list while increasing their score in a game with a particular game ID /// Returns the words value /// </summary> public int?PlayWord(PlayWord w) { if (w == null) { SetResponse("NF"); return(null); } if (String.IsNullOrEmpty(w.playerToken)) { SetResponse("player"); //403 Forbidden Response(invalid player token) return(null); } if (String.IsNullOrEmpty(w.word)) { SetResponse("word"); //403 Forbidden Response(invalid player token) return(null); } if (String.IsNullOrEmpty(w.gameToken)) { SetResponse("gt"); //403 Forbidden Response (invalid game token) return(null); } SetResponse("Success"); int value = WordLookUp(w.word); Game game; if (Games.TryGetValue(w.gameToken, out game)) //Find game { BoggleBoard bb = new BoggleBoard(game.board); if (!bb.CanBeFormed(w.word)) //TODO check to make sure its not negative points { value = 0; } if (game.Player1.userToken == w.playerToken) //Check if player is Player1 { if (value > 0 || value < 1) //If word value is greater than 0 { if (!game.Player1Words.ContainsKey(w.word)) //If Players word list does not contain the word being played { game.Player1Words.Add(w.word, value); //Add it to player word list //game.Player1.wordsPlayed.Add(word, value); //Add to word to player words played list //WordListComparer(g.gameToken); //Check if Player lists are unique and removes like words } } } else if (game.Player2.userToken == w.playerToken) //Repeat previous if the player is player two { if (value > 0 || value < 1) { if (!game.Player2Words.ContainsKey(w.word)) { game.Player2Words.Add(w.word, value); //game.Player2.wordsPlayed.Add(word, value); //Add to words to word played //WordListComparer(g.gameToken); } } } else { SetResponse("player"); //403 Forbidden Response(invalid player token) return(null); } } return(value); }
private WordValue PlayWordQuery(PlayWord w) { //Create a Connection MySqlConnection conn = new MySqlConnection(connectionString); //CreateTransaction Query Object TransactionQuery TQ = new TransactionQuery(conn); int player = 0; ///Check for games with gametoken TQ.addCommand("select count(*) from games where GameToken = ?gameToken"); TQ.addParms(new string[] { "gameToken" }, new string[] { w.gameToken }); TQ.addReadParms(new string[] { "count(*)" }, new bool[] { true }); TQ.addConditions((result, command) => { if (result.Dequeue().Equals("0")) { SetResponse("gt"); return(false); } else { Queue <string> returnQ; TQ.injectComand("select Player1Token from games where GameToken = ?gameToken", new string[, ] { }, new string[] { "Player1Token" }, true, out returnQ); if (returnQ.Dequeue() == w.playerToken) { player = 1; } return(true); } }); bool status = true; string gameState = ""; ///Check if the gamestate is playing TQ.addCommand("select GameState from games where GameToken = ?gameToken"); TQ.addParms(new string[] { }, new string[] { }); TQ.addReadParms(new string[] { "GameState" }, new bool[] { true }); TQ.addConditions((result, command) => { gameState = result.Dequeue(); if (gameState.Equals("playing")) { return(true); } else if (player == 1) { SetResponse("waitingPlay"); status = false; return(false); } else { SetResponse("wrongStatus"); status = false; return(false); } }); string board; //Get the board and see if word can be played TQ.addCommand("select Player2Token, Board from pairedGames where GameToken = ?gameToken"); TQ.addParms(new string[] { }, new string[] { }); TQ.addReadParms(new string[] { "Player2Token", "Board" }, new bool[] { false, true }); TQ.addConditions((result, command) => { if (result.Dequeue() == w.playerToken) { player = 2; } board = result.Dequeue(); BoggleBoard b = new BoggleBoard(board); points = WordLookUp(w.word, board); if (player == 0) { SetResponse("player"); return(false); } return(true); }); int totalScore = 0; bool repeat = false; ///Check if word is already played TQ.addCommand("select count(Word) from words where GameToken = ?gameToken and PlayerToken = ?playerToken"); TQ.addParms(new string[] { "playerToken" }, new string[] { w.playerToken }); TQ.addReadParms(new string[] { "Count(Word)" }, new bool[] { true }); TQ.addConditions((result, command) => { command.CommandText = "select Word, Score from words where GameToken = ?gameToken and PlayerToken = ?playerToken"; if (command.ExecuteNonQuery() == 0) { throw new Exception("GET WORDS FAILED"); } using (MySqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { if (reader.GetString("Word") == w.word) { points = 0; } totalScore += Convert.ToInt32(reader.GetString("Score")); } } if (!repeat) { totalScore += points; command.CommandText = "update pairedGames set Score" + player + "=?Score where GameToken=?gameToken"; command.Parameters.AddWithValue("Score", totalScore); if (command.ExecuteNonQuery() == 0) { throw new Exception("Update player score failed"); } command.CommandText = "insert into words (GameToken, PlayerToken, Word, Score) values (?gameToken, ?pt, ?word, ?wordscore)"; command.Parameters.AddWithValue("pt", w.playerToken); command.Parameters.AddWithValue("word", w.word); command.Parameters.AddWithValue("wordscore", points); if (command.ExecuteNonQuery() == 0) { throw new Exception("insert word score failed"); } return(true); } else { return(false); } }); if (!TQ.Transaction()) { SetResponse("ISE"); return(null); } else { if (status) { return new WordValue() { wordScore = points } } ; else { return(null); } } }