Compare commits
99 Commits
feature/br
...
feature/te
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7f8dfc0f9c | ||
|
|
5ac4b59e38 | ||
|
|
3c1f1a0028 | ||
|
|
e7b40d7e64 | ||
|
|
27e70d1ec0 | ||
|
|
0e6a2bab59 | ||
|
|
125f4c0410 | ||
|
|
b9b217622a | ||
|
|
2d4540e28e | ||
|
|
052f07db93 | ||
|
|
898b579ca9 | ||
|
|
39ded8524b | ||
|
|
398ba1d5bd | ||
|
|
8ca4efc296 | ||
|
|
3015c0312f | ||
|
|
3c0f5018db | ||
|
|
9558c75eab | ||
|
|
ec08fbfced | ||
|
|
87ebdeef58 | ||
|
|
bf09dba850 | ||
|
|
b14a7691b5 | ||
|
|
7df48ab322 | ||
|
|
6512518fb7 | ||
|
|
80d970da35 | ||
|
|
2c7bf3e217 | ||
|
|
92f57a87bc | ||
|
|
da5528c7b2 | ||
|
|
c16f7cf68f | ||
|
|
5c2dea3ab4 | ||
|
|
e2f9dfec78 | ||
|
|
7fcf424b65 | ||
|
|
97be0f937c | ||
|
|
09056818df | ||
|
|
8d4f72c09d | ||
|
|
f51d310787 | ||
|
|
9e829c47ff | ||
|
|
f5d55ef405 | ||
|
|
0d44b2d840 | ||
|
|
1c04ab95c0 | ||
|
|
ddf4594c5e | ||
|
|
09f9e227b8 | ||
|
|
ec156f3dc6 | ||
|
|
0158841159 | ||
|
|
8a490eb399 | ||
|
|
5e408091cb | ||
|
|
24eb43239b | ||
|
|
335d17838c | ||
|
|
242c435ac7 | ||
|
|
eae05d17df | ||
|
|
d37696d4bd | ||
|
|
4a400628df | ||
|
|
9fa231ab00 | ||
|
|
21ee724056 | ||
|
|
5075f285d1 | ||
|
|
eca17cc70f | ||
|
|
07b0357b0a | ||
|
|
d8bbaf5258 | ||
|
|
8190d9b31b | ||
|
|
bb289865b7 | ||
|
|
b8d0f206ba | ||
|
|
f1878eaf25 | ||
|
|
3b667b3f0c | ||
|
|
1fdba622cc | ||
|
|
cac0fdc0a4 | ||
|
|
674c4f1ba1 | ||
|
|
d3bd1418d1 | ||
|
|
5b5d66c41b | ||
|
|
d4d0545f0b | ||
|
|
0b72c4dc9b | ||
|
|
471247827b | ||
|
|
ef255e4828 | ||
|
|
8190724f77 | ||
|
|
b08e6cc749 | ||
|
|
c150bf3611 | ||
|
|
332fcf799c | ||
|
|
4d3dda023c | ||
|
|
e8a72e164f | ||
|
|
d5d6d59690 | ||
|
|
754c1c5db9 | ||
|
|
8a90e74e74 | ||
|
|
be99c8d3f9 | ||
|
|
9e1ac07b80 | ||
|
|
cc5c71a30f | ||
|
|
442cdccc49 | ||
|
|
c339746a82 | ||
|
|
0f01354b72 | ||
|
|
61577e0df7 | ||
|
|
298bd760e5 | ||
|
|
c4c97a3fbe | ||
|
|
95448832c3 | ||
|
|
3a13314519 | ||
|
|
4f07eeb95a | ||
|
|
fc5d51a876 | ||
|
|
24701f8bb3 | ||
|
|
2aeca40aa4 | ||
|
|
76cd392525 | ||
|
|
7b30911cd7 | ||
|
|
671951c35b | ||
|
|
ba1b71d870 |
206
Client/Client.cs
206
Client/Client.cs
@@ -2,22 +2,55 @@
|
|||||||
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;
|
||||||
|
|
||||||
namespace Client
|
namespace Client
|
||||||
{
|
{
|
||||||
|
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;
|
||||||
private string username;
|
private string username;
|
||||||
public Callback OnSuccessfullConnect;
|
public Callback OnSuccessfullConnect;
|
||||||
|
public Callback OnLobbiesListReceived;
|
||||||
|
public LobbyJoinCallback OnLobbyJoinSuccess;
|
||||||
|
public Callback OnLobbiesReceivedAndWaitingForHost;
|
||||||
|
public Callback OnServerDisconnect;
|
||||||
|
public Callback OnLobbyUpdate;
|
||||||
|
public LobbyCallback OnLobbyCreated;
|
||||||
|
public LobbyCallback OnLobbyLeave;
|
||||||
|
public RandomWord RandomWord;
|
||||||
|
public HandleIncomingMsg IncomingMsg;
|
||||||
|
public HandleIncomingPlayer IncomingPlayer;
|
||||||
|
private ClientData data = ClientData.Instance;
|
||||||
|
public CanvasDataReceived CanvasDataReceived;
|
||||||
|
public CanvasReset CReset;
|
||||||
|
public HandleIncomingPlayer UpdateUserScores;
|
||||||
|
public Lobby[] Lobbies { get; set; }
|
||||||
|
|
||||||
public Client(string username)
|
public Client(string username)
|
||||||
{
|
{
|
||||||
@@ -30,48 +63,73 @@ 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)
|
||||||
{
|
{
|
||||||
int amountReceived = stream.EndRead(ar);
|
|
||||||
|
|
||||||
if (totalBufferReceived + amountReceived > 1024)
|
if (ar == null || (!ar.IsCompleted) || (!this.stream.CanRead) || !this.tcpClient.Client.Connected)
|
||||||
|
return;
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void handleData(byte[] message)
|
private void handleData(byte[] message)
|
||||||
{
|
{
|
||||||
byte id = message[4];
|
byte id = message[4];
|
||||||
byte[] payload = new byte[message.Length - 1];
|
|
||||||
Array.Copy(message, 1, payload, 0, message.Length - 1);
|
byte[] payload = new byte[message.Length - 5];
|
||||||
|
Array.Copy(message, 5, payload, 0, message.Length - 5);
|
||||||
|
|
||||||
|
Debug.WriteLine("[CLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
|
||||||
switch (id)
|
switch (id)
|
||||||
{
|
{
|
||||||
case JSONConvert.LOGIN:
|
case JSONConvert.LOGIN:
|
||||||
@@ -83,6 +141,16 @@ namespace Client
|
|||||||
string textUsername = combo.Item1;
|
string textUsername = combo.Item1;
|
||||||
string textMsg = combo.Item2;
|
string textMsg = combo.Item2;
|
||||||
|
|
||||||
|
if (textUsername != data.User.Username)
|
||||||
|
{
|
||||||
|
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
|
||||||
Debug.WriteLine("[CLIENT] INCOMING MESSAGE!");
|
Debug.WriteLine("[CLIENT] INCOMING MESSAGE!");
|
||||||
Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
|
Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
|
||||||
@@ -90,20 +158,97 @@ namespace Client
|
|||||||
|
|
||||||
case JSONConvert.LOBBY:
|
case JSONConvert.LOBBY:
|
||||||
// lobby data
|
// lobby data
|
||||||
|
LobbyIdentifier lobbyIdentifier = JSONConvert.GetLobbyIdentifier(payload);
|
||||||
|
switch (lobbyIdentifier)
|
||||||
|
{
|
||||||
|
case LobbyIdentifier.LIST:
|
||||||
|
Debug.WriteLine("got lobbies list");
|
||||||
|
Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
|
||||||
|
OnLobbiesListReceived?.Invoke();
|
||||||
|
OnLobbiesReceivedAndWaitingForHost?.Invoke();
|
||||||
|
OnLobbyUpdate?.Invoke();
|
||||||
|
break;
|
||||||
|
case LobbyIdentifier.HOST:
|
||||||
|
// we receive this when the server has made us a host of a new lobby
|
||||||
|
// TODO get lobby id
|
||||||
|
Debug.WriteLine("[CLIENT] got lobby object");
|
||||||
|
int lobbyCreatedID = JSONConvert.GetLobbyID(payload);
|
||||||
|
OnLobbyCreated?.Invoke(lobbyCreatedID);
|
||||||
|
break;
|
||||||
|
case LobbyIdentifier.JOIN_SUCCESS:
|
||||||
|
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
|
||||||
|
break;
|
||||||
|
case LobbyIdentifier.LEAVE:
|
||||||
|
int lobbyLeaveID = JSONConvert.GetLobbyID(payload);
|
||||||
|
OnLobbyLeave?.Invoke(lobbyLeaveID);
|
||||||
|
break;
|
||||||
|
}
|
||||||
//TODO fill lobby with the data received
|
//TODO fill lobby with the data received
|
||||||
break;
|
break;
|
||||||
|
|
||||||
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;
|
||||||
|
|
||||||
|
case JSONConvert.RANDOMWORD:
|
||||||
|
//Flag byte for receiving the random word.
|
||||||
|
int lobbyId = JSONConvert.GetLobbyID(payload);
|
||||||
|
data.User.RandomWord = JSONConvert.GetRandomWord(payload);
|
||||||
|
data.User.TurnToDraw = true; // Dit is test code, dit kan weg zodra alles lopende is.
|
||||||
|
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));
|
||||||
@@ -114,6 +259,7 @@ namespace Client
|
|||||||
{
|
{
|
||||||
Debug.WriteLine("[CLIENT] finished writing");
|
Debug.WriteLine("[CLIENT] finished writing");
|
||||||
stream.EndWrite(ar);
|
stream.EndWrite(ar);
|
||||||
|
stream.Flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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; }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
37
Client/ViewModels/LoginViewModel.cs
Normal file
37
Client/ViewModels/LoginViewModel.cs
Normal 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();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,11 @@ using System.Diagnostics;
|
|||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Collections.ObjectModel;
|
using System.Collections.ObjectModel;
|
||||||
using Client.Views;
|
using Client.Views;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Windows.Data;
|
||||||
|
using System.Data;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
|
||||||
namespace Client
|
namespace Client
|
||||||
{
|
{
|
||||||
@@ -21,21 +26,112 @@ namespace Client
|
|||||||
|
|
||||||
public Lobby SelectedLobby { get; set; }
|
public Lobby SelectedLobby { get; set; }
|
||||||
|
|
||||||
|
private Client client;
|
||||||
|
|
||||||
|
private bool wantToBeHost = false;
|
||||||
|
private int wantToBeHostId = 0;
|
||||||
|
|
||||||
public ViewModel()
|
public ViewModel()
|
||||||
{
|
{
|
||||||
_model = new Model();
|
_model = new Model();
|
||||||
_lobbies = new ObservableCollection<Lobby>();
|
_lobbies = new ObservableCollection<Lobby>();
|
||||||
|
client = ClientData.Instance.Client;
|
||||||
_lobbies.Add(new Lobby(50, 3, 8));
|
client.OnLobbiesListReceived = updateLobbies;
|
||||||
_lobbies.Add(new Lobby(69, 1, 9));
|
client.OnLobbyLeave = leaveLobby;
|
||||||
_lobbies.Add(new Lobby(420, 7, 7));
|
client.OnServerDisconnect = () =>
|
||||||
|
|
||||||
OnHostButtonClick = new RelayCommand(() =>
|
|
||||||
{
|
{
|
||||||
Debug.WriteLine("Host button clicked");
|
Environment.Exit(0);
|
||||||
});
|
};
|
||||||
|
|
||||||
|
|
||||||
JoinSelectedLobby = new RelayCommand(startGameInLobby, true);
|
OnHostButtonClick = new RelayCommand(hostGame);
|
||||||
|
|
||||||
|
JoinSelectedLobby = new RelayCommand(joinLobby, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void leaveLobby(int id)
|
||||||
|
{
|
||||||
|
_model.CanStartGame = true;
|
||||||
|
ClientData.Instance.Lobby = null;
|
||||||
|
SelectedLobby = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void hostGame()
|
||||||
|
{
|
||||||
|
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
|
||||||
|
client.SendMessage(JSONConvert.ConstructLobbyHostMessage());
|
||||||
|
client.OnLobbyCreated = becomeHostForLobby;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void becomeHostForLobby(int id)
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"got host succes with data {id} ");
|
||||||
|
wantToBeHost = true;
|
||||||
|
wantToBeHostId = id;
|
||||||
|
ClientData.Instance.User.Host = true;
|
||||||
|
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void hostLobbiesReceived()
|
||||||
|
{
|
||||||
|
if (wantToBeHost)
|
||||||
|
foreach (Lobby l in Lobbies)
|
||||||
|
{
|
||||||
|
if (l.ID == wantToBeHostId)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("found lobby that we want to be host of: " + l.ID + ", joining..");
|
||||||
|
SelectedLobby = l;
|
||||||
|
startGameInLobby();
|
||||||
|
wantToBeHost = false;
|
||||||
|
client.OnLobbiesReceivedAndWaitingForHost = null;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void joinLobby()
|
||||||
|
{
|
||||||
|
if (SelectedLobby != null)
|
||||||
|
{
|
||||||
|
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
|
||||||
|
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnLobbyJoinSuccess(bool isHost)
|
||||||
|
{
|
||||||
|
ClientData.Instance.User.Host = isHost;
|
||||||
|
startGameInLobby();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private void updateLobbies()
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[VIEWMODEL] updating lobbies...");
|
||||||
|
Lobby[] lobbiesArr = client.Lobbies;
|
||||||
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
|
{
|
||||||
|
|
||||||
|
_lobbies.Clear();
|
||||||
|
|
||||||
|
foreach (Lobby l in lobbiesArr)
|
||||||
|
{
|
||||||
|
_lobbies.Add(l);
|
||||||
|
Lobby clientLobby = ClientData.Instance.Lobby;
|
||||||
|
if (l.ID == clientLobby?.ID)
|
||||||
|
{
|
||||||
|
clientLobby = l;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void startGameInLobby()
|
private void startGameInLobby()
|
||||||
@@ -43,11 +139,18 @@ namespace Client
|
|||||||
if (SelectedLobby != null)
|
if (SelectedLobby != null)
|
||||||
{
|
{
|
||||||
ClientData.Instance.Lobby = SelectedLobby;
|
ClientData.Instance.Lobby = SelectedLobby;
|
||||||
|
startGameWindow();
|
||||||
_model.CanStartGame = false;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void startGameWindow()
|
||||||
|
{
|
||||||
|
_model.CanStartGame = false;
|
||||||
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
|
{
|
||||||
GameWindow window = new GameWindow();
|
GameWindow window = new GameWindow();
|
||||||
window.Show();
|
window.Show();
|
||||||
}
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ClickCheck()
|
private void ClickCheck()
|
||||||
@@ -79,5 +182,7 @@ namespace Client
|
|||||||
get { return _lobbies; }
|
get { return _lobbies; }
|
||||||
set { _lobbies = value; }
|
set { _lobbies = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,41 @@
|
|||||||
using GalaSoft.MvvmLight.Command;
|
using Client.Views;
|
||||||
|
using GalaSoft.MvvmLight.Command;
|
||||||
using SharedClientServer;
|
using SharedClientServer;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Collections.ObjectModel;
|
using System.Collections.ObjectModel;
|
||||||
using System.ComponentModel;
|
using System.ComponentModel;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Windows.Input;
|
using System.Timers;
|
||||||
|
using System.Windows;
|
||||||
|
using System.Windows.Input;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using System.Windows.Shapes;
|
||||||
|
|
||||||
namespace Client.ViewModels
|
namespace Client.ViewModels
|
||||||
{
|
{
|
||||||
class ViewModelGame : INotifyPropertyChanged
|
class ViewModelGame : INotifyPropertyChanged
|
||||||
{
|
{
|
||||||
ClientData data = ClientData.Instance;
|
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
private ClientData data = ClientData.Instance;
|
||||||
|
private GameWindow window;
|
||||||
|
private Point currentPoint = new Point();
|
||||||
|
public Color color;
|
||||||
|
public double[][] buffer;
|
||||||
|
public int pos = 0;
|
||||||
|
public int maxLines = 50;
|
||||||
|
public Queue<double[][]> linesQueue;
|
||||||
|
private Timer queueTimer;
|
||||||
|
|
||||||
|
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
||||||
|
public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
|
||||||
|
|
||||||
private dynamic _payload;
|
private dynamic _payload;
|
||||||
|
|
||||||
private string _username;
|
public string _username;
|
||||||
|
|
||||||
private string _message;
|
|
||||||
|
public string _message;
|
||||||
public string Message
|
public string Message
|
||||||
{
|
{
|
||||||
get
|
get
|
||||||
@@ -29,22 +47,157 @@ namespace Client.ViewModels
|
|||||||
_message = value;
|
_message = value;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public ICommand OnKeyDown { get; set; }
|
|
||||||
|
|
||||||
public ViewModelGame()
|
private string _randomWord;
|
||||||
|
public string RandomWord
|
||||||
{
|
{
|
||||||
if (_payload == null)
|
get { return _randomWord; }
|
||||||
{
|
set { _randomWord = value; }
|
||||||
_message = "";
|
}
|
||||||
|
|
||||||
}
|
public bool IsHost
|
||||||
else
|
{
|
||||||
{
|
get { return data.User.Host; }
|
||||||
//_message = data.Message;
|
}
|
||||||
//_username = data.User.Username;
|
|
||||||
//Messages.Add($"{data.User.Username}: {Message}");
|
public ViewModelGame(GameWindow window)
|
||||||
}
|
{
|
||||||
|
this.window = window;
|
||||||
|
|
||||||
|
buffer = new double[maxLines][];
|
||||||
|
linesQueue = new Queue<double[][]>();
|
||||||
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
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
|
||||||
|
{
|
||||||
|
Messages.Clear();
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
queueTimer = new Timer(50);
|
||||||
|
queueTimer.Start();
|
||||||
|
queueTimer.Elapsed += sendArrayFromQueue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ICommand OnKeyDown { get; set; }
|
||||||
|
public ICommand ButtonStartGame { get; set; }
|
||||||
|
public ICommand ButtonResetCanvas { get; set; }
|
||||||
|
|
||||||
|
public void BeginGame()
|
||||||
|
{
|
||||||
|
|
||||||
|
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private void CanvasResetLocal()
|
||||||
|
{
|
||||||
|
this.window.CanvasForPaint.Children.Clear();
|
||||||
|
data.Client.SendMessage(JSONConvert.ConstructCanvasReset());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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);
|
||||||
|
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
|
||||||
|
{
|
||||||
|
this.window.CanvasForPaint.Children.Clear();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ChatBox_KeyDown()
|
private void ChatBox_KeyDown()
|
||||||
@@ -67,5 +220,63 @@ namespace Client.ViewModels
|
|||||||
//Broadcast the message after adding it to the list!
|
//Broadcast the message after adding it to the list!
|
||||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,6 @@
|
|||||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||||
xmlns:local="clr-namespace:Client.Views"
|
|
||||||
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
|
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
|
||||||
mc:Ignorable="d"
|
mc:Ignorable="d"
|
||||||
Title="Scrubl.io" Height="600" Width="1200">
|
Title="Scrubl.io" Height="600" Width="1200">
|
||||||
@@ -23,24 +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="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>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
|
|
||||||
|
|
||||||
<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>
|
||||||
@@ -48,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>
|
||||||
|
|||||||
@@ -1,15 +1,8 @@
|
|||||||
using Client.ViewModels;
|
using Client.ViewModels;
|
||||||
using System;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Text;
|
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Controls;
|
|
||||||
using System.Windows.Data;
|
|
||||||
using System.Windows.Documents;
|
|
||||||
using System.Windows.Input;
|
using System.Windows.Input;
|
||||||
using System.Windows.Media;
|
using System.Windows.Media;
|
||||||
using System.Windows.Media.Imaging;
|
|
||||||
using System.Windows.Shapes;
|
|
||||||
|
|
||||||
namespace Client.Views
|
namespace Client.Views
|
||||||
{
|
{
|
||||||
@@ -18,90 +11,41 @@ namespace Client.Views
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public partial class GameWindow : Window
|
public partial class GameWindow : Window
|
||||||
{
|
{
|
||||||
|
ClientData data = ClientData.Instance;
|
||||||
|
private ViewModelGame viewModel;
|
||||||
public GameWindow()
|
public GameWindow()
|
||||||
{
|
{
|
||||||
DataContext = new ViewModelGame();
|
this.viewModel = new ViewModelGame(this);
|
||||||
|
DataContext = this.viewModel;
|
||||||
|
Closing += this.viewModel.LeaveGame;
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
|
|
||||||
}
|
}
|
||||||
Point currentPoint = new Point();
|
|
||||||
|
|
||||||
private void CanvasForPaint_MouseDown(object sender, MouseButtonEventArgs e)
|
private void CanvasForPaint_MouseDown(object sender, MouseButtonEventArgs e)
|
||||||
{
|
{
|
||||||
if (e.ButtonState == MouseButtonState.Pressed)
|
this.viewModel.Canvas_MouseDown(e, this);
|
||||||
{
|
|
||||||
currentPoint = e.GetPosition(CanvasForPaint);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void CanvasForPaint_MouseMove(object sender, MouseEventArgs e)
|
private void CanvasForPaint_MouseMove(object sender, MouseEventArgs e)
|
||||||
{
|
{
|
||||||
if (e.LeftButton == MouseButtonState.Pressed)
|
viewModel.Canvas_MouseMove(e, this);
|
||||||
{
|
|
||||||
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(CanvasForPaint).X;
|
|
||||||
line.Y2 = e.GetPosition(CanvasForPaint).Y;
|
|
||||||
|
|
||||||
currentPoint = e.GetPosition(CanvasForPaint);
|
|
||||||
|
|
||||||
CanvasForPaint.Children.Add(line);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private Color color;
|
|
||||||
|
|
||||||
private void ClrPcker_Background_SelectedColorChanged(object sender, RoutedPropertyChangedEventArgs<Color> e)
|
|
||||||
{
|
|
||||||
Color colorSelected = new Color();
|
|
||||||
colorSelected.A = 255;
|
|
||||||
colorSelected.R = ClrPcker_Background.SelectedColor.Value.R;
|
|
||||||
colorSelected.G = ClrPcker_Background.SelectedColor.Value.G;
|
|
||||||
colorSelected.B = ClrPcker_Background.SelectedColor.Value.B;
|
|
||||||
color = colorSelected;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
||||||
{
|
{
|
||||||
Color colorSelected = new Color();
|
viewModel.Color_Picker(e, this);
|
||||||
colorSelected.A = 255;
|
|
||||||
colorSelected.R = ClrPcker_Background.SelectedColor.Value.R;
|
|
||||||
colorSelected.G = ClrPcker_Background.SelectedColor.Value.G;
|
|
||||||
colorSelected.B = ClrPcker_Background.SelectedColor.Value.B;
|
|
||||||
color = colorSelected;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
///*
|
private void CanvasForPaint_MouseUp(object sender, MouseButtonEventArgs e)
|
||||||
// * Writes the current client's message to the chatbox.
|
{
|
||||||
// */
|
viewModel.Canvas_MouseUp(sender, e);
|
||||||
//private void WriteToChat(string message)
|
}
|
||||||
//{
|
|
||||||
// string user = data.User.Username;
|
|
||||||
// SentMessage.AppendText($"{user}: {message}\n");
|
|
||||||
// data.User.Message = message;
|
|
||||||
//}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -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,20 +27,26 @@ 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
|
||||||
Application.Current.Dispatcher.Invoke(delegate {
|
Application.Current.Dispatcher.Invoke(delegate {
|
||||||
data.User = user;
|
data.User = user;
|
||||||
data.Client = client;
|
data.Client = client;
|
||||||
|
client.SendMessage(JSONConvert.ConstructLobbyRequestMessage());
|
||||||
MainWindow startWindow = new MainWindow();
|
MainWindow startWindow = new MainWindow();
|
||||||
startWindow.Show();
|
startWindow.Show();
|
||||||
this.Close();
|
this.Close();
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -32,18 +32,6 @@ namespace Client
|
|||||||
|
|
||||||
private void Button_Click(object sender, RoutedEventArgs e)
|
private void Button_Click(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
Lobby lobbySelected = LobbyList.SelectedItem as Lobby;
|
|
||||||
if(lobbySelected != null)
|
|
||||||
{
|
|
||||||
testLabel.Content = lobbySelected.ID;
|
|
||||||
colorSelection.IsEnabled = false;
|
|
||||||
joinButton.IsEnabled = false;
|
|
||||||
hostButton.IsEnabled = false;
|
|
||||||
|
|
||||||
GameWindow window = new GameWindow();
|
|
||||||
window.Show();
|
|
||||||
Close();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12
Eindproject/Client2/Client2.csproj
Normal file
12
Eindproject/Client2/Client2.csproj
Normal 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>
|
||||||
14
Eindproject/Client2/Program.cs
Normal file
14
Eindproject/Client2/Program.cs
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace Client2
|
||||||
|
{
|
||||||
|
class Program
|
||||||
|
{
|
||||||
|
static void Main(string[] args)
|
||||||
|
{
|
||||||
|
Client.App app = new Client.App();
|
||||||
|
app.Run();
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
10
Eindproject/TestHelper/Helper.cs
Normal file
10
Eindproject/TestHelper/Helper.cs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
using SharedClientServer;
|
||||||
|
using System;
|
||||||
|
|
||||||
|
namespace TestHelper
|
||||||
|
{
|
||||||
|
public class Helper
|
||||||
|
{
|
||||||
|
public static JSONConvert JSONConvert;
|
||||||
|
}
|
||||||
|
}
|
||||||
14
Eindproject/TestHelper/TestHelper.csproj
Normal file
14
Eindproject/TestHelper/TestHelper.csproj
Normal 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>
|
||||||
77
Eindproject/Tests/JSONConvertGetMessageToSendTest.cs
Normal file
77
Eindproject/Tests/JSONConvertGetMessageToSendTest.cs
Normal 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);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
59
Eindproject/Tests/JSONConvertRandomWord.cs
Normal file
59
Eindproject/Tests/JSONConvertRandomWord.cs
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using SharedClientServer;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Tests
|
||||||
|
{
|
||||||
|
[TestClass]
|
||||||
|
public class JSONConvertRandomWord
|
||||||
|
{
|
||||||
|
public byte[] GetPayload(byte[] message)
|
||||||
|
{
|
||||||
|
byte[] payload = new byte[message.Length - 5];
|
||||||
|
Array.Copy(message, 5, payload, 0, message.Length - 5);
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] RandomWord()
|
||||||
|
{
|
||||||
|
byte identifier = 0x07;
|
||||||
|
dynamic payload = new
|
||||||
|
{
|
||||||
|
word = "teacher"
|
||||||
|
};
|
||||||
|
|
||||||
|
byte[] res = JSONConvert.GetMessageToSend(identifier, payload);
|
||||||
|
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
public dynamic GetDynamic(byte[] payload)
|
||||||
|
{
|
||||||
|
return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(GetPayload(payload)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TestSendRandomWord()
|
||||||
|
{
|
||||||
|
string randomWord = JSONConvert.SendRandomWord("WordsForGame.json");
|
||||||
|
|
||||||
|
string result = "teacher";
|
||||||
|
|
||||||
|
Assert.AreEqual(result, randomWord);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TestGetRandomWord()
|
||||||
|
{
|
||||||
|
byte[] data = GetPayload(RandomWord());
|
||||||
|
string result = JSONConvert.GetRandomWord(data);
|
||||||
|
|
||||||
|
string word = "teacher";
|
||||||
|
|
||||||
|
Assert.AreEqual(word, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
89
Eindproject/Tests/JSONConvertUserMessages.cs
Normal file
89
Eindproject/Tests/JSONConvertUserMessages.cs
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using SharedClientServer;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace Tests
|
||||||
|
{
|
||||||
|
[TestClass]
|
||||||
|
public class JSONConvertUserMessages
|
||||||
|
{
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(GetPayload(payload)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] ComboArray()
|
||||||
|
{
|
||||||
|
byte identifier = 0x02;
|
||||||
|
dynamic payload = new
|
||||||
|
{
|
||||||
|
username = "testName",
|
||||||
|
message = "message"
|
||||||
|
};
|
||||||
|
|
||||||
|
byte[] result = JSONConvert.GetMessageToSend(identifier, payload);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] LoginArray()
|
||||||
|
{
|
||||||
|
byte identifier = 0x01;
|
||||||
|
dynamic payload = new
|
||||||
|
{
|
||||||
|
username = "testname"
|
||||||
|
};
|
||||||
|
|
||||||
|
byte[] result = JSONConvert.GetMessageToSend(identifier, payload);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TestGetUsernameAndMessage()
|
||||||
|
{
|
||||||
|
byte[] data = GetPayload(ComboArray());
|
||||||
|
(string,string) result = JSONConvert.GetUsernameAndMessage(data);
|
||||||
|
|
||||||
|
(string, string) testCombo = ("testName", "message");
|
||||||
|
|
||||||
|
Assert.AreEqual(testCombo, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TestGetUsernameLogin()
|
||||||
|
{
|
||||||
|
byte[] data = GetPayload(LoginArray());
|
||||||
|
string result = JSONConvert.GetUsernameLogin(data);
|
||||||
|
string username = "testname";
|
||||||
|
|
||||||
|
Assert.AreEqual(username, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
[TestMethod]
|
||||||
|
public void TestConstructUsernameMessage()
|
||||||
|
{
|
||||||
|
byte[] res = JSONConvert.ConstructUsernameMessage("testname");
|
||||||
|
dynamic payload = GetDynamic(res);
|
||||||
|
|
||||||
|
string username = "testname";
|
||||||
|
|
||||||
|
Assert.AreEqual(0x01, res[4]);
|
||||||
|
Assert.AreEqual(username, (string)payload.username);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
35
Eindproject/Tests/Tests.csproj
Normal file
35
Eindproject/Tests/Tests.csproj
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>netcoreapp3.1</TargetFramework>
|
||||||
|
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="resources\WordsForGame.json" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Content Include="resources\WordsForGame.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<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>
|
||||||
31
Eindproject/Tests/resources/WordsForGame.json
Normal file
31
Eindproject/Tests/resources/WordsForGame.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"filename": "wordsForGame",
|
||||||
|
"words": [
|
||||||
|
"teacher",
|
||||||
|
"love",
|
||||||
|
"engineer",
|
||||||
|
"supermarket",
|
||||||
|
"disaster",
|
||||||
|
"studio",
|
||||||
|
"restaurant",
|
||||||
|
"music",
|
||||||
|
"chocolate",
|
||||||
|
"dirt",
|
||||||
|
"thought",
|
||||||
|
"virus",
|
||||||
|
"lieutenant",
|
||||||
|
"painter",
|
||||||
|
"kiwi",
|
||||||
|
"power ranger",
|
||||||
|
"computer",
|
||||||
|
"people",
|
||||||
|
"candidate",
|
||||||
|
"security guard",
|
||||||
|
"Canada",
|
||||||
|
"teeth",
|
||||||
|
"army",
|
||||||
|
"airport",
|
||||||
|
"president",
|
||||||
|
"bedroom"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -1,24 +1,35 @@
|
|||||||
|
|
||||||
|
|
||||||
|
using Client;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using SharedClientServer;
|
using SharedClientServer;
|
||||||
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.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using System.Timers;
|
||||||
|
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>
|
||||||
/// Constructor that creates a new serverclient object with the given tcp client.
|
/// Constructor that creates a new serverclient object with the given tcp client.
|
||||||
@@ -26,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();
|
||||||
@@ -42,47 +54,59 @@ namespace Server.Models
|
|||||||
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;
|
||||||
|
|
||||||
|
try
|
||||||
int bytesReceived = this.stream.EndRead(ar);
|
|
||||||
|
|
||||||
if (totalBufferReceived + bytesReceived > 1024)
|
|
||||||
{
|
{
|
||||||
throw new OutOfMemoryException("buffer is too small!");
|
int bytesReceived = this.stream.EndRead(ar);
|
||||||
}
|
|
||||||
|
|
||||||
// copy the received bytes into the buffer
|
if (totalBufferReceived + bytesReceived > 2048)
|
||||||
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
|
|
||||||
// add the bytes we received to the total amount
|
|
||||||
totalBufferReceived += bytesReceived;
|
|
||||||
|
|
||||||
// calculate the expected length of the message
|
|
||||||
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
|
|
||||||
|
|
||||||
while (totalBufferReceived >= expectedMessageLength)
|
|
||||||
{
|
|
||||||
// we have received the full packet
|
|
||||||
byte[] message = new byte[expectedMessageLength];
|
|
||||||
// copy the total buffer contents into the message array so we can pass it to the handleIncomingMessage method
|
|
||||||
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
|
|
||||||
HandleIncomingMessage(message);
|
|
||||||
|
|
||||||
// move the contents of the totalbuffer to the start of the array
|
|
||||||
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength));
|
|
||||||
|
|
||||||
// remove the length of the expected message from the total buffer
|
|
||||||
totalBufferReceived -= expectedMessageLength;
|
|
||||||
// and set the new expected length to the rest that is still in the buffer
|
|
||||||
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
|
|
||||||
|
|
||||||
if (expectedMessageLength == 0)
|
|
||||||
{
|
{
|
||||||
break;
|
throw new OutOfMemoryException("buffer is too small!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// copy the received bytes into the buffer
|
||||||
|
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
|
||||||
|
// add the bytes we received to the total amount
|
||||||
|
totalBufferReceived += bytesReceived;
|
||||||
|
|
||||||
|
// calculate the expected length of the message
|
||||||
|
int expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
|
||||||
|
|
||||||
|
while (totalBufferReceived >= expectedMessageLength)
|
||||||
|
{
|
||||||
|
// we have received the full packet
|
||||||
|
byte[] message = new byte[expectedMessageLength];
|
||||||
|
// copy the total buffer contents into the message array so we can pass it to the handleIncomingMessage method
|
||||||
|
Array.Copy(totalBuffer, 0, message, 0, expectedMessageLength);
|
||||||
|
HandleIncomingMessage(message);
|
||||||
|
|
||||||
|
// move the contents of the totalbuffer to the start of the array
|
||||||
|
Array.Copy(totalBuffer, expectedMessageLength, totalBuffer, 0, (totalBufferReceived - expectedMessageLength));
|
||||||
|
|
||||||
|
// remove the length of the expected message from the total buffer
|
||||||
|
totalBufferReceived -= expectedMessageLength;
|
||||||
|
// and set the new expected length to the rest that is still in the buffer
|
||||||
|
expectedMessageLength = BitConverter.ToInt32(totalBuffer, 0);
|
||||||
|
|
||||||
|
if (expectedMessageLength == 0)
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
ar.AsyncWaitHandle.WaitOne();
|
||||||
|
// start reading for a new message
|
||||||
|
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
|
||||||
}
|
}
|
||||||
// start reading for a new message
|
catch (IOException e)
|
||||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
|
{
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] Client disconnected! exception was " + e.Message);
|
||||||
|
tcpClient.Close();
|
||||||
|
ServerCommunication.INSTANCE.ServerClientDisconnect(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,21 +119,21 @@ namespace Server.Models
|
|||||||
Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}");
|
Debug.WriteLine($"Got message : {Encoding.ASCII.GetString(message)}");
|
||||||
byte id = message[4];
|
byte id = message[4];
|
||||||
byte[] payload = new byte[message.Length - 5];
|
byte[] payload = new byte[message.Length - 5];
|
||||||
Array.Copy(message,5,payload,0,message.Length-5);
|
Array.Copy(message, 5, payload, 0, message.Length - 5);
|
||||||
Debug.WriteLine("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
|
Debug.WriteLine("[SERVERCLIENT] GOT STRING" + Encoding.ASCII.GetString(payload));
|
||||||
switch(id)
|
switch (id)
|
||||||
{
|
{
|
||||||
|
|
||||||
case JSONConvert.LOGIN:
|
case JSONConvert.LOGIN:
|
||||||
// json log in username data
|
// json log in username data
|
||||||
string uName = JSONConvert.GetUsernameLogin(payload);
|
string uName = JSONConvert.GetUsernameLogin(payload);
|
||||||
|
|
||||||
if (uName != null)
|
if (uName != null)
|
||||||
{
|
{
|
||||||
User = new User(uName);
|
User = new User(uName);
|
||||||
User.Username = uName;
|
User.Username = uName;
|
||||||
Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
|
Debug.WriteLine("[SERVERCLIENT] set username to " + uName);
|
||||||
|
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case JSONConvert.MESSAGE:
|
case JSONConvert.MESSAGE:
|
||||||
@@ -118,25 +142,171 @@ namespace Server.Models
|
|||||||
string textUsername = combo.Item1;
|
string textUsername = combo.Item1;
|
||||||
string textMsg = combo.Item2;
|
string textMsg = combo.Item2;
|
||||||
|
|
||||||
Debug.WriteLine("[SERVERCLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
|
//Takes the data sent from the client, and then sets it in a data packet to be sent.
|
||||||
|
dynamic packet = new
|
||||||
|
{
|
||||||
|
username = textUsername,
|
||||||
|
message = textMsg
|
||||||
|
};
|
||||||
|
|
||||||
// todo handle sending to all except this user the username and message to display in chat
|
if (textMsg == _randomWord && !string.IsNullOrEmpty(_randomWord))
|
||||||
serverCom.SendToLobby(User.Lobby,payload);
|
{
|
||||||
Debug.WriteLine("Payload has been sent!");
|
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.
|
||||||
|
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case JSONConvert.LOBBY:
|
case JSONConvert.LOBBY:
|
||||||
// lobby data
|
// lobby data
|
||||||
|
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
|
||||||
|
handleLobbyMessage(payload, l);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case JSONConvert.CANVAS:
|
case JSONConvert.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:
|
||||||
|
//Flag byte for receiving the random word.
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
//TODO implement ways to handle the message
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
switch (l)
|
||||||
|
{
|
||||||
|
case LobbyIdentifier.REQUEST:
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] got lobby request message, sending lobbies...");
|
||||||
|
sendMessage(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
|
||||||
|
break;
|
||||||
|
case LobbyIdentifier.HOST:
|
||||||
|
// add new lobby and add this serverclient to it
|
||||||
|
int createdLobbyID = ServerCommunication.INSTANCE.HostForLobby(this.User);
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] created lobby");
|
||||||
|
sendMessage(JSONConvert.ConstructLobbyHostCreatedMessage(createdLobbyID));
|
||||||
|
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
|
||||||
|
break;
|
||||||
|
case LobbyIdentifier.JOIN:
|
||||||
|
int id = JSONConvert.GetLobbyID(payload);
|
||||||
|
bool isHost;
|
||||||
|
ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost);
|
||||||
|
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost));
|
||||||
|
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
|
||||||
|
OnMessageReceivedOk = () =>
|
||||||
|
{
|
||||||
|
_randomWord = JSONConvert.SendRandomWord("WordsForGame.json");
|
||||||
|
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
|
||||||
|
{
|
||||||
|
id = serverCom.GetLobbyForUser(User).ID,
|
||||||
|
word = _randomWord
|
||||||
|
}));
|
||||||
|
OnMessageReceivedOk = null;
|
||||||
|
};
|
||||||
|
break;
|
||||||
|
case LobbyIdentifier.LEAVE:
|
||||||
|
id = JSONConvert.GetLobbyID(payload);
|
||||||
|
ServerCommunication.INSTANCE.LeaveLobby(User, id);
|
||||||
|
sendMessage(JSONConvert.ConstructLobbyLeaveMessage(id));
|
||||||
|
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async void SendLobbyData()
|
||||||
|
{
|
||||||
|
string result = await WaitForData();
|
||||||
|
if(result == "bruh momento")
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string> WaitForData()
|
||||||
|
{
|
||||||
|
await Task.Delay(1000);
|
||||||
|
return "bruh momento";
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ namespace Server.Models
|
|||||||
public bool Started = false;
|
public bool Started = false;
|
||||||
public List<Lobby> lobbies;
|
public List<Lobby> lobbies;
|
||||||
private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies;
|
private Dictionary<Lobby, List<ServerClient>> serverClientsInlobbies;
|
||||||
|
internal Action DisconnectClientAction;
|
||||||
public Action newClientAction;
|
public Action newClientAction;
|
||||||
|
|
||||||
|
|
||||||
@@ -32,7 +33,10 @@ namespace Server.Models
|
|||||||
listener = new TcpListener(IPAddress.Any, port);
|
listener = new TcpListener(IPAddress.Any, port);
|
||||||
serverClients = new List<ServerClient>();
|
serverClients = new List<ServerClient>();
|
||||||
lobbies = new List<Lobby>();
|
lobbies = new List<Lobby>();
|
||||||
|
Lobby temp = new Lobby(1, 7, 8);
|
||||||
|
lobbies.Add(temp);
|
||||||
serverClientsInlobbies = new Dictionary<Lobby, List<ServerClient>>();
|
serverClientsInlobbies = new Dictionary<Lobby, List<ServerClient>>();
|
||||||
|
serverClientsInlobbies.Add(temp, new List<ServerClient>());
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -86,7 +90,7 @@ namespace Server.Models
|
|||||||
/// send a message to all tcp clients in the list
|
/// send a message to all tcp clients in the list
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="message">the message to send</param>
|
/// <param name="message">the message to send</param>
|
||||||
public void sendToAll(byte[] message)
|
public async void sendToAll(byte[] message)
|
||||||
{
|
{
|
||||||
foreach (ServerClient sc in serverClients)
|
foreach (ServerClient sc in serverClients)
|
||||||
{
|
{
|
||||||
@@ -94,6 +98,26 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void ServerClientDisconnect(ServerClient serverClient)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[SERVERCOMM] handling disconnect");
|
||||||
|
DisconnectClientAction?.Invoke();
|
||||||
|
int id = -1;
|
||||||
|
foreach (Lobby l in serverClientsInlobbies.Keys)
|
||||||
|
{
|
||||||
|
if (serverClientsInlobbies[l].Contains(serverClient))
|
||||||
|
{
|
||||||
|
id = l.ID;
|
||||||
|
}break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (id != -1)
|
||||||
|
{
|
||||||
|
LeaveLobby(serverClient.User, id);
|
||||||
|
SendToAllExcept(serverClient, JSONConvert.ConstructLobbyLeaveMessage(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void SendToAllExcept(string username, byte[] message)
|
public void SendToAllExcept(string username, byte[] message)
|
||||||
{
|
{
|
||||||
foreach (ServerClient sc in serverClients)
|
foreach (ServerClient sc in serverClients)
|
||||||
@@ -102,6 +126,14 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void SendToAllExcept(ServerClient sc, byte[] message)
|
||||||
|
{
|
||||||
|
foreach (ServerClient s in serverClients)
|
||||||
|
{
|
||||||
|
if (s != sc) s.sendMessage(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public void SendToLobby(Lobby lobby, byte[] message)
|
public void SendToLobby(Lobby lobby, byte[] message)
|
||||||
{
|
{
|
||||||
foreach (Lobby l in lobbies)
|
foreach (Lobby l in lobbies)
|
||||||
@@ -110,6 +142,7 @@ namespace Server.Models
|
|||||||
{
|
{
|
||||||
foreach (ServerClient sc in serverClientsInlobbies[l])
|
foreach (ServerClient sc in serverClientsInlobbies[l])
|
||||||
{
|
{
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] Sending message to lobby");
|
||||||
sc.sendMessage(message);
|
sc.sendMessage(message);
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -117,6 +150,50 @@ 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)
|
||||||
|
{
|
||||||
|
foreach (Lobby l in lobbies)
|
||||||
|
{
|
||||||
|
if (l.Users.Contains(user))
|
||||||
|
{
|
||||||
|
return l;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
public void AddToLobby(Lobby lobby, User user)
|
public void AddToLobby(Lobby lobby, User user)
|
||||||
{
|
{
|
||||||
foreach (Lobby l in lobbies)
|
foreach (Lobby l in lobbies)
|
||||||
@@ -125,6 +202,7 @@ namespace Server.Models
|
|||||||
{
|
{
|
||||||
bool succ;
|
bool succ;
|
||||||
l.AddUser(user, out succ);
|
l.AddUser(user, out succ);
|
||||||
|
Debug.WriteLine("[SERVERCOMM] added user to lobby, now contains " + l.PlayersIn);
|
||||||
if (!succ)
|
if (!succ)
|
||||||
{
|
{
|
||||||
// TODO send lobby full message
|
// TODO send lobby full message
|
||||||
@@ -144,5 +222,85 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public int HostForLobby(User user)
|
||||||
|
{
|
||||||
|
Lobby lobby = new Lobby( lobbies.Count + 1,0, 8);
|
||||||
|
lobbies.Add(lobby);
|
||||||
|
serverClientsInlobbies.Add(lobby, new List<ServerClient>());
|
||||||
|
user.Host = true;
|
||||||
|
AddToLobby(lobby, user);
|
||||||
|
return lobby.ID;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void JoinLobby(User user, int id, out bool isHost)
|
||||||
|
{
|
||||||
|
isHost = false;
|
||||||
|
foreach (Lobby l in lobbies)
|
||||||
|
{
|
||||||
|
if (l.ID == id)
|
||||||
|
{
|
||||||
|
if (l.Users.Count == 0)
|
||||||
|
{
|
||||||
|
user.Host = true;
|
||||||
|
isHost = true;
|
||||||
|
}
|
||||||
|
AddToLobby(l, user);
|
||||||
|
Debug.WriteLine($"{user.Username} joined lobby with id {id}");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void LeaveLobby(User user, int id)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[SERVERCOMM] removing user from lobby");
|
||||||
|
foreach (Lobby l in lobbies)
|
||||||
|
{
|
||||||
|
if (l.ID == id)
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[SERVERCOMM] checking for lobby with id {l.ID}");
|
||||||
|
|
||||||
|
foreach (User u in l.Users)
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[SERVERCOMM] checking if {u.Username} is {user.Username} ");
|
||||||
|
// contains doesn't work, so we'll do it like this...
|
||||||
|
if (u.Username == user.Username)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[SERVERCOMM] removed user from lobby!");
|
||||||
|
l.Users.Remove(user);
|
||||||
|
foreach (ServerClient sc in serverClients)
|
||||||
|
{
|
||||||
|
if (sc.User.Username == user.Username)
|
||||||
|
{
|
||||||
|
serverClientsInlobbies[l].Remove(sc);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (l.Users.Count != 0)
|
||||||
|
{
|
||||||
|
l.Users[0].Host = true;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void CloseALobby(int lobbyID)
|
||||||
|
{
|
||||||
|
foreach (Lobby lobby in lobbies)
|
||||||
|
{
|
||||||
|
if (lobby.ID == lobbyID)
|
||||||
|
{
|
||||||
|
lobby.LobbyJoinable = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,16 @@
|
|||||||
<UseWPF>true</UseWPF>
|
<UseWPF>true</UseWPF>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<None Remove="resources\WordsForGame.json" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Content Include="resources\WordsForGame.json">
|
||||||
|
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||||
|
</Content>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" />
|
<PackageReference Include="AsyncAwaitBestPractices" Version="4.3.0" />
|
||||||
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" />
|
<PackageReference Include="Extended.Wpf.Toolkit" Version="4.0.1" />
|
||||||
|
|||||||
@@ -33,6 +33,10 @@ namespace Server.ViewModels
|
|||||||
{
|
{
|
||||||
InformationModel.ClientsConnected++;
|
InformationModel.ClientsConnected++;
|
||||||
};
|
};
|
||||||
|
serverCommunication.DisconnectClientAction = () =>
|
||||||
|
{
|
||||||
|
InformationModel.ClientsConnected--;
|
||||||
|
};
|
||||||
//BitmapImage onlineImg = new BitmapImage(new Uri(@"/img/online.png",UriKind.Relative));
|
//BitmapImage onlineImg = new BitmapImage(new Uri(@"/img/online.png",UriKind.Relative));
|
||||||
//BitmapImage offlineImg = new BitmapImage(new Uri(@"/img/offline.png", UriKind.Relative));
|
//BitmapImage offlineImg = new BitmapImage(new Uri(@"/img/offline.png", UriKind.Relative));
|
||||||
|
|
||||||
|
|||||||
31
Server/resources/WordsForGame.json
Normal file
31
Server/resources/WordsForGame.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"filename": "wordsForGame",
|
||||||
|
"words": [
|
||||||
|
"teacher",
|
||||||
|
"love",
|
||||||
|
"engineer",
|
||||||
|
"supermarket",
|
||||||
|
"disaster",
|
||||||
|
"studio",
|
||||||
|
"restaurant",
|
||||||
|
"music",
|
||||||
|
"chocolate",
|
||||||
|
"dirt",
|
||||||
|
"thought",
|
||||||
|
"virus",
|
||||||
|
"lieutenant",
|
||||||
|
"painter",
|
||||||
|
"kiwi",
|
||||||
|
"power ranger",
|
||||||
|
"computer",
|
||||||
|
"people",
|
||||||
|
"candidate",
|
||||||
|
"security guard",
|
||||||
|
"Canada",
|
||||||
|
"teeth",
|
||||||
|
"army",
|
||||||
|
"airport",
|
||||||
|
"president",
|
||||||
|
"bedroom"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -1,37 +1,63 @@
|
|||||||
using Client;
|
using Client;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using System;
|
using Newtonsoft.Json.Linq;
|
||||||
using System.Collections.Generic;
|
using System;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using System.Text;
|
using System.IO;
|
||||||
|
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 GAME = 0x05;
|
||||||
|
public const byte MESSAGE_RECEIVED = 0x06;
|
||||||
|
public const byte RANDOMWORD = 0x07;
|
||||||
|
|
||||||
enum LobbyIdentifier
|
public const int CANVAS_WRITING = 0;
|
||||||
|
public const int CANVAS_RESET = 1;
|
||||||
|
|
||||||
|
public enum LobbyIdentifier
|
||||||
{
|
{
|
||||||
HOST,
|
HOST,
|
||||||
ADD,
|
JOIN,
|
||||||
|
JOIN_SUCCESS,
|
||||||
LEAVE,
|
LEAVE,
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,11 +69,192 @@ namespace SharedClientServer
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] ConstructLobbyDataMessage(Lobby lobby)
|
#region lobby messages
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyHostMessage()
|
||||||
{
|
{
|
||||||
return null;
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.HOST
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyHostCreatedMessage(int lobbyID)
|
||||||
|
{
|
||||||
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.HOST,
|
||||||
|
id = lobbyID
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyRequestMessage()
|
||||||
|
{
|
||||||
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.REQUEST
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyListMessage(Lobby[] lobbiesList)
|
||||||
|
{
|
||||||
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.LIST,
|
||||||
|
lobbies = lobbiesList
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
||||||
|
{
|
||||||
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.JOIN,
|
||||||
|
id = lobbyID
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyLeaveMessage(int lobbyID)
|
||||||
|
{
|
||||||
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.LEAVE,
|
||||||
|
id = lobbyID
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.identifier;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Lobby[] GetLobbiesFromMessage(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
JArray lobbiesArray = payload.lobbies;
|
||||||
|
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
||||||
|
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
||||||
|
Debug.WriteLine("lobbies in array: ");
|
||||||
|
foreach (Lobby l in lobbiesTemp)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("players: " + l.PlayersIn);
|
||||||
|
}
|
||||||
|
return lobbiesTemp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int GetLobbyID(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Lobby GetLobby(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
JObject dynamicAsObject = payload.lobby;
|
||||||
|
return dynamicAsObject.ToObject<Lobby>();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost)
|
||||||
|
{
|
||||||
|
return GetMessageToSend(LOBBY, new
|
||||||
|
{
|
||||||
|
identifier = LobbyIdentifier.JOIN_SUCCESS,
|
||||||
|
host = isHost
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool GetLobbyJoinIsHost(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
|
return payload.host;
|
||||||
|
}
|
||||||
|
|
||||||
|
#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
|
||||||
@@ -58,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
|
||||||
@@ -66,8 +274,43 @@ 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.
|
||||||
|
*/
|
||||||
|
|
||||||
|
public static string SendRandomWord(string filename)
|
||||||
|
{
|
||||||
|
dynamic words;
|
||||||
|
Random random = new Random();
|
||||||
|
string workingDir = Path.GetFullPath(@"..\Server");
|
||||||
|
string projDir = Directory.GetParent(workingDir).Parent.Parent.FullName;
|
||||||
|
string filePath = projDir += $@"\resources\{filename}";
|
||||||
|
|
||||||
|
using (StreamReader reader = new StreamReader(filePath))
|
||||||
|
{
|
||||||
|
string json = reader.ReadToEnd();
|
||||||
|
words = JsonConvert.DeserializeObject(json);
|
||||||
|
}
|
||||||
|
|
||||||
|
int index = random.Next(0, 24);
|
||||||
|
|
||||||
|
Debug.WriteLine($"[SERVERCLIENT] Sending random words {words}");
|
||||||
|
|
||||||
|
return words.words[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Client gets the payload and retrieves the word from the payload
|
||||||
|
*/
|
||||||
|
|
||||||
|
public static string GetRandomWord(byte[] json)
|
||||||
|
{
|
||||||
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
|
||||||
|
return payload.word;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,16 +66,34 @@ namespace Client
|
|||||||
|
|
||||||
public int PlayersIn
|
public int PlayersIn
|
||||||
{
|
{
|
||||||
get { return _playersIn; }
|
get { return _users.Count; }
|
||||||
set { _playersIn = value; }
|
set { _playersIn = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Set(Lobby lobby)
|
||||||
|
{
|
||||||
|
this._id = lobby._id;
|
||||||
|
this._users = lobby._users;
|
||||||
|
this._maxPlayers = lobby._maxPlayers;
|
||||||
|
}
|
||||||
|
|
||||||
public int MaxPlayers
|
public int MaxPlayers
|
||||||
{
|
{
|
||||||
get { return _maxPlayers; }
|
get { return _maxPlayers; }
|
||||||
set { _maxPlayers = value; }
|
set { _maxPlayers = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<User> Users
|
||||||
|
{
|
||||||
|
get { return _users; }
|
||||||
|
set { _users = value; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool LobbyJoinable
|
||||||
|
{
|
||||||
|
get { return _lobbyJoinable; }
|
||||||
|
set { _lobbyJoinable = value; }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
@@ -1,21 +1,27 @@
|
|||||||
using System;
|
using Newtonsoft.Json;
|
||||||
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
namespace SharedClientServer
|
namespace SharedClientServer
|
||||||
{
|
{
|
||||||
class 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;
|
||||||
|
|
||||||
public User(string username, int score, bool host)
|
[JsonConstructor]
|
||||||
|
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)
|
||||||
@@ -23,6 +29,43 @@ namespace SharedClientServer
|
|||||||
_username = username;
|
_username = username;
|
||||||
_score = 0;
|
_score = 0;
|
||||||
_host = false;
|
_host = false;
|
||||||
|
_turnToDraw = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool operator ==(User u1, User u2)
|
||||||
|
{
|
||||||
|
if (object.ReferenceEquals(u1, null))
|
||||||
|
{
|
||||||
|
return object.ReferenceEquals(u2, null);
|
||||||
|
}
|
||||||
|
return u1.Equals(u2 as object);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool operator !=(User u1, User u2)
|
||||||
|
{
|
||||||
|
if (object.ReferenceEquals(u1, null))
|
||||||
|
{
|
||||||
|
return object.ReferenceEquals(u2, null);
|
||||||
|
}
|
||||||
|
return u1.Equals(u2 as object);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override bool Equals(object obj)
|
||||||
|
{
|
||||||
|
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
return this.Equals(obj as User);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Equals([AllowNull] User other)
|
||||||
|
{
|
||||||
|
return other.Username == this.Username;
|
||||||
}
|
}
|
||||||
|
|
||||||
public string Username
|
public string Username
|
||||||
@@ -42,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; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user