64 Commits

Author SHA1 Message Date
Lars
9199265eb6 [TESTS] tests for the canvas 2020-10-23 23:45:52 +02:00
Lars
b1b03e136d Some tests 2020-10-23 23:26:31 +02:00
Sem van der Hoeven
5ac4b59e38 test 2020-10-23 22:25:50 +02:00
Sem van der Hoeven
3c1f1a0028 rename 2020-10-23 22:25:13 +02:00
Sem van der Hoeven
e7b40d7e64 [ADD] test 2020-10-23 22:23:08 +02:00
Sem van der Hoeven
27e70d1ec0 [FIX] tests?? 2020-10-23 22:04:36 +02:00
Sem van der Hoeven
0e6a2bab59 Merge branch 'master' of https://github.com/SemvdH/Csharp-eindproject 2020-10-23 21:14:26 +02:00
Sem van der Hoeven
125f4c0410 [ADD] added 2 test methods 2020-10-23 21:14:16 +02:00
Lars
b9b217622a Merge remote-tracking branch 'origin/master' 2020-10-23 21:07:27 +02:00
Lars
2d4540e28e [DELETED] something 2020-10-23 21:07:12 +02:00
Sem van der Hoeven
052f07db93 [ADD] added test project for real 2020-10-23 21:05:05 +02:00
Sem van der Hoeven
898b579ca9 Merge branch 'master' of https://github.com/SemvdH/Csharp-eindproject 2020-10-23 21:04:29 +02:00
Sem van der Hoeven
39ded8524b [ADD] added test project 2020-10-23 21:04:22 +02:00
Lars
398ba1d5bd [ADDED] other canvas can be reset via an other canvas 2020-10-23 21:04:14 +02:00
Sem van der Hoeven
8ca4efc296 stuff 2020-10-23 20:45:25 +02:00
Sem van der Hoeven
3015c0312f [FIX] fix double drawing 2020-10-23 20:33:47 +02:00
Lars
3c0f5018db [TRYING] 2020-10-23 20:26:05 +02:00
SemvdH
9558c75eab Merge pull request #14 from SemvdH/feature/guesedWord
[ADDITION] added a new property to the user (may be removed later on)…
2020-10-23 15:51:30 +02:00
Dogukan
ec08fbfced [ADDITION] added a new property to the user (may be removed later on), and made a check for the random word 2020-10-23 15:47:52 +02:00
SemvdH
87ebdeef58 Merge pull request #13 from SemvdH/feature/timer
Feature/timer
2020-10-23 15:45:12 +02:00
Sem van der Hoeven
bf09dba850 [ADD] added timer start on next round message receive 2020-10-23 15:44:18 +02:00
SemvdH
b14a7691b5 Merge pull request #12 from SemvdH/hotfix/fixClientServerComms
[FIX] Callbacks weren't properly called
2020-10-23 14:56:45 +02:00
Dogukan
7df48ab322 [FIX] Callbacks weren't properly called 2020-10-23 14:49:20 +02:00
Sem van der Hoeven
6512518fb7 [FIX] made first user in lobby a host if the host leaves 2020-10-23 14:30:16 +02:00
Sem van der Hoeven
80d970da35 [FIX] made login impossible if no name was entered 2020-10-23 14:13:22 +02:00
SemvdH
2c7bf3e217 Merge pull request #11 from SemvdH/setupBranch
merge Setup branch into master
2020-10-23 14:06:36 +02:00
SemvdH
92f57a87bc Merge pull request #10 from SemvdH/update-scores
added updating scores on lobby list receive
2020-10-23 13:59:28 +02:00
Sem van der Hoeven
da5528c7b2 added updating scores on lobby list receive 2020-10-23 13:58:44 +02:00
Lars
c16f7cf68f Merge branch 'master' into setupBranch 2020-10-23 13:11:56 +02:00
SemvdH
5c2dea3ab4 Merge pull request #9 from SemvdH/feature/playerList
Feature/player list
2020-10-23 12:53:43 +02:00
SemvdH
e2f9dfec78 Merge branch 'master' into feature/playerList 2020-10-23 12:53:35 +02:00
Dogukan
7fcf424b65 [FIX] fixed the async for updating the label, as well as the chat messages 2020-10-23 12:48:27 +02:00
Dogukan
97be0f937c [Cleanup] cleaned a null checking if-statement for the lobby id 2020-10-23 12:42:24 +02:00
Dogukan
09056818df Merge remote-tracking branch 'origin/feature/playerList' into feature/playerList 2020-10-23 12:33:06 +02:00
Dogukan
8d4f72c09d [CHANGED] Static function for handling to callbacks 2020-10-23 12:32:11 +02:00
Sem van der Hoeven
f51d310787 [EDIT] removed uneccesary call to updatelobbies 2020-10-23 12:31:01 +02:00
Sem van der Hoeven
9e829c47ff [FIX] lobbies now get correctly updated when someone leaves or joins 2020-10-23 12:26:31 +02:00
Lars
f5d55ef405 [FIX] randomword is not visible 2020-10-23 11:54:43 +02:00
Dogukan
0d44b2d840 [TRY] tried to bind the label data, doesn't work yet 2020-10-23 11:30:06 +02:00
Dogukan
1c04ab95c0 [ADDED] player list in lobby updates on join! Not on disconnect yet. Tried to set the word label doesn't work yet. 2020-10-22 23:54:07 +02:00
Sem van der Hoeven
ddf4594c5e [ADD] add canvas data sending on mouse up 2020-10-22 22:47:11 +02:00
Sem van der Hoeven
09f9e227b8 merge stuff 2020-10-22 22:35:29 +02:00
SemvdH
ec156f3dc6 Merge pull request #8 from SemvdH/stateful-canvas
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
2020-10-22 22:31:09 +02:00
SemvdH
0158841159 Merge branch 'master' into stateful-canvas 2020-10-22 22:30:42 +02:00
Sem van der Hoeven
8a490eb399 [FIX] AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 2020-10-22 22:22:24 +02:00
Sem van der Hoeven
5e408091cb the fuck????? 2020-10-22 22:04:20 +02:00
Lars
24eb43239b [FIX] nog when you click host, you are able to click the start game button 2020-10-22 22:02:41 +02:00
Lars
335d17838c Merge branch 'master' into setupBranch 2020-10-22 20:04:30 +02:00
Lars
242c435ac7 added something little, not that very important tho 2020-10-22 17:46:45 +02:00
Lars
eae05d17df [ADDED] Color can now we transfered, still need to get fixed with the buffer -_- 2020-10-22 17:30:40 +02:00
Sem van der Hoeven
d37696d4bd [FIX] made message sending statful 2020-10-22 17:11:55 +02:00
Sem van der Hoeven
4a400628df [FIX] merge stuff 2020-10-22 17:05:02 +02:00
SemvdH
9fa231ab00 Merge pull request #7 from SemvdH/fix-async-stuff
merge Fix async stuff into master
2020-10-22 17:02:30 +02:00
SemvdH
21ee724056 Merge pull request #6 from SemvdH/feature/jsonForWords
Feature/json for words
2020-10-22 17:01:41 +02:00
Sem van der Hoeven
eca17cc70f [FIX] handled disconnects for everything 2020-10-22 17:00:26 +02:00
Sem van der Hoeven
07b0357b0a Merge branch 'feature/jsonForWords' into fix-async-stuff 2020-10-22 16:37:05 +02:00
Sem van der Hoeven
d8bbaf5258 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 16:36:45 +02:00
Sem van der Hoeven
bb289865b7 [ADD] added message received ok 2020-10-22 16:34:31 +02:00
Sem van der Hoeven
f1878eaf25 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 16:16:08 +02:00
Lars
1fdba622cc Merge branch 'master' into setupBranch 2020-10-22 15:46:20 +02:00
Lars
cac0fdc0a4 [ADDED] lobby now secured when the game starts. start button is still for everyone available, not working yet 2020-10-22 15:40:09 +02:00
Sem van der Hoeven
674c4f1ba1 Merge branch 'feature/jsonForWords' of https://github.com/SemvdH/Csharp-eindproject into feature/jsonForWords 2020-10-22 13:55:49 +02:00
Sem van der Hoeven
d3bd1418d1 line 2020-10-22 13:55:46 +02:00
Lars
8190724f77 [ADDED] canvas data sending to the server works, but not fully yet to all the clients 2020-10-21 23:18:37 +02:00
25 changed files with 1153 additions and 271 deletions

View File

@@ -2,20 +2,35 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.IO;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Windows.Media;
using System.Windows;
using static SharedClientServer.JSONConvert; using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void LobbyCallback(int id);
public delegate void LobbyJoinCallback(bool isHost); public delegate void LobbyJoinCallback(bool isHost);
public delegate void RandomWord(string word);
public delegate void HandleIncomingMsg(string username, string msg);
internal delegate void HandleIncomingPlayer(Lobby lobby);
public delegate void CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset();
public delegate void LobbyCallback(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
private ClientData clientData = ClientData.Instance;
private TcpClient tcpClient; private TcpClient tcpClient;
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[2048];
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
public int Port = 5555; public int Port = 5555;
public bool Connected = false; public bool Connected = false;
@@ -24,9 +39,17 @@ namespace Client
public Callback OnLobbiesListReceived; public Callback OnLobbiesListReceived;
public LobbyJoinCallback OnLobbyJoinSuccess; public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public Callback OnServerDisconnect;
public Callback OnLobbyUpdate;
public LobbyCallback OnLobbyCreated; public LobbyCallback OnLobbyCreated;
public LobbyCallback OnLobbyLeave; public LobbyCallback OnLobbyLeave;
public RandomWord RandomWord;
public HandleIncomingMsg IncomingMsg;
public HandleIncomingPlayer IncomingPlayer;
private ClientData data = ClientData.Instance; private ClientData data = ClientData.Instance;
public CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset;
public HandleIncomingPlayer UpdateUserScores;
public Lobby[] Lobbies { get; set; } public Lobby[] Lobbies { get; set; }
public Client(string username) public Client(string username)
@@ -40,45 +63,63 @@ namespace Client
private void OnConnect(IAsyncResult ar) private void OnConnect(IAsyncResult ar)
{ {
Debug.Write("finished connecting to server"); Debug.Write("finished connecting to server");
this.tcpClient.EndConnect(ar); try
this.stream = tcpClient.GetStream(); {
OnSuccessfullConnect?.Invoke(); this.tcpClient.EndConnect(ar);
SendMessage(JSONConvert.ConstructUsernameMessage(username)); this.stream = tcpClient.GetStream();
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null); OnSuccessfullConnect?.Invoke();
OnLobbyUpdate = updateGameLobby;
SendMessage(JSONConvert.ConstructUsernameMessage(username));
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
}
catch (Exception e)
{
Debug.WriteLine("Can't connect, retrying...");
tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null);
}
} }
private void OnReadComplete(IAsyncResult ar) private void OnReadComplete(IAsyncResult ar)
{ {
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected) if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
return; return;
int amountReceived = stream.EndRead(ar); try
if (totalBufferReceived + amountReceived > 1024)
{ {
throw new OutOfMemoryException("buffer too small"); int amountReceived = stream.EndRead(ar);
if (totalBufferReceived + amountReceived > 2048)
{
throw new OutOfMemoryException("buffer too small");
}
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived;
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{
// we have received the complete packet
byte[] message = new byte[expectedMessageLength];
// put the message received into the message array
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
handleData(message);
totalBufferReceived -= expectedMessageLength;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
}
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} }
catch (IOException e)
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived;
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
while (totalBufferReceived >= expectedMessageLength)
{ {
// we have received the complete packet Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
byte[] message = new byte[expectedMessageLength]; OnServerDisconnect?.Invoke();
// put the message received into the message array
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
handleData(message);
totalBufferReceived -= expectedMessageLength;
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
} }
ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} }
private void handleData(byte[] message) private void handleData(byte[] message)
@@ -100,9 +141,14 @@ namespace Client
string textUsername = combo.Item1; string textUsername = combo.Item1;
string textMsg = combo.Item2; string textMsg = combo.Item2;
if(textUsername != data.User.Username) if (textUsername != data.User.Username)
{ {
ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg); IncomingMsg?.Invoke(textUsername, textMsg);
}
if (textMsg == data.User.RandomWord && !string.IsNullOrEmpty(data.User.RandomWord))
{
Debug.WriteLine($"[CLIENT] word has been guessed! {data.User.Username} + Word: {data.User.RandomWord}");
} }
//TODO display username and message in chat window //TODO display username and message in chat window
@@ -120,6 +166,7 @@ namespace Client
Lobbies = JSONConvert.GetLobbiesFromMessage(payload); Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
OnLobbiesListReceived?.Invoke(); OnLobbiesListReceived?.Invoke();
OnLobbiesReceivedAndWaitingForHost?.Invoke(); OnLobbiesReceivedAndWaitingForHost?.Invoke();
OnLobbyUpdate?.Invoke();
break; break;
case LobbyIdentifier.HOST: case LobbyIdentifier.HOST:
// we receive this when the server has made us a host of a new lobby // we receive this when the server has made us a host of a new lobby
@@ -129,7 +176,6 @@ namespace Client
OnLobbyCreated?.Invoke(lobbyCreatedID); OnLobbyCreated?.Invoke(lobbyCreatedID);
break; break;
case LobbyIdentifier.JOIN_SUCCESS: case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload)); OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
@@ -142,22 +188,67 @@ namespace Client
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
// canvas data // canvas data
//clientData.CanvasData = JSONConvert.getCoordinates(payload);
int type = JSONConvert.GetCanvasMessageType(payload);
switch (type)
{
case JSONConvert.CANVAS_RESET:
CReset?.Invoke();
break;
case JSONConvert.CANVAS_WRITING:
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
break;
}
break; break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload); int lobbyId = JSONConvert.GetLobbyID(payload);
data.User.RandomWord = JSONConvert.GetRandomWord(payload);
if(data.Lobby?.ID == lobbyId) data.User.TurnToDraw = true; // Dit is test code, dit kan weg zodra alles lopende is.
ViewModels.ViewModelGame.HandleRandomWord(JSONConvert.GetRandomWord(payload)); if (data.Lobby?.ID == lobbyId && data.User.TurnToDraw)
RandomWord?.Invoke(data.User.RandomWord);
break; break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break; break;
case JSONConvert.GAME:
switch (JSONConvert.GetGameCommand(payload))
{
case JSONConvert.GameCommand.TIMER_ELAPSED:
int lobbyElapsedID = JSONConvert.GetLobbyID(payload);
//todo set next round
break;
}
break;
} }
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED, null));
} }
/*
* Updates the current lobby with the joining players,
* their player score is also tracked and should always be zero.
*/
private void updateGameLobby()
{
Debug.WriteLine("[CLIENT] updating game lobby");
foreach (var item in Lobbies)
{
Debug.WriteLine("[CLIENT] lobby data: {0}", item.Users.Count);
if (item.ID == data.Lobby?.ID)
{
//IncomingPlayer?.Invoke(item);
UpdateUserScores?.Invoke(item as Lobby);
}
}
}
public void SendMessage(byte[] message) public void SendMessage(byte[] message)
{ {
Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message)); Debug.WriteLine("[CLIENT] sending message " + Encoding.ASCII.GetString(message));
@@ -168,6 +259,7 @@ namespace Client
{ {
Debug.WriteLine("[CLIENT] finished writing"); Debug.WriteLine("[CLIENT] finished writing");
stream.EndWrite(ar); stream.EndWrite(ar);
stream.Flush();
} }
} }
} }

View File

@@ -31,6 +31,7 @@ namespace Client
private Client _client; private Client _client;
private Lobby _lobby; private Lobby _lobby;
private string _message; private string _message;
private double[] _canvasData = new double[4];
private ClientData() private ClientData()
{ {
@@ -68,5 +69,11 @@ namespace Client
} }
} }
public double[] CanvasData
{
get { return _canvasData; }
set { _canvasData = value; }
}
} }
} }

View File

@@ -0,0 +1,37 @@
using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
namespace Client.ViewModels
{
class LoginViewModel
{
ClientData data = ClientData.Instance;
private Window window;
public LoginViewModel(Window window)
{
this.window = window;
}
public void UsernameEntered(string name) {
User user = new User(name);
Client client = new Client(user.Username);
client.OnSuccessfullConnect = () =>
{
// because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread
Application.Current.Dispatcher.Invoke(delegate {
data.User = user;
data.Client = client;
client.SendMessage(JSONConvert.ConstructLobbyRequestMessage());
MainWindow startWindow = new MainWindow();
startWindow.Show();
window.Close();
});
};
}
}
}

View File

@@ -11,6 +11,9 @@ using System.Collections.ObjectModel;
using Client.Views; using Client.Views;
using System.Linq; using System.Linq;
using System.Windows.Data; using System.Windows.Data;
using System.Data;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
namespace Client namespace Client
{ {
@@ -35,6 +38,10 @@ namespace Client
client = ClientData.Instance.Client; client = ClientData.Instance.Client;
client.OnLobbiesListReceived = updateLobbies; client.OnLobbiesListReceived = updateLobbies;
client.OnLobbyLeave = leaveLobby; client.OnLobbyLeave = leaveLobby;
client.OnServerDisconnect = () =>
{
Environment.Exit(0);
};
OnHostButtonClick = new RelayCommand(hostGame); OnHostButtonClick = new RelayCommand(hostGame);
@@ -54,16 +61,16 @@ namespace Client
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username); Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
client.SendMessage(JSONConvert.ConstructLobbyHostMessage()); client.SendMessage(JSONConvert.ConstructLobbyHostMessage());
client.OnLobbyCreated = becomeHostForLobby; client.OnLobbyCreated = becomeHostForLobby;
} }
private void becomeHostForLobby(int id) private void becomeHostForLobby(int id)
{ {
Debug.WriteLine($"got host succes with data {id} "); Debug.WriteLine($"got host succes with data {id} ");
wantToBeHost = true; wantToBeHost = true;
wantToBeHostId = id; wantToBeHostId = id;
ClientData.Instance.User.Host = true;
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived; client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
} }
private void hostLobbiesReceived() private void hostLobbiesReceived()
@@ -85,9 +92,16 @@ namespace Client
private void joinLobby() private void joinLobby()
{ {
if (SelectedLobby != null)
{
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
{
return;
}
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
}
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
} }
private void OnLobbyJoinSuccess(bool isHost) private void OnLobbyJoinSuccess(bool isHost)
@@ -100,7 +114,7 @@ namespace Client
private void updateLobbies() private void updateLobbies()
{ {
Debug.WriteLine("updating lobbies..."); Debug.WriteLine("[VIEWMODEL] updating lobbies...");
Lobby[] lobbiesArr = client.Lobbies; Lobby[] lobbiesArr = client.Lobbies;
Application.Current.Dispatcher.Invoke(delegate Application.Current.Dispatcher.Invoke(delegate
{ {
@@ -110,6 +124,11 @@ namespace Client
foreach (Lobby l in lobbiesArr) foreach (Lobby l in lobbiesArr)
{ {
_lobbies.Add(l); _lobbies.Add(l);
Lobby clientLobby = ClientData.Instance.Lobby;
if (l.ID == clientLobby?.ID)
{
clientLobby = l;
}
} }
}); });
@@ -163,5 +182,7 @@ namespace Client
get { return _lobbies; } get { return _lobbies; }
set { _lobbies = value; } set { _lobbies = value; }
} }
} }
} }

View File

@@ -1,148 +1,282 @@
using Client.Views;
using Client.Views; using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Command; using SharedClientServer;
using SharedClientServer; using System;
using System.Collections.ObjectModel; using System.Collections.Generic;
using System.ComponentModel; using System.Collections.ObjectModel;
using System.Diagnostics; using System.ComponentModel;
using System.Windows; using System.Diagnostics;
using System.Windows.Controls; using System.Timers;
using System.Windows;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Shapes; using System.Windows.Shapes;
namespace Client.ViewModels namespace Client.ViewModels
{ {
class ViewModelGame : INotifyPropertyChanged class ViewModelGame : INotifyPropertyChanged
{ {
private ClientData data = ClientData.Instance; public event PropertyChangedEventHandler PropertyChanged;
private ClientData data = ClientData.Instance;
public event PropertyChangedEventHandler PropertyChanged; private GameWindow window;
private Point currentPoint = new Point();
private Point currentPoint = new Point(); public Color color;
private Color color; public double[][] buffer;
public int pos = 0;
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public int maxLines = 50;
public Queue<double[][]> linesQueue;
private dynamic _payload; private Timer queueTimer;
public static string Word public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
{ public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
get;
set; private dynamic _payload;
}
public string _username; public string _username;
public string _message;
public string Message public string _message;
{ public string Message
get {
get
{
return _message;
}
set
{
_message = value;
}
}
private string _randomWord;
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
public bool IsHost
{
get { return data.User.Host; }
}
public ViewModelGame(GameWindow window)
{
this.window = window;
buffer = new double[maxLines][];
linesQueue = new Queue<double[][]>();
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
ButtonStartGame = new RelayCommand(BeginGame);
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
data.Client.CReset = CanvasResetData;
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer;
data.Client.UpdateUserScores = UpdateUserScores;
Application.Current.Dispatcher.Invoke(delegate
{ {
return _message; Messages.Clear();
} });
set
{
_message = value;
}
}
public ICommand OnKeyDown { get; set; }
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
{
if (e.ButtonState == MouseButtonState.Pressed)
{
currentPoint = e.GetPosition(window.CanvasForPaint);
}
}
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
double[] coordinates = new double[4];
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
line.Y1 = currentPoint.Y;
line.X2 = e.GetPosition(window.CanvasForPaint).X;
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
coordinates[0] = line.X1;
coordinates[1] = line.Y1;
coordinates[2] = line.X2;
coordinates[3] = line.Y2;
currentPoint = e.GetPosition(window.CanvasForPaint);
window.CanvasForPaint.Children.Add(line);
data.Client.SendMessage(JSONConvert.GetMessageToSend(0x04, coordinates));
}
}
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
{
Color colorSelected = new Color();
colorSelected.A = 255;
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
}
public ViewModelGame() queueTimer = new Timer(50);
{ queueTimer.Start();
OnKeyDown = new RelayCommand(ChatBox_KeyDown); queueTimer.Elapsed += sendArrayFromQueue;
} }
private void ChatBox_KeyDown() public ICommand OnKeyDown { get; set; }
{ public ICommand ButtonStartGame { get; set; }
//if enter then clear textbox and send message. public ICommand ButtonResetCanvas { get; set; }
if (Message != string.Empty) AddMessage(Message);
Message = string.Empty; public void BeginGame()
} {
internal void AddMessage(string message) data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
{ }
Messages.Add($"{data.User.Username}: {message}");
_payload = new private void CanvasResetLocal()
{ {
username = data.User.Username, this.window.CanvasForPaint.Children.Clear();
message = message data.Client.SendMessage(JSONConvert.ConstructCanvasReset());
}; }
//Broadcast the message after adding it to the list!
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
} {
if (e.ButtonState == MouseButtonState.Pressed)
/* {
* MISC make this a callback currentPoint = e.GetPosition(window.CanvasForPaint);
* Handles the incoming chat message from another client. }
*/ }
public static void HandleIncomingMsg(string username, string message)
{ public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
double[] coordinates = new double[4];
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
//line.Stroke = SystemColors.WindowFrameBrush;
line.X1 = currentPoint.X;
line.Y1 = currentPoint.Y;
line.X2 = e.GetPosition(window.CanvasForPaint).X;
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
coordinates[0] = line.X1;
coordinates[1] = line.Y1;
coordinates[2] = line.X2;
coordinates[3] = line.Y2;
currentPoint = e.GetPosition(window.CanvasForPaint);
buffer[pos] = coordinates;
pos++;
window.CanvasForPaint.Children.Add(line);
if (pos == maxLines)
{
double[][] temp = new double[maxLines][];
for (int i = 0; i < maxLines; i++)
{
temp[i] = buffer[i];
}
linesQueue.Enqueue(temp);
Array.Clear(buffer, 0, buffer.Length);
pos = 0;
}
}
}
public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
sendArrayFromQueue(sender, null);
}
private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
{
if (linesQueue.Count != 0)
{
double[][] temp = linesQueue.Dequeue();
data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color));
}
}
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
{
Color colorSelected = new Color();
colorSelected.A = 255;
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
color = colorSelected;
}
private void UpdateCanvasWithNewData(double[][] buffer, Color color)
{
Application.Current.Dispatcher.Invoke(delegate
{
foreach (double[] arr in buffer)
{
Line line = new Line();
line.Stroke = new SolidColorBrush(color);
line.X1 = arr[0];
line.Y1 = arr[1];
line.X2 = arr[2];
line.Y2 = arr[3];
this.window.CanvasForPaint.Children.Add(line);
}
});
}
private void CanvasResetData()
{
Application.Current.Dispatcher.Invoke(delegate Application.Current.Dispatcher.Invoke(delegate
{ {
Messages.Add($"{username}: {message}"); this.window.CanvasForPaint.Children.Clear();
}); });
} }
public void LeaveGame(object sender, CancelEventArgs e)
{ private void ChatBox_KeyDown()
Debug.WriteLine("Leaving..."); {
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID)); //if enter then clear textbox and send message.
} if (Message != string.Empty) AddMessage(Message);
Message = string.Empty;
/* }
* MISC make this a callback
* Handles the random word that has been received from the server. internal void AddMessage(string message)
*/ {
public static void HandleRandomWord(string randomWord) Messages.Add($"{data.User.Username}: {message}");
{
Debug.WriteLine("[CLIENT] Reached the handle random word method!"); _payload = new
Word = "NegerPik"; {
} username = data.User.Username,
} message = message
} };
//Broadcast the message after adding it to the list!
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
}
public void HandleIncomingMsg(string username, string message)
{
Application.Current.Dispatcher.Invoke(delegate
{
Messages.Add($"{username}: {message}");
});
}
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
{
Debug.WriteLine("Leaving...");
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
}
public void HandleRandomWord(string randomWord)
{
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Application.Current.Dispatcher.Invoke(delegate
{
RandomWord = randomWord;
});
}
public void HandleIncomingPlayer(Lobby lobby)
{
Application.Current.Dispatcher.Invoke(delegate
{
Players.Clear();
foreach (var item in lobby.Users)
{
Players.Add(item.Username + "\n" + item.Score);
}
});
}
private void UpdateUserScores(Lobby newLobby) {
Debug.WriteLine("[GAME] updating user scores");
List<User> newUsers = newLobby.Users;
// go over all users in current lobby
foreach (User user in data.Lobby?.Users)
{
// check with all users in new lobby
foreach (User newUser in newUsers)
{
// and update the score
if (newUser.Username == user.Username)
{
Debug.WriteLine($"[GAME] setting score of {user.Username} to {newUser.Score}. it was {user.Score}");
user.Score = newUser.Score;
break;
}
}
}
// update all the scores in the player list
HandleIncomingPlayer(newLobby);
}
}
}

View File

@@ -22,26 +22,32 @@
<Grid Grid.Column="0" Grid.Row="1"> <Grid Grid.Column="0" Grid.Row="1">
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition/> <RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<ListBox Name="PlayerList" ItemsSource="{Binding Path=Players}" Margin="10,0,0,10" FontSize="20"/>
</Grid> </Grid>
<Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="2" Margin="84,10,10,10" Content="RESET"/> <Grid Grid.Row="0" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="160"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=Word, UpdateSourceTrigger=PropertyChanged}" Margin="140,0,109,0"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/> <Label Name="GuessWord" Grid.Row="0" Grid.Column="2" Content="{Binding Path=RandomWord, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="20"/>
<Button Name="CanvasReset" Command="{Binding ButtonResetCanvas}" Grid.Row="0" Grid.Column="3" Content="RESET"/>
</Grid>
<Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5"> <Border Grid.Row="1" Grid.Column="1" Margin ="10,10,10,10" BorderBrush="Black" BorderThickness ="2.5">
<Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove"> <Canvas Name="CanvasForPaint" MouseDown="CanvasForPaint_MouseDown" MouseMove="CanvasForPaint_MouseMove" MouseUp="CanvasForPaint_MouseUp">
<Canvas.Background> <Canvas.Background>
<SolidColorBrush Color="White" Opacity="0"/> <SolidColorBrush Color="White" Opacity="0"/>
</Canvas.Background> </Canvas.Background>
@@ -49,9 +55,9 @@
</Border> </Border>
<Grid Grid.Column="2" Grid.Row="1"> <Grid Grid.Column="2" Grid.Row="1">
<ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,0,69"/> <ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,10,69" />
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,0,0"> <TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,10,0">
<TextBox.InputBindings> <TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/> <KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings> </TextBox.InputBindings>

View File

@@ -15,7 +15,7 @@ namespace Client.Views
private ViewModelGame viewModel; private ViewModelGame viewModel;
public GameWindow() public GameWindow()
{ {
this.viewModel = new ViewModelGame(); this.viewModel = new ViewModelGame(this);
DataContext = this.viewModel; DataContext = this.viewModel;
Closing += this.viewModel.LeaveGame; Closing += this.viewModel.LeaveGame;
InitializeComponent(); InitializeComponent();
@@ -36,16 +36,6 @@ namespace Client.Views
private void CanvasReset_Click(object sender, RoutedEventArgs e) private void CanvasReset_Click(object sender, RoutedEventArgs e)
{ {
CanvasForPaint.Children.Clear(); CanvasForPaint.Children.Clear();
//FOR FUTURE USE, IF NECCESSARY
//TEST.Children.Clear();
//foreach (UIElement child in CanvasForPaint.Children)
//{
// var xaml = System.Windows.Markup.XamlWriter.Save(child);
// var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
// TEST.Children.Add(deepCopy);
//}
} }
private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e) private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e)
@@ -53,5 +43,9 @@ namespace Client.Views
viewModel.Color_Picker(e, this); viewModel.Color_Picker(e, this);
} }
private void CanvasForPaint_MouseUp(object sender, MouseButtonEventArgs e)
{
viewModel.Canvas_MouseUp(sender, e);
}
} }
} }

View File

@@ -11,6 +11,7 @@
<RowDefinition Height="60"/> <RowDefinition Height="60"/>
<RowDefinition Height="50"/> <RowDefinition Height="50"/>
<RowDefinition Height="30"/> <RowDefinition Height="30"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@@ -22,8 +23,7 @@
<Label Grid.Row="1" FontSize="30" Content="Enter a username:"/> <Label Grid.Row="1" FontSize="30" Content="Enter a username:"/>
<Label Grid.Row="2" FontSize="15" Content="(max amount of characters for the username is 10)"/> <Label Grid.Row="2" FontSize="15" Content="(max amount of characters for the username is 10)"/>
<TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="10" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Left" Width="250"/> <TextBox Name="usernameTextbox" Grid.Row="1" Grid.Column="1" MaxLength="69" FontSize="30" VerticalAlignment="Center" HorizontalAlignment="Left" Width="250"/>
<Button Content="ENTER" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="100" Height="40" Click="Button_EnterUsername"/> <Button Name="LoginButton" Content="ENTER" Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Right" Width="100" Height="40" Click="Button_EnterUsername"/>
</Grid> </Grid>
</Window> </Window>

View File

@@ -1,4 +1,5 @@
using SharedClientServer; using Client.ViewModels;
using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -26,8 +27,12 @@ namespace Client.Views
private void Button_EnterUsername(object sender, RoutedEventArgs e) private void Button_EnterUsername(object sender, RoutedEventArgs e)
{ {
User user = new User(usernameTextbox.Text); string name = usernameTextbox.Text;
if (name == string.Empty) return;
User user = new User(name);
Client client = new Client(user.Username); Client client = new Client(user.Username);
LoginButton.IsEnabled = false;
client.OnSuccessfullConnect = () => client.OnSuccessfullConnect = () =>
{ {
// because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread // because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread
@@ -41,6 +46,7 @@ namespace Client.Views
}); });
}; };
} }
} }
} }

View File

@@ -57,7 +57,8 @@
<GridView x:Name="grdList"> <GridView x:Name="grdList">
<GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/> <GridViewColumn Header="Lobby ID" DisplayMemberBinding="{Binding ID}" Width="70"/>
<GridViewColumn Header="Players in" DisplayMemberBinding="{Binding PlayersIn}" Width="70"/> <GridViewColumn Header="Players in" DisplayMemberBinding="{Binding PlayersIn}" Width="70"/>
<GridViewColumn Header="max players available" DisplayMemberBinding="{Binding MaxPlayers}"/> <GridViewColumn Header="max players available" DisplayMemberBinding="{Binding MaxPlayers}" Width="150"/>
<GridViewColumn Header="joinable" DisplayMemberBinding="{Binding LobbyJoinable}"/>
</GridView> </GridView>
</ListView.View> </ListView.View>
</ListView> </ListView>

View File

@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Client\Client.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,14 @@
using System;
namespace Client2
{
class Program
{
static void Main(string[] args)
{
Client.App app = new Client.App();
app.Run();
}
}
}

View File

@@ -9,6 +9,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Client", "..\Client\Client.
EndProject EndProject
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "SharedClientServer", "..\SharedClientServer\SharedClientServer.shproj", "{6D26F969-9CB1-414F-AC3E-7253D449AC5A}" Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "SharedClientServer", "..\SharedClientServer\SharedClientServer.shproj", "{6D26F969-9CB1-414F-AC3E-7253D449AC5A}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "Tests\Tests.csproj", "{4CB2CD76-07D9-44D0-A559-A7A301621D30}"
EndProject
Global Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution GlobalSection(SharedMSBuildProjectFiles) = preSolution
..\SharedClientServer\SharedClientServer.projitems*{67a9bf1a-d317-47ca-9f07-c3480d1360ff}*SharedItemsImports = 5 ..\SharedClientServer\SharedClientServer.projitems*{67a9bf1a-d317-47ca-9f07-c3480d1360ff}*SharedItemsImports = 5
@@ -28,6 +30,10 @@ Global
{83768EDB-097E-4089-A5DE-208CB252D1A0}.Debug|Any CPU.Build.0 = Debug|Any CPU {83768EDB-097E-4089-A5DE-208CB252D1A0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{83768EDB-097E-4089-A5DE-208CB252D1A0}.Release|Any CPU.ActiveCfg = Release|Any CPU {83768EDB-097E-4089-A5DE-208CB252D1A0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{83768EDB-097E-4089-A5DE-208CB252D1A0}.Release|Any CPU.Build.0 = Release|Any CPU {83768EDB-097E-4089-A5DE-208CB252D1A0}.Release|Any CPU.Build.0 = Release|Any CPU
{4CB2CD76-07D9-44D0-A559-A7A301621D30}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4CB2CD76-07D9-44D0-A559-A7A301621D30}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4CB2CD76-07D9-44D0-A559-A7A301621D30}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4CB2CD76-07D9-44D0-A559-A7A301621D30}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -0,0 +1,10 @@
using SharedClientServer;
using System;
namespace TestHelper
{
public class Helper
{
public static JSONConvert JSONConvert;
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<Import Project="..\..\SharedClientServer\SharedClientServer.projitems" Label="Shared" />
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,158 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SharedClientServer;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Media;
namespace Tests
{
[TestClass]
public class JSONConvertCanvasMessages
{
//Helper method for the tests
public byte[] GetPayload(byte[] message)
{
byte[] payload = new byte[message.Length - 5];
Array.Copy(message, 5, payload, 0, message.Length - 5);
return payload;
}
public dynamic GetDynamic(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json;
}
[TestMethod]
public void TestConstructCanvasDataSend()
{
int type = JSONConvert.CANVAS_WRITING;
double[][] coordinateInfo = new double[2][];
double[] coordinatesOne = { 10.0, 10.0, 3.0, 3.0 };
double[] coordinatesTwo = { 10.0, 10.0, 3.0, 3.0 };
coordinateInfo[0] = coordinatesOne;
coordinateInfo[1] = coordinatesTwo;
Color color = Color.FromRgb(0, 0, 0);
byte[] message = JSONConvert.ConstructCanvasDataSend(type, coordinateInfo, color);
byte[] payload = GetPayload(message);
dynamic json = GetDynamic(payload);
int ID = json.canvasType;
JArray coorArray = json.coords;
double[][] coordinates = coorArray.ToObject<double[][]>();
Color colorResult = json.color;
Assert.AreEqual(0x04, message[4]);
Assert.AreEqual(type, ID, "The canvas type message is not correct on the ConstructDrawingCanvasData");
for (int i = 0; i < coordinateInfo.Length; i++)
{
CollectionAssert.AreEqual(coordinateInfo[i], coordinates[i], "Coordinates are not correct on the ConstructDrawingCanvasData");
}
Assert.AreEqual(color, colorResult, "color is not correct on the ConstructDrawingCanvasData");
}
[TestMethod]
public void TestConstructDrawingCanvasData()
{
double[][] coordinateInfo = new double[2][];
double[] coordinatesOne = {10.0, 10.0, 3.0, 3.0 };
double[] coordinatesTwo = { 10.0, 10.0, 3.0, 3.0 };
coordinateInfo[0] = coordinatesOne;
coordinateInfo[1] = coordinatesTwo;
Color color = Color.FromRgb(0, 0, 0);
byte[] message = JSONConvert.ConstructDrawingCanvasData(coordinateInfo, color);
byte[] payload = GetPayload(message);
dynamic json = GetDynamic(payload);
int ID = json.canvasType;
JArray coorArray = json.coords;
double[][] coordinates = coorArray.ToObject<double[][]>();
Color colorResult = json.color;
Assert.AreEqual(0x04, message[4]);
Assert.AreEqual(JSONConvert.CANVAS_WRITING, ID, "The canvas type message is not correct on the ConstructDrawingCanvasData");
for (int i = 0; i < coordinateInfo.Length; i++)
{
CollectionAssert.AreEqual(coordinateInfo[i], coordinates[i], "Coordinates are not correct on the ConstructDrawingCanvasData");
}
Assert.AreEqual(color, colorResult, "color is not correct on the ConstructDrawingCanvasData");
}
[TestMethod]
public void TestConstructCanvasReset()
{
byte[] canvasReset = JSONConvert.ConstructCanvasReset();
dynamic json = GetDynamic(GetPayload(canvasReset));
int ID = json.canvasType;
Assert.AreEqual(JSONConvert.CANVAS_RESET, ID, $"Canvas type should be reset(1)! Not, {ID}");
}
[TestMethod]
public void TestGetCanvasMessageType()
{
int type = JSONConvert.CANVAS_WRITING;
byte IDsend = JSONConvert.CANVAS;
dynamic payloadSend = new
{
canvasType = type
};
byte[] message = JSONConvert.GetMessageToSend(IDsend, payloadSend);
byte[] payload = GetPayload(message);
int resultID = JSONConvert.GetCanvasMessageType(payload);
Assert.AreEqual(type, resultID, $"Canvas type should be {IDsend}! Not, {resultID}");
}
[TestMethod]
public void TestgetCoordinates()
{
int type = JSONConvert.CANVAS_WRITING;
byte IDsend = JSONConvert.CANVAS;
double[][] coordinateInfo = new double[2][];
double[] coordinatesOne = { 10.0, 10.0, 3.0, 3.0 };
double[] coordinatesTwo = { 10.0, 10.0, 3.0, 3.0 };
coordinateInfo[0] = coordinatesOne;
coordinateInfo[1] = coordinatesTwo;
dynamic payloadSend = new
{
canvasType = type,
coords = coordinateInfo
};
byte[] message = JSONConvert.GetMessageToSend(IDsend, payloadSend);
byte[] payload = GetPayload(message);
double[][] coordinates = JSONConvert.getCoordinates(payload);
for (int i = 0; i < coordinateInfo.Length; i++)
{
CollectionAssert.AreEqual(coordinateInfo[i], coordinates[i], "Coordinates are not correct on the ConstructDrawingCanvasData");
}
}
[TestMethod]
public void TestGetCanvasDrawingColor()
{
int type = JSONConvert.CANVAS_WRITING;
byte IDsend = JSONConvert.CANVAS;
Color colorSend = Color.FromRgb(0, 0, 0);
dynamic payloadSend = new
{
canvasType = type,
color = colorSend
};
byte[] message = JSONConvert.GetMessageToSend(IDsend, payloadSend);
byte[] payload = GetPayload(message);
Color colorResult = JSONConvert.getCanvasDrawingColor(payload);
Assert.AreEqual(colorSend, colorResult, "Colors are not equal!");
}
}
}

View File

@@ -0,0 +1,77 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using SharedClientServer;
using System;
using System.Diagnostics;
using System.Text;
using Xunit.Sdk;
namespace Tests
{
[TestClass]
public class JSONConvertGetMessageToSendTest
{
private byte[] testArray1()
{
byte identifier = 0x01;
dynamic payload = new
{
value = "test"
};
byte[] result = JSONConvert.GetMessageToSend(identifier, payload);
return result;
}
[TestMethod]
public void TestGetMessageToSendLength()
{
byte identifier = 0x01;
dynamic payload = new
{
value = "test"
};
string payloadToJson = JsonConvert.SerializeObject(payload);
byte[] payloadToBytes = Encoding.UTF8.GetBytes(payloadToJson);
byte[] result = JSONConvert.GetMessageToSend(identifier, payload);
Assert.AreEqual(payloadToBytes.Length + 5, result.Length);
}
[TestMethod]
public void TestGetMessageToSendIdentifier()
{
byte[] result = testArray1();
Assert.AreEqual(0x01, result[4]);
}
[TestMethod]
public void TestGetMessageToSendMessageLength()
{
byte identifier = 0x01;
dynamic payload = new
{
value = "test"
};
string json = JsonConvert.SerializeObject(payload);
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
byte[] res = new byte[payloadBytes.Length + 5];
Array.Copy(payloadBytes, 0, res, 5, payloadBytes.Length);
res[4] = identifier;
Array.Copy(BitConverter.GetBytes(payloadBytes.Length + 5), 0, res, 0, 4);
int lengthTest = BitConverter.ToInt32(res, 0);
byte[] result = testArray1();
int lengthResult = BitConverter.ToInt32(result, 0);
Assert.AreEqual(lengthTest, lengthResult);
}
}
}

View File

@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.2" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.2" />
<PackageReference Include="coverlet.collector" Version="1.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit.extensibility.execution" Version="2.4.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Client\Client.csproj" />
</ItemGroup>
</Project>

View File

@@ -11,19 +11,24 @@ using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers;
using static SharedClientServer.JSONConvert; using static SharedClientServer.JSONConvert;
namespace Server.Models namespace Server.Models
{ {
public delegate void Callback();
class ServerClient : ObservableObject class ServerClient : ObservableObject
{ {
private TcpClient tcpClient; private TcpClient tcpClient;
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[1024]; private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[1024]; private byte[] totalBuffer = new byte[2048];
private string _randomWord = "";
private int totalBufferReceived = 0; private int totalBufferReceived = 0;
private Dictionary<System.Timers.Timer, int> lobbyTimers;
public User User { get; set; } public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE; private ServerCommunication serverCom = ServerCommunication.INSTANCE;
private Callback OnMessageReceivedOk;
/// <summary> /// <summary>
@@ -32,6 +37,7 @@ namespace Server.Models
/// <param name="client">the TcpClient object to use</param> /// <param name="client">the TcpClient object to use</param>
public ServerClient(TcpClient client) public ServerClient(TcpClient client)
{ {
lobbyTimers = new Dictionary<System.Timers.Timer, int>();
Debug.WriteLine("[SERVERCLIENT] making new instance and starting"); Debug.WriteLine("[SERVERCLIENT] making new instance and starting");
tcpClient = client; tcpClient = client;
stream = tcpClient.GetStream(); stream = tcpClient.GetStream();
@@ -52,11 +58,12 @@ namespace Server.Models
{ {
int bytesReceived = this.stream.EndRead(ar); int bytesReceived = this.stream.EndRead(ar);
if (totalBufferReceived + bytesReceived > 1024) if (totalBufferReceived + bytesReceived > 2048)
{ {
throw new OutOfMemoryException("buffer is too small!"); throw new OutOfMemoryException("buffer is too small!");
} }
// copy the received bytes into the buffer // copy the received bytes into the buffer
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived); Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
// add the bytes we received to the total amount // add the bytes we received to the total amount
@@ -88,12 +95,14 @@ namespace Server.Models
} }
ar.AsyncWaitHandle.WaitOne(); ar.AsyncWaitHandle.WaitOne();
// start reading for a new message // start reading for a new message
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
} }
catch (IOException e) catch (IOException e)
{ {
Debug.WriteLine("[SERVERCLIENT] Client disconnected! exception was " + e.Message);
tcpClient.Close(); tcpClient.Close();
ServerCommunication.INSTANCE.ServerClientDisconnect(this); ServerCommunication.INSTANCE.ServerClientDisconnect(this);
} }
@@ -140,6 +149,11 @@ namespace Server.Models
message = textMsg message = textMsg
}; };
if (textMsg == _randomWord && !string.IsNullOrEmpty(_randomWord))
{
Debug.WriteLine($"[SERVERCLIENT] word has been guessed! {User.Username} + Word: {_randomWord}");
}
//Sends the incomming message to be broadcast to all of the clients inside the current lobby. //Sends the incomming message to be broadcast to all of the clients inside the current lobby.
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet)); serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
break; break;
@@ -149,21 +163,96 @@ namespace Server.Models
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload); LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
handleLobbyMessage(payload, l); handleLobbyMessage(payload, l);
break; break;
case JSONConvert.CANVAS: case JSONConvert.CANVAS:
Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
switch (typeToCheck)
{
case JSONConvert.CANVAS_WRITING:
dynamic canvasData = new
{
canvasType = typeToCheck,
coords = JSONConvert.getCoordinates(payload),
color = JSONConvert.getCanvasDrawingColor(payload)
};
//serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
serverCom.SendCanvasDataToLobby(serverCom.GetLobbyForUser(User), User.Username, JSONConvert.GetMessageToSend(JSONConvert.CANVAS, canvasData));
break;
case JSONConvert.CANVAS_RESET:
dynamic canvasDataForReset = new
{
canvasType = JSONConvert.GetCanvasMessageType(payload)
};
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(CANVAS, canvasDataForReset));
break;
}
// canvas data // canvas data
// todo send canvas data to all other serverclients in lobby // todo send canvas data to all other serverclients in lobby
break; break;
case JSONConvert.GAME:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
GameCommand command = JSONConvert.GetGameCommand(payload);
switch (command)
{
case GameCommand.START_GAME:
int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID);
//todo start a timer for this lobby
Debug.WriteLine("[SERVERCLIENT] making timer for lobby " + lobbyID);
System.Timers.Timer lobbyTimer = new System.Timers.Timer(60 * 1000);
this.lobbyTimers.Add(lobbyTimer, lobbyID);
lobbyTimer.Elapsed += LobbyTimer_Elapsed;
lobbyTimer.Start();
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
break;
case GameCommand.TIMER_ELAPSED:
break;
case GameCommand.NEXT_ROUND:
// The next round has been started, so we can start the timer again
lobbyID = JSONConvert.GetLobbyID(payload);
foreach (System.Timers.Timer timer in lobbyTimers.Keys)
{
if (lobbyTimers[timer] == lobbyID)
{
timer.Start();
break;
}
}
break;
}
break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
break; break;
case JSONConvert.MESSAGE_RECEIVED:
// we now can send a new message
OnMessageReceivedOk?.Invoke();
break;
default: default:
Debug.WriteLine("[SERVER] Received weird identifier: " + id); Debug.WriteLine("[SERVER] Received weird identifier: " + id);
break; break;
} }
} }
private void LobbyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
System.Timers.Timer timer = sender as System.Timers.Timer;
int lobbyID = lobbyTimers[timer];
Debug.WriteLine("[SERVERCLIENT] timer elapsed for lobby " + lobbyID);
serverCom.SendToLobby(lobbyID, JSONConvert.ConstructGameTimerElapsedMessage(lobbyID));
timer.Stop();
}
private void handleLobbyMessage(byte[] payload, LobbyIdentifier l) private void handleLobbyMessage(byte[] payload, LobbyIdentifier l)
{ {
switch (l) switch (l)
@@ -181,21 +270,20 @@ namespace Server.Models
break; break;
case LobbyIdentifier.JOIN: case LobbyIdentifier.JOIN:
int id = JSONConvert.GetLobbyID(payload); int id = JSONConvert.GetLobbyID(payload);
ServerCommunication.INSTANCE.JoinLobby(this.User, id);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage());
bool isHost; bool isHost;
ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost); ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost);
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost)); sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost));
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () =>
//Task.Run(SendLobbyData);
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{ {
id = serverCom.GetLobbyForUser(User).ID, _randomWord = JSONConvert.SendRandomWord("WordsForGame.json");
word = JSONConvert.SendRandomWord("WordsForGame.json") serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
})); {
id = serverCom.GetLobbyForUser(User).ID,
word = _randomWord
}));
OnMessageReceivedOk = null;
};
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
id = JSONConvert.GetLobbyID(payload); id = JSONConvert.GetLobbyID(payload);

View File

@@ -142,7 +142,7 @@ namespace Server.Models
{ {
foreach (ServerClient sc in serverClientsInlobbies[l]) foreach (ServerClient sc in serverClientsInlobbies[l])
{ {
Debug.WriteLine("[SERVERCLIENT] Sending message"); Debug.WriteLine("[SERVERCLIENT] Sending message to lobby");
sc.sendMessage(message); sc.sendMessage(message);
} }
break; break;
@@ -150,6 +150,38 @@ namespace Server.Models
} }
} }
public void SendToLobby(int lobbyID, byte[] message)
{
foreach (Lobby l in lobbies)
{
if (l.ID == lobbyID)
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
Debug.WriteLine("[SERVERCLIENT] Sending message to lobby");
sc.sendMessage(message);
}
break;
}
}
}
public void SendCanvasDataToLobby(Lobby lobby, string username, byte[] message)
{
foreach (Lobby l in lobbies)
{
if (l == lobby)
{
foreach (ServerClient sc in serverClientsInlobbies[l])
{
if (sc.User.Username != username)
sc.sendMessage(message);
}
break;
}
}
}
public Lobby GetLobbyForUser(User user) public Lobby GetLobbyForUser(User user)
{ {
foreach (Lobby l in lobbies) foreach (Lobby l in lobbies)
@@ -246,6 +278,10 @@ namespace Server.Models
break; break;
} }
} }
if (l.Users.Count != 0)
{
l.Users[0].Host = true;
}
break; break;
} }
} }
@@ -255,5 +291,16 @@ namespace Server.Models
} }
} }
} }
public void CloseALobby(int lobbyID)
{
foreach (Lobby lobby in lobbies)
{
if (lobby.ID == lobbyID)
{
lobby.LobbyJoinable = false;
}
}
}
} }
} }

View File

@@ -7,6 +7,8 @@ using System.Text;
namespace SharedClientServer namespace SharedClientServer
{ {
public delegate void Callback(); public delegate void Callback();
class ClientServerUtil class ClientServerUtil
{ {
// creates a message array to send to the server or to clients // creates a message array to send to the server or to clients

View File

@@ -1,23 +1,26 @@
using Client; using Client;
using Microsoft.VisualBasic.CompilerServices;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
using System.Collections.Generic; using System.Diagnostics;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Text;
using System.Text; using System.Windows.Media;
namespace SharedClientServer namespace SharedClientServer
{ {
class JSONConvert public class JSONConvert
{ {
public const byte LOGIN = 0x01; public const byte LOGIN = 0x01;
public const byte MESSAGE = 0x02; public const byte MESSAGE = 0x02;
public const byte LOBBY = 0x03; public const byte LOBBY = 0x03;
public const byte CANVAS = 0x04; public const byte CANVAS = 0x04;
public const byte RANDOMWORD = 0x05; public const byte GAME = 0x05;
public const byte MESSAGE_RECEIVED = 0x06;
public const byte RANDOMWORD = 0x07;
public const int CANVAS_WRITING = 0;
public const int CANVAS_RESET = 1;
public enum LobbyIdentifier public enum LobbyIdentifier
{ {
@@ -28,17 +31,33 @@ namespace SharedClientServer
LIST, LIST,
REQUEST REQUEST
} }
public static (string,string) GetUsernameAndMessage(byte[] json)
public enum GameCommand
{ {
string msg = Encoding.ASCII.GetString(json); START_GAME,
dynamic payload = JsonConvert.DeserializeObject(msg); TIMER_ELAPSED,
NEXT_ROUND
}
public static (string, string) GetUsernameAndMessage(byte[] json)
{
string msg = Encoding.UTF8.GetString(json);
dynamic payload = JsonConvert.DeserializeObject(msg);
return (payload.username, payload.message); return (payload.username, payload.message);
} }
internal static byte[] ConstructCanvasResetMessage()
{
return GetMessageToSend(CANVAS, new
{
canvasType = CANVAS_RESET
});
}
public static string GetUsernameLogin(byte[] json) public static string GetUsernameLogin(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.username; return payload.username;
} }
@@ -66,7 +85,7 @@ namespace SharedClientServer
{ {
identifier = LobbyIdentifier.HOST, identifier = LobbyIdentifier.HOST,
id = lobbyID id = lobbyID
}) ; });
} }
public static byte[] ConstructLobbyRequestMessage() public static byte[] ConstructLobbyRequestMessage()
@@ -80,7 +99,7 @@ namespace SharedClientServer
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList) public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
{ {
return GetMessageToSend(LOBBY, new return GetMessageToSend(LOBBY, new
{ {
identifier = LobbyIdentifier.LIST, identifier = LobbyIdentifier.LIST,
lobbies = lobbiesList lobbies = lobbiesList
}); });
@@ -102,16 +121,17 @@ namespace SharedClientServer
identifier = LobbyIdentifier.LEAVE, identifier = LobbyIdentifier.LEAVE,
id = lobbyID id = lobbyID
}); });
} }
public static LobbyIdentifier GetLobbyIdentifier(byte[] json) public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.identifier; return payload.identifier;
} }
public static Lobby[] GetLobbiesFromMessage(byte[] json) public static Lobby[] GetLobbiesFromMessage(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JArray lobbiesArray = payload.lobbies; JArray lobbiesArray = payload.lobbies;
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString()); Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>(); Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
@@ -125,30 +145,117 @@ namespace SharedClientServer
public static int GetLobbyID(byte[] json) public static int GetLobbyID(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.id; return payload.id;
} }
public static Lobby GetLobby(byte[] json) public static Lobby GetLobby(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
JObject dynamicAsObject = payload.lobby; JObject dynamicAsObject = payload.lobby;
return dynamicAsObject.ToObject<Lobby>(); return dynamicAsObject.ToObject<Lobby>();
} }
public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost) public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost)
{ {
return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS, return GetMessageToSend(LOBBY, new
host = isHost}); {
identifier = LobbyIdentifier.JOIN_SUCCESS,
host = isHost
});
} }
public static bool GetLobbyJoinIsHost(byte[] json) public static bool GetLobbyJoinIsHost(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return payload.host; return payload.host;
} }
#endregion #endregion lobby messages
public static byte[] ConstructCanvasDataSend(int typeToSend, double[][] buffer, Color colorToSend)
{
return GetMessageToSend(CANVAS, new
{
canvasType = typeToSend,
coords = buffer,
color = colorToSend
}); ;
}
public static byte[] ConstructDrawingCanvasData(double[][] buffer, Color colorToSend)
{
return GetMessageToSend(CANVAS, new
{
canvasType = CANVAS_WRITING,
coords = buffer,
color = colorToSend
});
}
public static byte[] ConstructCanvasReset()
{
dynamic payload = new
{
canvasType = CANVAS_RESET
};
return GetMessageToSend(CANVAS, payload);
}
public static int GetCanvasMessageType(byte[] json)
{
dynamic d = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
return d.canvasType;
}
public static double[][] getCoordinates(byte[] payload)
{
Debug.WriteLine("got coords " + Encoding.UTF8.GetString(payload));
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
JArray coordinatesArray = json.coords;
double[][] coordinates = coordinatesArray.ToObject<double[][]>();
return coordinates;
}
public static Color getCanvasDrawingColor(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
Color color = json.color;
return color;
}
public static byte[] ConstructGameStartData(int lobbyID)
{
return GetMessageToSend(GAME, new
{
command = GameCommand.START_GAME,
lobbyToStart = lobbyID
}); ;
}
public static byte[] ConstructGameTimerElapsedMessage(int lobbyID)
{
return GetMessageToSend(GAME, new
{
command = GameCommand.TIMER_ELAPSED,
id = lobbyID
});
}
public static GameCommand GetGameCommand(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.command;
}
public static int GetStartGameLobbyID(byte[] payload)
{
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.lobbyToStart;
}
/// <summary> /// <summary>
/// constructs a message that can be sent to the clients or server /// constructs a message that can be sent to the clients or server
/// </summary> /// </summary>
@@ -158,7 +265,8 @@ namespace SharedClientServer
public static byte[] GetMessageToSend(byte identifier, dynamic payload) public static byte[] GetMessageToSend(byte identifier, dynamic payload)
{ {
// convert the dynamic to bytes // convert the dynamic to bytes
byte[] payloadBytes = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(payload)); string json = JsonConvert.SerializeObject(payload);
byte[] payloadBytes = Encoding.UTF8.GetBytes(json);
// make the array that holds the message and copy the payload into it with the first spot containing the identifier // make the array that holds the message and copy the payload into it with the first spot containing the identifier
byte[] res = new byte[payloadBytes.Length + 5]; byte[] res = new byte[payloadBytes.Length + 5];
// put the payload in the res array // put the payload in the res array
@@ -166,13 +274,14 @@ namespace SharedClientServer
// put the identifier at the start of the payload part // put the identifier at the start of the payload part
res[4] = identifier; res[4] = identifier;
// put the length of the payload at the start of the res array // put the length of the payload at the start of the res array
Array.Copy(BitConverter.GetBytes(payloadBytes.Length+5),0,res,0,4); Array.Copy(BitConverter.GetBytes(payloadBytes.Length + 5), 0, res, 0, 4);
return res; return res;
} }
/* /*
* This method sends a random word from the json file, this happens when the client joins a lobby. * This method sends a random word from the json file, this happens when the client joins a lobby.
*/ */
public static string SendRandomWord(string filename) public static string SendRandomWord(string filename)
{ {
dynamic words; dynamic words;
@@ -181,27 +290,27 @@ namespace SharedClientServer
string projDir = Directory.GetParent(workingDir).Parent.Parent.FullName; string projDir = Directory.GetParent(workingDir).Parent.Parent.FullName;
string filePath = projDir += $@"\resources\{filename}"; string filePath = projDir += $@"\resources\{filename}";
using(StreamReader reader = new StreamReader(filePath)) using (StreamReader reader = new StreamReader(filePath))
{ {
string json = reader.ReadToEnd(); string json = reader.ReadToEnd();
words = JsonConvert.DeserializeObject(json); words = JsonConvert.DeserializeObject(json);
} }
int index = random.Next(0, 24); int index = random.Next(0, 24);
Debug.WriteLine($"[SERVERCLIENT] Sending random words {words}"); Debug.WriteLine($"[SERVERCLIENT] Sending random words {words}");
return words.words[index]; return words.words[index];
} }
/* /*
* Client gets the payload and retrieves the word from the payload * Client gets the payload and retrieves the word from the payload
*/ */
public static string GetRandomWord(byte[] json) public static string GetRandomWord(byte[] json)
{ {
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json)); dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
return payload.word; return payload.word;
} }
} }
} }

View File

@@ -6,7 +6,7 @@ using System.Text;
namespace Client namespace Client
{ {
class Lobby : INotifyPropertyChanged public class Lobby : INotifyPropertyChanged
{ {
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;
@@ -14,6 +14,7 @@ namespace Client
private int _id; private int _id;
private int _playersIn; private int _playersIn;
private int _maxPlayers; private int _maxPlayers;
private bool _lobbyJoinable;
//private List<string> _usernames; //private List<string> _usernames;
private List<User> _users; private List<User> _users;
@@ -34,6 +35,7 @@ namespace Client
_maxPlayers = maxPlayers; _maxPlayers = maxPlayers;
//_usernames = new List<string>(); //_usernames = new List<string>();
_users = new List<User>(); _users = new List<User>();
_lobbyJoinable = true;
} }
public void AddUser(string username, out bool succes) public void AddUser(string username, out bool succes)
@@ -41,7 +43,7 @@ namespace Client
succes = false; succes = false;
if (_users.Count < _maxPlayers) if (_users.Count < _maxPlayers)
{ {
_users.Add(new User(username, 0, false)); _users.Add(new User(username, 0, false, false));
succes = true; succes = true;
} }
} }
@@ -87,6 +89,11 @@ namespace Client
set { _users = value; } set { _users = value; }
} }
public bool LobbyJoinable
{
get { return _lobbyJoinable; }
set { _lobbyJoinable = value; }
}
} }
} }

View File

@@ -10,4 +10,4 @@
<PropertyGroup /> <PropertyGroup />
<Import Project="SharedClientServer.projitems" Label="Shared" /> <Import Project="SharedClientServer.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project> </Project>

View File

@@ -6,19 +6,22 @@ using System.Text;
namespace SharedClientServer namespace SharedClientServer
{ {
class User : IEquatable<User> public class User : IEquatable<User>
{ {
private string _username; private string _username;
private int _score; private int _score;
private bool _host; private bool _host;
private bool _turnToDraw;
private string _message; private string _message;
private string _randomWord;
[JsonConstructor] [JsonConstructor]
public User(string username, int score, bool host) public User(string username, int score, bool host, bool turnToDraw)
{ {
_username = username; _username = username;
_score = score; _score = score;
_host = host; _host = host;
_turnToDraw = turnToDraw;
} }
public User(string username) public User(string username)
@@ -26,6 +29,7 @@ namespace SharedClientServer
_username = username; _username = username;
_score = 0; _score = 0;
_host = false; _host = false;
_turnToDraw = false;
} }
public static bool operator ==(User u1, User u2) public static bool operator ==(User u1, User u2)
@@ -81,5 +85,16 @@ namespace SharedClientServer
get { return _host; } get { return _host; }
set { _host = value; } set { _host = value; }
} }
public bool TurnToDraw
{
get { return _turnToDraw; }
set { _turnToDraw = value; }
}
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
} }
} }