Compare commits
56 Commits
feature/ha
...
feature/gu
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec08fbfced | ||
|
|
b14a7691b5 | ||
|
|
7df48ab322 | ||
|
|
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 | ||
|
|
e8a72e164f |
158
Client/Client.cs
158
Client/Client.cs
@@ -2,30 +2,54 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
using System.Net.Sockets;
|
using System.Net.Sockets;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Windows.Media;
|
||||||
|
using System.Windows;
|
||||||
|
|
||||||
using static SharedClientServer.JSONConvert;
|
using static SharedClientServer.JSONConvert;
|
||||||
|
|
||||||
namespace Client
|
namespace Client
|
||||||
{
|
{
|
||||||
|
public delegate void 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);
|
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 Callback OnLobbiesListReceived;
|
||||||
public Callback OnLobbyJoinSuccess;
|
public LobbyJoinCallback OnLobbyJoinSuccess;
|
||||||
public Callback OnLobbiesReceivedAndWaitingForHost;
|
public Callback OnLobbiesReceivedAndWaitingForHost;
|
||||||
|
public Callback OnServerDisconnect;
|
||||||
|
public Callback OnLobbyUpdate;
|
||||||
public LobbyCallback OnLobbyCreated;
|
public LobbyCallback OnLobbyCreated;
|
||||||
public LobbyCallback OnLobbyLeave;
|
public LobbyCallback OnLobbyLeave;
|
||||||
|
public RandomWord RandomWord;
|
||||||
|
public HandleIncomingMsg IncomingMsg;
|
||||||
|
public HandleIncomingPlayer IncomingPlayer;
|
||||||
private ClientData data = ClientData.Instance;
|
private ClientData data = ClientData.Instance;
|
||||||
|
public CanvasDataReceived CanvasDataReceived;
|
||||||
|
public CanvasReset CReset;
|
||||||
|
public HandleIncomingPlayer UpdateUserScores;
|
||||||
public Lobby[] Lobbies { get; set; }
|
public Lobby[] Lobbies { get; set; }
|
||||||
|
|
||||||
public Client(string username)
|
public Client(string username)
|
||||||
@@ -39,41 +63,63 @@ namespace Client
|
|||||||
private void OnConnect(IAsyncResult ar)
|
private void OnConnect(IAsyncResult ar)
|
||||||
{
|
{
|
||||||
Debug.Write("finished connecting to server");
|
Debug.Write("finished connecting to server");
|
||||||
this.tcpClient.EndConnect(ar);
|
try
|
||||||
this.stream = tcpClient.GetStream();
|
{
|
||||||
OnSuccessfullConnect?.Invoke();
|
this.tcpClient.EndConnect(ar);
|
||||||
SendMessage(JSONConvert.ConstructUsernameMessage(username));
|
this.stream = tcpClient.GetStream();
|
||||||
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null);
|
OnSuccessfullConnect?.Invoke();
|
||||||
|
OnLobbyUpdate = updateGameLobby;
|
||||||
|
SendMessage(JSONConvert.ConstructUsernameMessage(username));
|
||||||
|
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("Can't connect, retrying...");
|
||||||
|
tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnReadComplete(IAsyncResult ar)
|
private void OnReadComplete(IAsyncResult ar)
|
||||||
{
|
{
|
||||||
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)
|
||||||
@@ -95,9 +141,14 @@ namespace Client
|
|||||||
string textUsername = combo.Item1;
|
string textUsername = combo.Item1;
|
||||||
string textMsg = combo.Item2;
|
string textMsg = combo.Item2;
|
||||||
|
|
||||||
if(textUsername != data.User.Username)
|
if (textUsername != data.User.Username)
|
||||||
{
|
{
|
||||||
ViewModels.ViewModelGame.HandleIncomingMsg(textUsername, textMsg);
|
IncomingMsg?.Invoke(textUsername, textMsg);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (textMsg == data.User.RandomWord && !string.IsNullOrEmpty(data.User.RandomWord))
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[CLIENT] word has been guessed! {data.User.Username} + Word: {data.User.RandomWord}");
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO display username and message in chat window
|
//TODO display username and message in chat window
|
||||||
@@ -115,6 +166,7 @@ namespace Client
|
|||||||
Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
|
Lobbies = JSONConvert.GetLobbiesFromMessage(payload);
|
||||||
OnLobbiesListReceived?.Invoke();
|
OnLobbiesListReceived?.Invoke();
|
||||||
OnLobbiesReceivedAndWaitingForHost?.Invoke();
|
OnLobbiesReceivedAndWaitingForHost?.Invoke();
|
||||||
|
OnLobbyUpdate?.Invoke();
|
||||||
break;
|
break;
|
||||||
case LobbyIdentifier.HOST:
|
case LobbyIdentifier.HOST:
|
||||||
// we receive this when the server has made us a host of a new lobby
|
// we receive this when the server has made us a host of a new lobby
|
||||||
@@ -124,7 +176,7 @@ namespace Client
|
|||||||
OnLobbyCreated?.Invoke(lobbyCreatedID);
|
OnLobbyCreated?.Invoke(lobbyCreatedID);
|
||||||
break;
|
break;
|
||||||
case LobbyIdentifier.JOIN_SUCCESS:
|
case LobbyIdentifier.JOIN_SUCCESS:
|
||||||
OnLobbyJoinSuccess?.Invoke();
|
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
|
||||||
break;
|
break;
|
||||||
case LobbyIdentifier.LEAVE:
|
case LobbyIdentifier.LEAVE:
|
||||||
int lobbyLeaveID = JSONConvert.GetLobbyID(payload);
|
int lobbyLeaveID = JSONConvert.GetLobbyID(payload);
|
||||||
@@ -136,15 +188,56 @@ namespace Client
|
|||||||
|
|
||||||
case JSONConvert.CANVAS:
|
case JSONConvert.CANVAS:
|
||||||
// canvas data
|
// canvas data
|
||||||
|
//clientData.CanvasData = JSONConvert.getCoordinates(payload);
|
||||||
|
int type = JSONConvert.GetCanvasMessageType(payload);
|
||||||
|
switch (type)
|
||||||
|
{
|
||||||
|
case JSONConvert.CANVAS_RESET:
|
||||||
|
CReset?.Invoke();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case JSONConvert.CANVAS_WRITING:
|
||||||
|
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
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;
|
||||||
}
|
}
|
||||||
|
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));
|
||||||
@@ -155,6 +248,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; }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ using System.Collections.ObjectModel;
|
|||||||
using Client.Views;
|
using Client.Views;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Windows.Data;
|
using System.Windows.Data;
|
||||||
|
using System.Data;
|
||||||
|
using System.Windows.Controls.Primitives;
|
||||||
|
using System.Windows.Controls;
|
||||||
|
|
||||||
namespace Client
|
namespace Client
|
||||||
{
|
{
|
||||||
@@ -35,6 +38,10 @@ namespace Client
|
|||||||
client = ClientData.Instance.Client;
|
client = ClientData.Instance.Client;
|
||||||
client.OnLobbiesListReceived = updateLobbies;
|
client.OnLobbiesListReceived = updateLobbies;
|
||||||
client.OnLobbyLeave = leaveLobby;
|
client.OnLobbyLeave = leaveLobby;
|
||||||
|
client.OnServerDisconnect = () =>
|
||||||
|
{
|
||||||
|
Environment.Exit(0);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
OnHostButtonClick = new RelayCommand(hostGame);
|
OnHostButtonClick = new RelayCommand(hostGame);
|
||||||
@@ -54,16 +61,16 @@ namespace Client
|
|||||||
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
|
Debug.WriteLine("attempting to host game for " + ClientData.Instance.User.Username);
|
||||||
client.SendMessage(JSONConvert.ConstructLobbyHostMessage());
|
client.SendMessage(JSONConvert.ConstructLobbyHostMessage());
|
||||||
client.OnLobbyCreated = becomeHostForLobby;
|
client.OnLobbyCreated = becomeHostForLobby;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void becomeHostForLobby(int id)
|
private void becomeHostForLobby(int id)
|
||||||
{
|
{
|
||||||
|
|
||||||
Debug.WriteLine($"got host succes with data {id} ");
|
Debug.WriteLine($"got host succes with data {id} ");
|
||||||
wantToBeHost = true;
|
wantToBeHost = true;
|
||||||
wantToBeHostId = id;
|
wantToBeHostId = id;
|
||||||
|
ClientData.Instance.User.Host = true;
|
||||||
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
|
client.OnLobbiesReceivedAndWaitingForHost = hostLobbiesReceived;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void hostLobbiesReceived()
|
private void hostLobbiesReceived()
|
||||||
@@ -85,14 +92,21 @@ namespace Client
|
|||||||
|
|
||||||
private void joinLobby()
|
private void joinLobby()
|
||||||
{
|
{
|
||||||
// lobby die je wilt joinen verwijderen
|
if (SelectedLobby != null)
|
||||||
// nieuwe binnengekregen lobby toevoegen
|
{
|
||||||
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
|
if (SelectedLobby.PlayersIn == SelectedLobby.MaxPlayers || !SelectedLobby.LobbyJoinable)
|
||||||
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
client.OnLobbyJoinSuccess = OnLobbyJoinSuccess;
|
||||||
|
client.SendMessage(JSONConvert.ConstructLobbyJoinMessage(SelectedLobby.ID));
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnLobbyJoinSuccess()
|
private void OnLobbyJoinSuccess(bool isHost)
|
||||||
{
|
{
|
||||||
|
ClientData.Instance.User.Host = isHost;
|
||||||
startGameInLobby();
|
startGameInLobby();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,7 +114,7 @@ namespace Client
|
|||||||
|
|
||||||
private void updateLobbies()
|
private void updateLobbies()
|
||||||
{
|
{
|
||||||
Debug.WriteLine("updating lobbies...");
|
Debug.WriteLine("[VIEWMODEL] updating lobbies...");
|
||||||
Lobby[] lobbiesArr = client.Lobbies;
|
Lobby[] lobbiesArr = client.Lobbies;
|
||||||
Application.Current.Dispatcher.Invoke(delegate
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
{
|
{
|
||||||
@@ -110,6 +124,11 @@ namespace Client
|
|||||||
foreach (Lobby l in lobbiesArr)
|
foreach (Lobby l in lobbiesArr)
|
||||||
{
|
{
|
||||||
_lobbies.Add(l);
|
_lobbies.Add(l);
|
||||||
|
Lobby clientLobby = ClientData.Instance.Lobby;
|
||||||
|
if (l.ID == clientLobby?.ID)
|
||||||
|
{
|
||||||
|
clientLobby = l;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
});
|
});
|
||||||
@@ -163,5 +182,7 @@ namespace Client
|
|||||||
get { return _lobbies; }
|
get { return _lobbies; }
|
||||||
set { _lobbies = value; }
|
set { _lobbies = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,140 +1,271 @@
|
|||||||
|
using Client.Views;
|
||||||
using Client.Views;
|
using GalaSoft.MvvmLight.Command;
|
||||||
using GalaSoft.MvvmLight.Command;
|
using SharedClientServer;
|
||||||
using SharedClientServer;
|
using System;
|
||||||
using System.Collections.ObjectModel;
|
using System.Collections.Generic;
|
||||||
using System.ComponentModel;
|
using System.Collections.ObjectModel;
|
||||||
using System.Diagnostics;
|
using System.ComponentModel;
|
||||||
using System.Windows;
|
using System.Diagnostics;
|
||||||
using System.Windows.Input;
|
using System.Timers;
|
||||||
using System.Windows.Media;
|
using System.Windows;
|
||||||
using System.Windows.Shapes;
|
using System.Windows.Input;
|
||||||
|
using System.Windows.Media;
|
||||||
namespace Client.ViewModels
|
using System.Windows.Shapes;
|
||||||
{
|
|
||||||
class ViewModelGame : INotifyPropertyChanged
|
namespace Client.ViewModels
|
||||||
{
|
{
|
||||||
private ClientData data = ClientData.Instance;
|
class ViewModelGame : INotifyPropertyChanged
|
||||||
|
{
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
|
private ClientData data = ClientData.Instance;
|
||||||
private Point currentPoint = new Point();
|
private GameWindow window;
|
||||||
private Color color;
|
private Point currentPoint = new Point();
|
||||||
|
public Color color;
|
||||||
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
public double[][] buffer;
|
||||||
|
public int pos = 0;
|
||||||
private dynamic _payload;
|
public int maxLines = 50;
|
||||||
|
public Queue<double[][]> linesQueue;
|
||||||
public string _username;
|
private Timer queueTimer;
|
||||||
|
|
||||||
public string _message;
|
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
|
||||||
public string Message
|
public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
|
||||||
{
|
|
||||||
get
|
private dynamic _payload;
|
||||||
{
|
|
||||||
return _message;
|
public string _username;
|
||||||
}
|
|
||||||
set
|
public string _message;
|
||||||
{
|
public string Message
|
||||||
_message = value;
|
{
|
||||||
}
|
get
|
||||||
}
|
{
|
||||||
public ICommand OnKeyDown { get; set; }
|
return _message;
|
||||||
|
}
|
||||||
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
|
set
|
||||||
{
|
{
|
||||||
if (e.ButtonState == MouseButtonState.Pressed)
|
_message = value;
|
||||||
{
|
}
|
||||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
}
|
||||||
}
|
|
||||||
}
|
private string _randomWord;
|
||||||
|
public string RandomWord
|
||||||
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
|
{
|
||||||
{
|
get { return _randomWord; }
|
||||||
if (e.LeftButton == MouseButtonState.Pressed)
|
set { _randomWord = value; }
|
||||||
{
|
}
|
||||||
double[] coordinates = new double[4];
|
|
||||||
Line line = new Line();
|
public bool IsHost
|
||||||
|
{
|
||||||
line.Stroke = new SolidColorBrush(color);
|
get { return data.User.Host; }
|
||||||
//line.Stroke = SystemColors.WindowFrameBrush;
|
}
|
||||||
line.X1 = currentPoint.X;
|
|
||||||
line.Y1 = currentPoint.Y;
|
public ViewModelGame(GameWindow window)
|
||||||
line.X2 = e.GetPosition(window.CanvasForPaint).X;
|
{
|
||||||
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
|
this.window = window;
|
||||||
coordinates[0] = line.X1;
|
|
||||||
coordinates[1] = line.Y1;
|
buffer = new double[maxLines][];
|
||||||
coordinates[2] = line.X2;
|
linesQueue = new Queue<double[][]>();
|
||||||
coordinates[3] = line.Y2;
|
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
||||||
currentPoint = e.GetPosition(window.CanvasForPaint);
|
ButtonStartGame = new RelayCommand(BeginGame);
|
||||||
|
ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
|
||||||
window.CanvasForPaint.Children.Add(line);
|
data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
|
||||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(0x04, coordinates));
|
data.Client.CReset = CanvasResetData;
|
||||||
}
|
data.Client.RandomWord = HandleRandomWord;
|
||||||
}
|
data.Client.IncomingMsg = HandleIncomingMsg;
|
||||||
|
data.Client.IncomingPlayer = HandleIncomingPlayer;
|
||||||
public void Color_Picker(RoutedPropertyChangedEventArgs<Color?> e, GameWindow window)
|
data.Client.UpdateUserScores = UpdateUserScores;
|
||||||
{
|
}
|
||||||
Color colorSelected = new Color();
|
|
||||||
colorSelected.A = 255;
|
public ICommand OnKeyDown { get; set; }
|
||||||
colorSelected.R = window.ClrPcker_Background.SelectedColor.Value.R;
|
public ICommand ButtonStartGame { get; set; }
|
||||||
colorSelected.G = window.ClrPcker_Background.SelectedColor.Value.G;
|
public ICommand ButtonResetCanvas { get; set; }
|
||||||
colorSelected.B = window.ClrPcker_Background.SelectedColor.Value.B;
|
|
||||||
color = colorSelected;
|
public void BeginGame()
|
||||||
}
|
{
|
||||||
|
|
||||||
|
queueTimer = new Timer(50);
|
||||||
public ViewModelGame()
|
queueTimer.Start();
|
||||||
{
|
queueTimer.Elapsed += sendArrayFromQueue;
|
||||||
if (_payload == null)
|
data.Client.SendMessage(JSONConvert.ConstructGameStartData(data.Lobby.ID));
|
||||||
{
|
}
|
||||||
_message = "";
|
|
||||||
|
|
||||||
}
|
private void CanvasResetLocal()
|
||||||
else
|
{
|
||||||
{
|
this.window.CanvasForPaint.Children.Clear();
|
||||||
//_message = data.Message;
|
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.CANVAS, JSONConvert.CANVAS_RESET));
|
||||||
//_username = data.User.Username;
|
}
|
||||||
//Messages.Add($"{data.User.Username}: {Message}");
|
|
||||||
}
|
|
||||||
OnKeyDown = new RelayCommand(ChatBox_KeyDown);
|
public void Canvas_MouseDown(MouseButtonEventArgs e, GameWindow window)
|
||||||
}
|
{
|
||||||
|
if (e.ButtonState == MouseButtonState.Pressed)
|
||||||
private void ChatBox_KeyDown()
|
{
|
||||||
{
|
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||||
//if enter then clear textbox and send message.
|
}
|
||||||
if (Message != string.Empty) AddMessage(Message);
|
}
|
||||||
Message = string.Empty;
|
|
||||||
}
|
public void Canvas_MouseMove(MouseEventArgs e, GameWindow window)
|
||||||
|
{
|
||||||
internal void AddMessage(string message)
|
if (e.LeftButton == MouseButtonState.Pressed)
|
||||||
{
|
{
|
||||||
Messages.Add($"{data.User.Username}: {message}");
|
double[] coordinates = new double[4];
|
||||||
|
Line line = new Line();
|
||||||
_payload = new
|
|
||||||
{
|
line.Stroke = new SolidColorBrush(color);
|
||||||
username = data.User.Username,
|
//line.Stroke = SystemColors.WindowFrameBrush;
|
||||||
message = message
|
line.X1 = currentPoint.X;
|
||||||
};
|
line.Y1 = currentPoint.Y;
|
||||||
|
line.X2 = e.GetPosition(window.CanvasForPaint).X;
|
||||||
//Broadcast the message after adding it to the list!
|
line.Y2 = e.GetPosition(window.CanvasForPaint).Y;
|
||||||
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
|
coordinates[0] = line.X1;
|
||||||
}
|
coordinates[1] = line.Y1;
|
||||||
|
coordinates[2] = line.X2;
|
||||||
public static void HandleIncomingMsg(string username, string message)
|
coordinates[3] = line.Y2;
|
||||||
{
|
currentPoint = e.GetPosition(window.CanvasForPaint);
|
||||||
Application.Current.Dispatcher.Invoke(delegate
|
buffer[pos] = coordinates;
|
||||||
{
|
pos++;
|
||||||
Messages.Add($"{username}: {message}");
|
|
||||||
});
|
window.CanvasForPaint.Children.Add(line);
|
||||||
}
|
if (pos == maxLines)
|
||||||
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
|
{
|
||||||
{
|
double[][] temp = new double[maxLines][];
|
||||||
Debug.WriteLine("Leaving...");
|
for (int i = 0; i < maxLines; i++)
|
||||||
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
|
{
|
||||||
}
|
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()
|
||||||
|
{
|
||||||
|
this.window.CanvasForPaint.Children.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ChatBox_KeyDown()
|
||||||
|
{
|
||||||
|
//if enter then clear textbox and send message.
|
||||||
|
if (Message != string.Empty) AddMessage(Message);
|
||||||
|
Message = string.Empty;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal void AddMessage(string message)
|
||||||
|
{
|
||||||
|
Messages.Add($"{data.User.Username}: {message}");
|
||||||
|
|
||||||
|
_payload = new
|
||||||
|
{
|
||||||
|
username = data.User.Username,
|
||||||
|
message = message
|
||||||
|
};
|
||||||
|
|
||||||
|
//Broadcast the message after adding it to the list!
|
||||||
|
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void HandleIncomingMsg(string username, string message)
|
||||||
|
{
|
||||||
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
|
{
|
||||||
|
Messages.Add($"{username}: {message}");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("Leaving...");
|
||||||
|
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void HandleRandomWord(string randomWord)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[CLIENT] Reached the handle random word method!");
|
||||||
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
|
{
|
||||||
|
RandomWord = randomWord;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
public void HandleIncomingPlayer(Lobby lobby)
|
||||||
|
{
|
||||||
|
Application.Current.Dispatcher.Invoke(delegate
|
||||||
|
{
|
||||||
|
Players.Clear();
|
||||||
|
foreach (var item in lobby.Users)
|
||||||
|
{
|
||||||
|
Players.Add(item.Username + "\n" + item.Score);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateUserScores(Lobby newLobby) {
|
||||||
|
Debug.WriteLine("[GAME] updating user scores");
|
||||||
|
List<User> newUsers = newLobby.Users;
|
||||||
|
// go over all users in current lobby
|
||||||
|
foreach (User user in data.Lobby?.Users)
|
||||||
|
{
|
||||||
|
// check with all users in new lobby
|
||||||
|
foreach (User newUser in newUsers)
|
||||||
|
{
|
||||||
|
// and update the score
|
||||||
|
if (newUser.Username == user.Username)
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[GAME] setting score of {user.Username} to {newUser.Score}. it was {user.Score}");
|
||||||
|
user.Score = newUser.Score;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// update all the scores in the player list
|
||||||
|
HandleIncomingPlayer(newLobby);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -22,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" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/>
|
||||||
|
</Grid>
|
||||||
|
|
||||||
|
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
|
||||||
|
|
||||||
<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>
|
||||||
@@ -47,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>
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ namespace Client.Views
|
|||||||
private ViewModelGame viewModel;
|
private ViewModelGame viewModel;
|
||||||
public GameWindow()
|
public GameWindow()
|
||||||
{
|
{
|
||||||
this.viewModel = new ViewModelGame();
|
this.viewModel = new ViewModelGame(this);
|
||||||
DataContext = this.viewModel;
|
DataContext = this.viewModel;
|
||||||
Closing += this.viewModel.LeaveGame;
|
Closing += this.viewModel.LeaveGame;
|
||||||
InitializeComponent();
|
InitializeComponent();
|
||||||
@@ -36,16 +36,6 @@ namespace Client.Views
|
|||||||
private void CanvasReset_Click(object sender, RoutedEventArgs e)
|
private void CanvasReset_Click(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
CanvasForPaint.Children.Clear();
|
CanvasForPaint.Children.Clear();
|
||||||
|
|
||||||
//FOR FUTURE USE, IF NECCESSARY
|
|
||||||
//TEST.Children.Clear();
|
|
||||||
|
|
||||||
//foreach (UIElement child in CanvasForPaint.Children)
|
|
||||||
//{
|
|
||||||
// var xaml = System.Windows.Markup.XamlWriter.Save(child);
|
|
||||||
// var deepCopy = System.Windows.Markup.XamlReader.Parse(xaml) as UIElement;
|
|
||||||
// TEST.Children.Add(deepCopy);
|
|
||||||
//}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e)
|
private void ClrPcker_Background_SelectedColorChanged_1(object sender, RoutedPropertyChangedEventArgs<Color?> e)
|
||||||
@@ -53,5 +43,9 @@ namespace Client.Views
|
|||||||
viewModel.Color_Picker(e, this);
|
viewModel.Color_Picker(e, this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void CanvasForPaint_MouseUp(object sender, MouseButtonEventArgs e)
|
||||||
|
{
|
||||||
|
viewModel.Canvas_MouseUp(sender, e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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,9 @@
|
|||||||
<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"/>
|
||||||
|
|
||||||
|
<Label Grid.Row="3" Grid.Column="0" Content="Tip of the century: base64 != UTF8!" FontSize="20" FontWeight="Bold"/>
|
||||||
</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,8 +27,12 @@ namespace Client.Views
|
|||||||
|
|
||||||
private void Button_EnterUsername(object sender, RoutedEventArgs e)
|
private void Button_EnterUsername(object sender, RoutedEventArgs e)
|
||||||
{
|
{
|
||||||
User user = new User(usernameTextbox.Text);
|
string name = usernameTextbox.Text;
|
||||||
|
if (name == string.Empty) return;
|
||||||
|
User user = new User(name);
|
||||||
|
|
||||||
Client client = new Client(user.Username);
|
Client client = new Client(user.Username);
|
||||||
|
LoginButton.IsEnabled = false;
|
||||||
client.OnSuccessfullConnect = () =>
|
client.OnSuccessfullConnect = () =>
|
||||||
{
|
{
|
||||||
// because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread
|
// because we need to start the main window on a UI thread, we need to let the dispatcher handle it, which will execute the code on the ui thread
|
||||||
@@ -41,6 +46,7 @@ namespace Client.Views
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>
|
||||||
|
|||||||
@@ -6,22 +6,28 @@ 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 static SharedClientServer.JSONConvert;
|
using static SharedClientServer.JSONConvert;
|
||||||
|
|
||||||
namespace Server.Models
|
namespace Server.Models
|
||||||
{
|
{
|
||||||
|
public delegate void Callback();
|
||||||
class ServerClient : ObservableObject
|
class ServerClient : ObservableObject
|
||||||
{
|
{
|
||||||
private TcpClient tcpClient;
|
private TcpClient tcpClient;
|
||||||
private NetworkStream stream;
|
private NetworkStream stream;
|
||||||
private byte[] buffer = new byte[1024];
|
private byte[] buffer = new byte[2048];
|
||||||
private byte[] totalBuffer = new byte[1024];
|
private byte[] totalBuffer = new byte[2048];
|
||||||
|
private string _randomWord = "";
|
||||||
private int totalBufferReceived = 0;
|
private int totalBufferReceived = 0;
|
||||||
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.
|
||||||
@@ -45,49 +51,60 @@ 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);
|
||||||
|
}
|
||||||
|
catch (IOException e)
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] Client disconnected! exception was " + e.Message);
|
||||||
|
tcpClient.Close();
|
||||||
|
ServerCommunication.INSTANCE.ServerClientDisconnect(this);
|
||||||
}
|
}
|
||||||
// start reading for a new message
|
|
||||||
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -99,21 +116,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:
|
||||||
@@ -129,6 +146,11 @@ namespace Server.Models
|
|||||||
message = textMsg
|
message = textMsg
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (textMsg == _randomWord && !string.IsNullOrEmpty(_randomWord))
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[SERVERCLIENT] word has been guessed! {User.Username} + Word: {_randomWord}");
|
||||||
|
}
|
||||||
|
|
||||||
//Sends the incomming message to be broadcast to all of the clients inside the current lobby.
|
//Sends the incomming message to be broadcast to all of the clients inside the current lobby.
|
||||||
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
|
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
|
||||||
break;
|
break;
|
||||||
@@ -136,13 +158,59 @@ namespace Server.Models
|
|||||||
case JSONConvert.LOBBY:
|
case JSONConvert.LOBBY:
|
||||||
// lobby data
|
// lobby data
|
||||||
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
|
LobbyIdentifier l = JSONConvert.GetLobbyIdentifier(payload);
|
||||||
handleLobbyMessage(payload,l);
|
handleLobbyMessage(payload, l);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case JSONConvert.CANVAS:
|
case JSONConvert.CANVAS:
|
||||||
Debug.WriteLine("GOT A MESSAGE FROM THE CLIENT ABOUT THE CANVAS!!!");
|
|
||||||
|
int typeToCheck = JSONConvert.GetCanvasMessageType(payload);
|
||||||
|
switch (typeToCheck)
|
||||||
|
{
|
||||||
|
case JSONConvert.CANVAS_WRITING:
|
||||||
|
dynamic canvasData = new
|
||||||
|
{
|
||||||
|
canvasType = typeToCheck,
|
||||||
|
coords = JSONConvert.getCoordinates(payload),
|
||||||
|
color = JSONConvert.getCanvasDrawingColor(payload)
|
||||||
|
};
|
||||||
|
serverCom.SendToLobby(serverCom.GetLobbyForUser(User),JSONConvert.GetMessageToSend(JSONConvert.CANVAS,canvasData));
|
||||||
|
break;
|
||||||
|
|
||||||
|
case JSONConvert.CANVAS_RESET:
|
||||||
|
dynamic canvasDataForReset = new
|
||||||
|
{
|
||||||
|
type = 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");
|
||||||
|
string command = JSONConvert.GetGameCommand(payload);
|
||||||
|
switch (command)
|
||||||
|
{
|
||||||
|
case "startGame":
|
||||||
|
int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
|
||||||
|
serverCom.CloseALobby(lobbyID);
|
||||||
|
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
|
||||||
|
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;
|
||||||
@@ -166,9 +234,20 @@ namespace Server.Models
|
|||||||
break;
|
break;
|
||||||
case LobbyIdentifier.JOIN:
|
case LobbyIdentifier.JOIN:
|
||||||
int id = JSONConvert.GetLobbyID(payload);
|
int id = JSONConvert.GetLobbyID(payload);
|
||||||
ServerCommunication.INSTANCE.JoinLobby(this.User,id);
|
bool isHost;
|
||||||
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage());
|
ServerCommunication.INSTANCE.JoinLobby(this.User,id, out isHost);
|
||||||
|
sendMessage(JSONConvert.ConstructLobbyJoinSuccessMessage(isHost));
|
||||||
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
|
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;
|
break;
|
||||||
case LobbyIdentifier.LEAVE:
|
case LobbyIdentifier.LEAVE:
|
||||||
id = JSONConvert.GetLobbyID(payload);
|
id = JSONConvert.GetLobbyID(payload);
|
||||||
@@ -179,6 +258,21 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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>
|
||||||
/// sends a message to the tcp client
|
/// sends a message to the tcp client
|
||||||
/// </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;
|
||||||
|
|
||||||
|
|
||||||
@@ -89,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)
|
||||||
{
|
{
|
||||||
@@ -97,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)
|
||||||
@@ -105,8 +126,32 @@ 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)
|
||||||
|
{
|
||||||
|
if (l == lobby)
|
||||||
|
{
|
||||||
|
foreach (ServerClient sc in serverClientsInlobbies[l])
|
||||||
|
{
|
||||||
|
Debug.WriteLine("[SERVERCLIENT] Sending message");
|
||||||
|
sc.sendMessage(message);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SendCanvasDataToLobby(Lobby lobby, string username, byte[] message)
|
||||||
|
{
|
||||||
foreach (Lobby l in lobbies)
|
foreach (Lobby l in lobbies)
|
||||||
{
|
{
|
||||||
if (l == lobby)
|
if (l == lobby)
|
||||||
@@ -117,7 +162,7 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public Lobby GetLobbyForUser(User user)
|
public Lobby GetLobbyForUser(User user)
|
||||||
@@ -172,12 +217,18 @@ namespace Server.Models
|
|||||||
return lobby.ID;
|
return lobby.ID;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void JoinLobby(User user, int id)
|
public void JoinLobby(User user, int id, out bool isHost)
|
||||||
{
|
{
|
||||||
|
isHost = false;
|
||||||
foreach (Lobby l in lobbies)
|
foreach (Lobby l in lobbies)
|
||||||
{
|
{
|
||||||
if (l.ID == id)
|
if (l.ID == id)
|
||||||
{
|
{
|
||||||
|
if (l.Users.Count == 0)
|
||||||
|
{
|
||||||
|
user.Host = true;
|
||||||
|
isHost = true;
|
||||||
|
}
|
||||||
AddToLobby(l, user);
|
AddToLobby(l, user);
|
||||||
Debug.WriteLine($"{user.Username} joined lobby with id {id}");
|
Debug.WriteLine($"{user.Username} joined lobby with id {id}");
|
||||||
break;
|
break;
|
||||||
@@ -219,5 +270,16 @@ namespace Server.Models
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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,11 +1,13 @@
|
|||||||
using Client;
|
using Client;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using Newtonsoft.Json.Linq;
|
using Newtonsoft.Json.Linq;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
|
using System.IO;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
using System.Windows.Media;
|
||||||
|
|
||||||
namespace SharedClientServer
|
namespace SharedClientServer
|
||||||
{
|
{
|
||||||
@@ -15,6 +17,13 @@ namespace SharedClientServer
|
|||||||
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;
|
||||||
|
|
||||||
|
public const int CANVAS_WRITING = 0;
|
||||||
|
public const int CANVAS_RESET = 1;
|
||||||
|
|
||||||
|
|
||||||
public enum LobbyIdentifier
|
public enum LobbyIdentifier
|
||||||
{
|
{
|
||||||
@@ -25,9 +34,10 @@ namespace SharedClientServer
|
|||||||
LIST,
|
LIST,
|
||||||
REQUEST
|
REQUEST
|
||||||
}
|
}
|
||||||
|
|
||||||
public static (string,string) GetUsernameAndMessage(byte[] json)
|
public static (string,string) GetUsernameAndMessage(byte[] json)
|
||||||
{
|
{
|
||||||
string msg = Encoding.ASCII.GetString(json);
|
string msg = Encoding.UTF8.GetString(json);
|
||||||
dynamic payload = JsonConvert.DeserializeObject(msg);
|
dynamic payload = JsonConvert.DeserializeObject(msg);
|
||||||
|
|
||||||
return (payload.username, payload.message);
|
return (payload.username, payload.message);
|
||||||
@@ -35,7 +45,7 @@ namespace SharedClientServer
|
|||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,6 +93,7 @@ namespace SharedClientServer
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
public static byte[] ConstructLobbyJoinMessage(int lobbyID)
|
||||||
{
|
{
|
||||||
return GetMessageToSend(LOBBY, new
|
return GetMessageToSend(LOBBY, new
|
||||||
@@ -102,13 +113,13 @@ namespace SharedClientServer
|
|||||||
}
|
}
|
||||||
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
public static LobbyIdentifier GetLobbyIdentifier(byte[] json)
|
||||||
{
|
{
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
return payload.identifier;
|
return payload.identifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Lobby[] GetLobbiesFromMessage(byte[] json)
|
public static Lobby[] GetLobbiesFromMessage(byte[] json)
|
||||||
{
|
{
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
JArray lobbiesArray = payload.lobbies;
|
JArray lobbiesArray = payload.lobbies;
|
||||||
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
Debug.WriteLine("[JSONCONVERT] got lobbies from message" + lobbiesArray.ToString());
|
||||||
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
Lobby[] lobbiesTemp = lobbiesArray.ToObject<Lobby[]>();
|
||||||
@@ -122,23 +133,98 @@ namespace SharedClientServer
|
|||||||
|
|
||||||
public static int GetLobbyID(byte[] json)
|
public static int GetLobbyID(byte[] json)
|
||||||
{
|
{
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
return payload.id;
|
return payload.id;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Lobby GetLobby(byte[] json)
|
public static Lobby GetLobby(byte[] json)
|
||||||
{
|
{
|
||||||
dynamic payload = JsonConvert.DeserializeObject(Encoding.ASCII.GetString(json));
|
dynamic payload = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(json));
|
||||||
JObject dynamicAsObject = payload.lobby;
|
JObject dynamicAsObject = payload.lobby;
|
||||||
return dynamicAsObject.ToObject<Lobby>();
|
return dynamicAsObject.ToObject<Lobby>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public static byte[] ConstructLobbyJoinSuccessMessage()
|
public static byte[] ConstructLobbyJoinSuccessMessage(bool isHost)
|
||||||
{
|
{
|
||||||
return GetMessageToSend(LOBBY, new { identifier = LobbyIdentifier.JOIN_SUCCESS});
|
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
|
#endregion
|
||||||
|
|
||||||
|
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 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)
|
||||||
|
{
|
||||||
|
string startGame = "startGame";
|
||||||
|
return GetMessageToSend(GAME, new
|
||||||
|
{
|
||||||
|
command = startGame,
|
||||||
|
lobbyToStart = lobbyID
|
||||||
|
}); ;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string GetGameCommand(byte[] payload)
|
||||||
|
{
|
||||||
|
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
||||||
|
return json.command;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int GetStartGameLobbyID(byte[] payload)
|
||||||
|
{
|
||||||
|
dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
|
||||||
|
return json.lobbyToStart;
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// constructs a message that can be sent to the clients or server
|
/// constructs a message that can be sent to the clients or server
|
||||||
/// </summary>
|
/// </summary>
|
||||||
@@ -148,7 +234,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
|
||||||
@@ -159,6 +246,40 @@ namespace SharedClientServer
|
|||||||
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[index];
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* 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
|
internal class Lobby : INotifyPropertyChanged
|
||||||
{
|
{
|
||||||
public event PropertyChangedEventHandler PropertyChanged;
|
public event PropertyChangedEventHandler PropertyChanged;
|
||||||
|
|
||||||
@@ -14,6 +14,7 @@ namespace Client
|
|||||||
private int _id;
|
private int _id;
|
||||||
private int _playersIn;
|
private int _playersIn;
|
||||||
private int _maxPlayers;
|
private int _maxPlayers;
|
||||||
|
private bool _lobbyJoinable;
|
||||||
//private List<string> _usernames;
|
//private List<string> _usernames;
|
||||||
private List<User> _users;
|
private List<User> _users;
|
||||||
|
|
||||||
@@ -34,6 +35,7 @@ namespace Client
|
|||||||
_maxPlayers = maxPlayers;
|
_maxPlayers = maxPlayers;
|
||||||
//_usernames = new List<string>();
|
//_usernames = new List<string>();
|
||||||
_users = new List<User>();
|
_users = new List<User>();
|
||||||
|
_lobbyJoinable = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void AddUser(string username, out bool succes)
|
public void AddUser(string username, out bool succes)
|
||||||
@@ -41,7 +43,7 @@ namespace Client
|
|||||||
succes = false;
|
succes = false;
|
||||||
if (_users.Count < _maxPlayers)
|
if (_users.Count < _maxPlayers)
|
||||||
{
|
{
|
||||||
_users.Add(new User(username, 0, false));
|
_users.Add(new User(username, 0, false, false));
|
||||||
succes = true;
|
succes = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -87,6 +89,11 @@ namespace Client
|
|||||||
set { _users = value; }
|
set { _users = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool LobbyJoinable
|
||||||
|
{
|
||||||
|
get { return _lobbyJoinable; }
|
||||||
|
set { _lobbyJoinable = value; }
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,14 +11,17 @@ namespace SharedClientServer
|
|||||||
private string _username;
|
private string _username;
|
||||||
private int _score;
|
private int _score;
|
||||||
private bool _host;
|
private bool _host;
|
||||||
|
private bool _turnToDraw;
|
||||||
private string _message;
|
private string _message;
|
||||||
|
private string _randomWord;
|
||||||
|
|
||||||
[JsonConstructor]
|
[JsonConstructor]
|
||||||
public User(string username, int score, bool host)
|
public User(string username, int score, bool host, bool turnToDraw)
|
||||||
{
|
{
|
||||||
_username = username;
|
_username = username;
|
||||||
_score = score;
|
_score = score;
|
||||||
_host = host;
|
_host = host;
|
||||||
|
_turnToDraw = turnToDraw;
|
||||||
}
|
}
|
||||||
|
|
||||||
public User(string username)
|
public User(string username)
|
||||||
@@ -26,6 +29,7 @@ namespace SharedClientServer
|
|||||||
_username = username;
|
_username = username;
|
||||||
_score = 0;
|
_score = 0;
|
||||||
_host = false;
|
_host = false;
|
||||||
|
_turnToDraw = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static bool operator ==(User u1, User u2)
|
public static bool operator ==(User u1, User u2)
|
||||||
@@ -81,5 +85,16 @@ namespace SharedClientServer
|
|||||||
get { return _host; }
|
get { return _host; }
|
||||||
set { _host = value; }
|
set { _host = value; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public bool TurnToDraw
|
||||||
|
{
|
||||||
|
get { return _turnToDraw; }
|
||||||
|
set { _turnToDraw = value; }
|
||||||
|
}
|
||||||
|
public string RandomWord
|
||||||
|
{
|
||||||
|
get { return _randomWord; }
|
||||||
|
set { _randomWord = value; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user