35 Commits

Author SHA1 Message Date
Sem van der Hoeven
7ce04447d0 [FIX] fixed canvas data being sent to person drawing 2020-10-23 17:44:39 +02:00
Sem van der Hoeven
2d64accf09 [EDIT] made loginviewmodel kinda mvvm 2020-10-23 17:35:33 +02:00
Sem van der Hoeven
1d8963ec60 [REMOVE] removed the checks for who is host 2020-10-23 17:27:43 +02:00
Lars
13cf0e44ee [ADDED] a begin for the turn base 2020-10-23 16:46:29 +02:00
Lars
eee4f0347f Merge branch 'master' into setupBranch 2020-10-23 15:54:21 +02:00
SemvdH
9558c75eab Merge pull request #14 from SemvdH/feature/guesedWord
[ADDITION] added a new property to the user (may be removed later on)…
2020-10-23 15:51:30 +02:00
Dogukan
ec08fbfced [ADDITION] added a new property to the user (may be removed later on), and made a check for the random word 2020-10-23 15:47:52 +02:00
SemvdH
87ebdeef58 Merge pull request #13 from SemvdH/feature/timer
Feature/timer
2020-10-23 15:45:12 +02:00
Sem van der Hoeven
bf09dba850 [ADD] added timer start on next round message receive 2020-10-23 15:44:18 +02:00
Lars
fd59368c03 Merge branch 'master' into setupBranch 2020-10-23 14:59:41 +02:00
SemvdH
b14a7691b5 Merge pull request #12 from SemvdH/hotfix/fixClientServerComms
[FIX] Callbacks weren't properly called
2020-10-23 14:56:45 +02:00
Dogukan
7df48ab322 [FIX] Callbacks weren't properly called 2020-10-23 14:49:20 +02:00
Sem van der Hoeven
6512518fb7 [FIX] made first user in lobby a host if the host leaves 2020-10-23 14:30:16 +02:00
Sem van der Hoeven
80d970da35 [FIX] made login impossible if no name was entered 2020-10-23 14:13:22 +02:00
SemvdH
2c7bf3e217 Merge pull request #11 from SemvdH/setupBranch
merge Setup branch into master
2020-10-23 14:06:36 +02:00
SemvdH
92f57a87bc Merge pull request #10 from SemvdH/update-scores
added updating scores on lobby list receive
2020-10-23 13:59:28 +02:00
Sem van der Hoeven
da5528c7b2 added updating scores on lobby list receive 2020-10-23 13:58:44 +02:00
Lars
c16f7cf68f Merge branch 'master' into setupBranch 2020-10-23 13:11:56 +02:00
SemvdH
5c2dea3ab4 Merge pull request #9 from SemvdH/feature/playerList
Feature/player list
2020-10-23 12:53:43 +02:00
SemvdH
e2f9dfec78 Merge branch 'master' into feature/playerList 2020-10-23 12:53:35 +02:00
Dogukan
7fcf424b65 [FIX] fixed the async for updating the label, as well as the chat messages 2020-10-23 12:48:27 +02:00
Dogukan
97be0f937c [Cleanup] cleaned a null checking if-statement for the lobby id 2020-10-23 12:42:24 +02:00
Dogukan
09056818df Merge remote-tracking branch 'origin/feature/playerList' into feature/playerList 2020-10-23 12:33:06 +02:00
Dogukan
8d4f72c09d [CHANGED] Static function for handling to callbacks 2020-10-23 12:32:11 +02:00
Sem van der Hoeven
f51d310787 [EDIT] removed uneccesary call to updatelobbies 2020-10-23 12:31:01 +02:00
Sem van der Hoeven
9e829c47ff [FIX] lobbies now get correctly updated when someone leaves or joins 2020-10-23 12:26:31 +02:00
Lars
f5d55ef405 [FIX] randomword is not visible 2020-10-23 11:54:43 +02:00
Dogukan
0d44b2d840 [TRY] tried to bind the label data, doesn't work yet 2020-10-23 11:30:06 +02:00
Dogukan
1c04ab95c0 [ADDED] player list in lobby updates on join! Not on disconnect yet. Tried to set the word label doesn't work yet. 2020-10-22 23:54:07 +02:00
Sem van der Hoeven
ddf4594c5e [ADD] add canvas data sending on mouse up 2020-10-22 22:47:11 +02:00
Sem van der Hoeven
09f9e227b8 merge stuff 2020-10-22 22:35:29 +02:00
SemvdH
ec156f3dc6 Merge pull request #8 from SemvdH/stateful-canvas
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
2020-10-22 22:31:09 +02:00
Lars
24eb43239b [FIX] nog when you click host, you are able to click the start game button 2020-10-22 22:02:41 +02:00
Lars
335d17838c Merge branch 'master' into setupBranch 2020-10-22 20:04:30 +02:00
Lars
242c435ac7 added something little, not that very important tho 2020-10-22 17:46:45 +02:00
12 changed files with 342 additions and 107 deletions

View File

@@ -13,9 +13,15 @@ using static SharedClientServer.JSONConvert;
namespace Client namespace Client
{ {
public delegate void LobbyJoinCallback(bool isHost); public delegate void LobbyJoinCallback(bool isHost);
public delegate void RandomWord(string word);
public delegate void HandleIncomingMsg(string username, string msg);
internal delegate void HandleIncomingPlayer(Lobby lobby);
public delegate void CanvasDataReceived(double[][] coordinates, Color color); public delegate void CanvasDataReceived(double[][] coordinates, Color color);
public delegate void CanvasReset(); public delegate void CanvasReset();
public delegate void LobbyCallback(int id); public delegate void LobbyCallback(int id);
class Client : ObservableObject class Client : ObservableObject
{ {
@@ -34,11 +40,16 @@ namespace Client
public LobbyJoinCallback OnLobbyJoinSuccess; public LobbyJoinCallback OnLobbyJoinSuccess;
public Callback OnLobbiesReceivedAndWaitingForHost; public Callback OnLobbiesReceivedAndWaitingForHost;
public Callback OnServerDisconnect; 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 CanvasDataReceived CanvasDataReceived;
public CanvasReset CReset; public CanvasReset CReset;
public HandleIncomingPlayer UpdateUserScores;
public Lobby[] Lobbies { get; set; } public Lobby[] Lobbies { get; set; }
public Client(string username) public Client(string username)
@@ -57,10 +68,12 @@ namespace Client
this.tcpClient.EndConnect(ar); this.tcpClient.EndConnect(ar);
this.stream = tcpClient.GetStream(); this.stream = tcpClient.GetStream();
OnSuccessfullConnect?.Invoke(); OnSuccessfullConnect?.Invoke();
OnLobbyUpdate = updateGameLobby;
SendMessage(JSONConvert.ConstructUsernameMessage(username)); SendMessage(JSONConvert.ConstructUsernameMessage(username));
this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete),null); this.stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} catch (Exception e) }
catch (Exception e)
{ {
Debug.WriteLine("Can't connect, retrying..."); Debug.WriteLine("Can't connect, retrying...");
tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null); tcpClient.BeginConnect("localhost", Port, new AsyncCallback(OnConnect), null);
@@ -72,6 +85,7 @@ namespace Client
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 try
{ {
int amountReceived = stream.EndRead(ar); int amountReceived = stream.EndRead(ar);
@@ -81,7 +95,6 @@ namespace Client
throw new OutOfMemoryException("buffer too small"); throw new OutOfMemoryException("buffer too small");
} }
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived); Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, amountReceived);
totalBufferReceived += amountReceived; totalBufferReceived += amountReceived;
@@ -101,7 +114,8 @@ namespace Client
ar.AsyncWaitHandle.WaitOne(); ar.AsyncWaitHandle.WaitOne();
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnReadComplete), null);
} catch (IOException e) }
catch (IOException e)
{ {
Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message); Debug.WriteLine("[CLIENT] server not responding! got error: " + e.Message);
OnServerDisconnect?.Invoke(); OnServerDisconnect?.Invoke();
@@ -127,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
@@ -147,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
@@ -156,7 +176,6 @@ namespace Client
OnLobbyCreated?.Invoke(lobbyCreatedID); OnLobbyCreated?.Invoke(lobbyCreatedID);
break; break;
case LobbyIdentifier.JOIN_SUCCESS: case LobbyIdentifier.JOIN_SUCCESS:
OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload)); OnLobbyJoinSuccess?.Invoke(JSONConvert.GetLobbyJoinIsHost(payload));
break; break;
case LobbyIdentifier.LEAVE: case LobbyIdentifier.LEAVE:
@@ -179,33 +198,78 @@ namespace Client
case JSONConvert.CANVAS_WRITING: case JSONConvert.CANVAS_WRITING:
CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload)); CanvasDataReceived?.Invoke(JSONConvert.getCoordinates(payload), JSONConvert.getCanvasDrawingColor(payload));
// we hebben gedrawed, dus stuur dat we weer kunnen drawen
break; break;
} }
break; break;
case JSONConvert.RANDOMWORD: case JSONConvert.RANDOMWORD:
//Flag byte for receiving the random word. //Flag byte for receiving the random word.
int lobbyId = JSONConvert.GetLobbyID(payload); int lobbyId = JSONConvert.GetLobbyID(payload);
data.User.RandomWord = JSONConvert.GetRandomWord(payload);
if(data.Lobby?.ID == lobbyId) data.User.TurnToDraw = true; // Dit is test code, dit kan weg zodra alles lopende is.
ViewModels.ViewModelGame.HandleRandomWord(JSONConvert.GetRandomWord(payload)); if (data.Lobby?.ID == lobbyId && data.User.TurnToDraw)
RandomWord?.Invoke(data.User.RandomWord);
break; break;
default: default:
Debug.WriteLine("[CLIENT] Received weird identifier: " + id); Debug.WriteLine("[CLIENT] Received weird identifier: " + id);
break; break;
} case JSONConvert.GAME:
SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE_RECEIVED,null)); switch (JSONConvert.GetGameCommand(payload))
{
case JSONConvert.GameCommand.TIMER_ELAPSED:
int lobbyElapsedID = JSONConvert.GetLobbyID(payload);
//todo set next round
break;
case JSONConvert.GameCommand.INITIALIZE:
int lobbyID = JSONConvert.GetLobbyID(payload);
string userName = JSONConvert.GetUsernameLogin(payload);
if (lobbyID == clientData.Lobby.ID)
{
if (userName == clientData.User.Username)
{
clientData.User.TurnToDraw = true;
Debug.WriteLine("[CLIENT] Setting a player's turnToDraw to true");
}
clientData.Client.UpdateUserScores?.Invoke(clientData.Lobby);
}
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));
stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null); stream.BeginWrite(message, 0, message.Length, new AsyncCallback(OnWriteComplete), null);
} }
private void OnWriteComplete(IAsyncResult ar) private void OnWriteComplete(IAsyncResult ar)

View File

@@ -61,6 +61,7 @@ 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)
@@ -68,6 +69,7 @@ namespace Client
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;
} }
@@ -112,16 +114,26 @@ 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
{ {
_lobbies.Clear(); _lobbies.Clear();
Lobby clientLobby = ClientData.Instance.Lobby;
foreach (Lobby l in lobbiesArr) foreach (Lobby l in lobbiesArr)
{ {
_lobbies.Add(l); _lobbies.Add(l);
if (l.ID == clientLobby?.ID)
{
clientLobby.Users.Clear();
foreach (User user in l.Users)
{
clientLobby.Users.Add(user);
}
}
} }
}); });

View File

@@ -1,5 +1,4 @@
using Client.Views;
using Client.Views;
using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Command;
using SharedClientServer; using SharedClientServer;
using System; using System;
@@ -9,7 +8,6 @@ using System.ComponentModel;
using System.Diagnostics; using System.Diagnostics;
using System.Timers; using System.Timers;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
using System.Windows.Media; using System.Windows.Media;
using System.Windows.Shapes; using System.Windows.Shapes;
@@ -29,16 +27,13 @@ namespace Client.ViewModels
public Queue<double[][]> linesQueue; public Queue<double[][]> linesQueue;
private Timer queueTimer; private Timer queueTimer;
private bool wordGuessed = false;
public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public static ObservableCollection<string> Messages { get; } = new ObservableCollection<string>();
public ObservableCollection<string> Players { get; } = new ObservableCollection<string>();
private dynamic _payload; private dynamic _payload;
public static string Word
{
get;
set;
}
public string _username; public string _username;
public string _message; public string _message;
@@ -54,26 +49,43 @@ namespace Client.ViewModels
} }
} }
private string _randomWord;
public string RandomWord
{
get {
if (data.User.TurnToDraw)
return _randomWord;
if (!wordGuessed)
{
string hiddenWord = "";
for (int i = 0; i < _randomWord.Length; i++)
{
hiddenWord += "_ ";
}
return hiddenWord;
}
else
return _randomWord;
}
set { _randomWord = value; }
}
public bool IsHost public bool IsHost
{ {
get { return data.User.Host; } get { return data.User.Host; }
} }
public bool UserTurnToDraw
{
get { return data.User.TurnToDraw; }
}
public ViewModelGame(GameWindow window) public ViewModelGame(GameWindow window)
{ {
this.window = window; this.window = window;
if (_payload == null) _randomWord = "";
{
_message = "";
}
else
{
//_message = data.Message;
//_username = data.User.Username;
//Messages.Add($"{data.User.Username}: {Message}");
}
buffer = new double[maxLines][]; buffer = new double[maxLines][];
linesQueue = new Queue<double[][]>(); linesQueue = new Queue<double[][]>();
OnKeyDown = new RelayCommand(ChatBox_KeyDown); OnKeyDown = new RelayCommand(ChatBox_KeyDown);
@@ -81,6 +93,10 @@ namespace Client.ViewModels
ButtonResetCanvas = new RelayCommand(CanvasResetLocal); ButtonResetCanvas = new RelayCommand(CanvasResetLocal);
data.Client.CanvasDataReceived = UpdateCanvasWithNewData; data.Client.CanvasDataReceived = UpdateCanvasWithNewData;
data.Client.CReset = CanvasResetData; data.Client.CReset = CanvasResetData;
data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer;
data.Client.UpdateUserScores = UpdateUserScores;
} }
public ICommand OnKeyDown { get; set; } public ICommand OnKeyDown { get; set; }
@@ -149,12 +165,18 @@ namespace Client.ViewModels
} }
} }
public void Canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
sendArrayFromQueue(sender, null);
}
private void sendArrayFromQueue(object sender, ElapsedEventArgs e) private void sendArrayFromQueue(object sender, ElapsedEventArgs e)
{ {
if (linesQueue.Count != 0) if (linesQueue.Count != 0)
{ {
Debug.WriteLine("[GAME] sending canvas data...");
double[][] temp = linesQueue.Dequeue(); double[][] temp = linesQueue.Dequeue();
data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color)); data.Client.SendMessage(JSONConvert.ConstructDrawingCanvasData(temp,color));
} }
@@ -213,32 +235,62 @@ namespace Client.ViewModels
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
} }
/* public void HandleIncomingMsg(string username, string message)
* MISC make this a callback
* Handles the incoming chat message from another client.
*/
public static void HandleIncomingMsg(string username, string message)
{ {
Application.Current.Dispatcher.Invoke(delegate Application.Current.Dispatcher.Invoke(delegate
{ {
Messages.Add($"{username}: {message}"); Messages.Add($"{username}: {message}");
}); });
} }
public void LeaveGame(object sender, CancelEventArgs e) public void LeaveGame(object sender, System.ComponentModel.CancelEventArgs e)
{ {
Debug.WriteLine("Leaving..."); Debug.WriteLine("Leaving...");
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID)); data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
} }
/* public void HandleRandomWord(string randomWord)
* MISC make this a callback
* Handles the random word that has been received from the server.
*/
public static void HandleRandomWord(string randomWord)
{ {
Debug.WriteLine("[CLIENT] Reached the handle random word method!"); Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Word = "NegerPik"; 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 + "\n" + item.TurnToDraw);
}
});
}
private void UpdateUserScores(Lobby newLobby) {
Debug.WriteLine("[GAME] updating user scores");
List<User> newUsers = newLobby.Users;
// go over all users in current lobby
foreach (User user in data.Lobby?.Users)
{
// check with all users in new lobby
foreach (User newUser in newUsers)
{
// and update the score
if (newUser.Username == user.Username)
{
Debug.WriteLine($"[GAME] setting score of {user.Username} to {newUser.Score}. it was {user.Score}");
user.Score = newUser.Score;
break;
}
}
}
// update all the scores in the player list
HandleIncomingPlayer(newLobby);
}
} }
} }

View File

@@ -22,16 +22,9 @@
<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>
<Grid Grid.Row="0" Grid.Column="1"> <Grid Grid.Row="0" Grid.Column="1">
@@ -42,21 +35,19 @@
<ColumnDefinition Width="100"/> <ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" FontSize="20" Content="Pick a color -->"/> <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"/> <xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100" />
<Label Grid.Row="0" Grid.Column="2" FontSize="20" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<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"/> <Button Name="CanvasReset" Click="CanvasReset_Click" Grid.Row="0" Grid.Column="3" Content="RESET"/>
</Grid> </Grid>
<Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/> <Button Name="StartGame" Grid.Row="0" Grid.Column="2" Content="Start Game" FontSize="20" Command="{Binding ButtonStartGame}" IsEnabled="{Binding IsHost}"/>
<Label Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=Word, UpdateSourceTrigger=PropertyChanged}" Margin="140,0,109,0"/>
<xctk:ColorPicker Name="ClrPcker_Background" SelectedColorChanged="ClrPcker_Background_SelectedColorChanged_1" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center" Height="22" Width="100"/>
<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>
@@ -64,9 +55,9 @@
</Border> </Border>
<Grid Grid.Column="2" Grid.Row="1"> <Grid Grid.Column="2" Grid.Row="1">
<ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,0,69"/> <ListBox Name ="TextBox" ItemsSource="{Binding Path=Messages}" Margin="0,0,10,69" />
<TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,0,0"> <TextBox Name="ChatBox" Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,465,10,0">
<TextBox.InputBindings> <TextBox.InputBindings>
<KeyBinding Key="Return" Command="{Binding OnKeyDown}"/> <KeyBinding Key="Return" Command="{Binding OnKeyDown}"/>
</TextBox.InputBindings> </TextBox.InputBindings>

View File

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

View File

@@ -11,6 +11,7 @@
<RowDefinition Height="60"/> <RowDefinition Height="60"/>
<RowDefinition Height="50"/> <RowDefinition Height="50"/>
<RowDefinition Height="30"/> <RowDefinition Height="30"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<Grid.ColumnDefinitions> <Grid.ColumnDefinitions>
@@ -22,8 +23,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>

View File

@@ -1,4 +1,5 @@
using SharedClientServer; using Client.ViewModels;
using SharedClientServer;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@@ -19,27 +20,20 @@ namespace Client.Views
public partial class LoginScreen : Window public partial class LoginScreen : Window
{ {
ClientData data = ClientData.Instance; ClientData data = ClientData.Instance;
private LoginViewModel loginViewModel;
public LoginScreen() public LoginScreen()
{ {
loginViewModel = new LoginViewModel(this);
InitializeComponent(); InitializeComponent();
} }
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;
Client client = new Client(user.Username); if (name == string.Empty) return;
client.OnSuccessfullConnect = () => LoginButton.IsEnabled = false;
{ loginViewModel.UsernameEntered(name);
// 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();
this.Close();
});
};
} }
} }

View File

@@ -11,6 +11,7 @@ using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers;
using static SharedClientServer.JSONConvert; using static SharedClientServer.JSONConvert;
namespace Server.Models namespace Server.Models
@@ -22,7 +23,9 @@ namespace Server.Models
private NetworkStream stream; private NetworkStream stream;
private byte[] buffer = new byte[2048]; private byte[] buffer = new byte[2048];
private byte[] totalBuffer = new byte[2048]; 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; private Callback OnMessageReceivedOk;
@@ -34,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();
@@ -59,6 +63,7 @@ namespace Server.Models
throw new OutOfMemoryException("buffer is too small!"); throw new OutOfMemoryException("buffer is too small!");
} }
// copy the received bytes into the buffer // copy the received bytes into the buffer
Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived); Array.Copy(buffer, 0, totalBuffer, totalBufferReceived, bytesReceived);
// add the bytes we received to the total amount // add the bytes we received to the total amount
@@ -90,6 +95,7 @@ namespace Server.Models
} }
ar.AsyncWaitHandle.WaitOne(); ar.AsyncWaitHandle.WaitOne();
// start reading for a new message // start reading for a new message
stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null); stream.BeginRead(buffer, 0, buffer.Length, new AsyncCallback(OnRead), null);
@@ -143,6 +149,11 @@ namespace Server.Models
message = textMsg message = textMsg
}; };
if (textMsg == _randomWord && !string.IsNullOrEmpty(_randomWord))
{
Debug.WriteLine($"[SERVERCLIENT] word has been guessed! {User.Username} + Word: {_randomWord}");
}
//Sends the incomming message to be broadcast to all of the clients inside the current lobby. //Sends the incomming message to be broadcast to all of the clients inside the current lobby.
serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet)); serverCom.SendToLobby(serverCom.GetLobbyForUser(User), JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, packet));
break; break;
@@ -165,7 +176,7 @@ namespace Server.Models
coords = JSONConvert.getCoordinates(payload), coords = JSONConvert.getCoordinates(payload),
color = JSONConvert.getCanvasDrawingColor(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; break;
case JSONConvert.CANVAS_RESET: case JSONConvert.CANVAS_RESET:
@@ -184,13 +195,36 @@ namespace Server.Models
case JSONConvert.GAME: case JSONConvert.GAME:
Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic"); Debug.WriteLine("[SERVERCLIENT] Got a message about the game logic");
string command = JSONConvert.GetGameCommand(payload); GameCommand command = JSONConvert.GetGameCommand(payload);
switch (command) switch (command)
{ {
case "startGame": case GameCommand.START_GAME:
int lobbyID = JSONConvert.GetStartGameLobbyID(payload); int lobbyID = JSONConvert.GetStartGameLobbyID(payload);
serverCom.CloseALobby(lobbyID); 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())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
serverCom.SendToLobby(lobbyID, JSONConvert.ConstructGameInitializeData( serverCom.FindUserNameInLobby(lobbyID),lobbyID));
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;
} }
@@ -209,6 +243,17 @@ namespace Server.Models
} }
} }
private void LobbyTimer_Elapsed(object sender, ElapsedEventArgs e)
{
System.Timers.Timer timer = sender as System.Timers.Timer;
int lobbyID = lobbyTimers[timer];
Debug.WriteLine("[SERVERCLIENT] timer elapsed for lobby " + lobbyID);
serverCom.SendToLobby(lobbyID, JSONConvert.ConstructGameTimerElapsedMessage(lobbyID));
timer.Stop();
}
private void handleLobbyMessage(byte[] payload, LobbyIdentifier l) private void handleLobbyMessage(byte[] payload, LobbyIdentifier l)
{ {
switch (l) switch (l)
@@ -232,10 +277,11 @@ namespace Server.Models
ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray())); ServerCommunication.INSTANCE.sendToAll(JSONConvert.ConstructLobbyListMessage(ServerCommunication.INSTANCE.lobbies.ToArray()));
OnMessageReceivedOk = () => OnMessageReceivedOk = () =>
{ {
_randomWord = JSONConvert.SendRandomWord("WordsForGame.json");
serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new serverCom.sendToAll(JSONConvert.GetMessageToSend(JSONConvert.RANDOMWORD, new
{ {
id = serverCom.GetLobbyForUser(User).ID, id = serverCom.GetLobbyForUser(User).ID,
word = JSONConvert.SendRandomWord("WordsForGame.json") word = _randomWord
})); }));
OnMessageReceivedOk = null; OnMessageReceivedOk = null;
}; };

View File

@@ -142,7 +142,23 @@ namespace Server.Models
{ {
foreach (ServerClient sc in serverClientsInlobbies[l]) foreach (ServerClient sc in serverClientsInlobbies[l])
{ {
Debug.WriteLine("[SERVERCLIENT] Sending message"); Debug.WriteLine("[SERVERCLIENT] Sending message to lobby");
sc.sendMessage(message);
}
break;
}
}
}
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); sc.sendMessage(message);
} }
break; break;
@@ -158,6 +174,7 @@ namespace Server.Models
{ {
foreach (ServerClient sc in serverClientsInlobbies[l]) foreach (ServerClient sc in serverClientsInlobbies[l])
{ {
if (sc.User.Username != username)
sc.sendMessage(message); sc.sendMessage(message);
} }
break; break;
@@ -261,6 +278,10 @@ namespace Server.Models
break; break;
} }
} }
if (l.Users.Count != 0)
{
l.Users[0].Host = true;
}
break; break;
} }
} }
@@ -278,8 +299,24 @@ namespace Server.Models
if (lobby.ID == lobbyID) if (lobby.ID == lobbyID)
{ {
lobby.LobbyJoinable = false; lobby.LobbyJoinable = false;
break;
} }
} }
} }
public string FindUserNameInLobby(int lobbyID)
{
Lobby lobbyFound = null;
foreach (Lobby lobby in lobbies)
{
if (lobby.ID == lobbyID)
{
lobbyFound = lobby;
break;
}
}
return lobbyFound?.Users[lobbyFound.UserDrawing]?.Username;
}
} }
} }

View File

@@ -4,6 +4,7 @@ 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; using System.Windows.Media;
@@ -34,6 +35,14 @@ namespace SharedClientServer
REQUEST REQUEST
} }
public enum GameCommand
{
START_GAME,
INITIALIZE,
TIMER_ELAPSED,
NEXT_ROUND
}
public static (string,string) GetUsernameAndMessage(byte[] json) public static (string,string) GetUsernameAndMessage(byte[] json)
{ {
string msg = Encoding.UTF8.GetString(json); string msg = Encoding.UTF8.GetString(json);
@@ -204,15 +213,35 @@ namespace SharedClientServer
public static byte[] ConstructGameStartData(int lobbyID) public static byte[] ConstructGameStartData(int lobbyID)
{ {
string startGame = "startGame";
return GetMessageToSend(GAME, new return GetMessageToSend(GAME, new
{ {
command = startGame, command = GameCommand.START_GAME,
lobbyToStart = lobbyID lobbyToStart = lobbyID
}); ; }); ;
} }
public static string GetGameCommand(byte[] payload) public static byte[] ConstructGameInitializeData(string userName, int lobbyID)
{
dynamic payload = new
{
id = lobbyID,
command = GameCommand.INITIALIZE,
username = userName
};
return GetMessageToSend(GAME, payload);
}
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)); dynamic json = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(payload));
return json.command; return json.command;

View File

@@ -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;
@@ -17,6 +17,7 @@ namespace Client
private bool _lobbyJoinable; private bool _lobbyJoinable;
//private List<string> _usernames; //private List<string> _usernames;
private List<User> _users; private List<User> _users;
private int _userDrawing;
//public void AddUsername(string username, out bool success) //public void AddUsername(string username, out bool success)
//{ //{
@@ -36,6 +37,7 @@ namespace Client
//_usernames = new List<string>(); //_usernames = new List<string>();
_users = new List<User>(); _users = new List<User>();
_lobbyJoinable = true; _lobbyJoinable = true;
_userDrawing = 0;
} }
public void AddUser(string username, out bool succes) public void AddUser(string username, out bool succes)
@@ -95,5 +97,11 @@ namespace Client
set { _lobbyJoinable = value; } set { _lobbyJoinable = value; }
} }
public int UserDrawing
{
get { return _userDrawing; }
set { _userDrawing = value; }
}
} }
} }

View File

@@ -13,6 +13,7 @@ namespace SharedClientServer
private bool _host; private bool _host;
private bool _turnToDraw; private bool _turnToDraw;
private string _message; private string _message;
private string _randomWord;
[JsonConstructor] [JsonConstructor]
public User(string username, int score, bool host, bool turnToDraw) public User(string username, int score, bool host, bool turnToDraw)
@@ -90,5 +91,10 @@ namespace SharedClientServer
get { return _turnToDraw; } get { return _turnToDraw; }
set { _turnToDraw = value; } set { _turnToDraw = value; }
} }
public string RandomWord
{
get { return _randomWord; }
set { _randomWord = value; }
}
} }
} }