12 Commits

Author SHA1 Message Date
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
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
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
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
8 changed files with 92 additions and 48 deletions

View File

@@ -21,6 +21,7 @@ namespace Client
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
{ {
@@ -48,6 +49,7 @@ namespace Client
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)
@@ -70,7 +72,8 @@ namespace Client
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);
@@ -92,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;
@@ -112,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();
@@ -143,6 +146,11 @@ namespace Client
IncomingMsg?.Invoke(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
Debug.WriteLine("[CLIENT] INCOMING MESSAGE!"); Debug.WriteLine("[CLIENT] INCOMING MESSAGE!");
Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg); Debug.WriteLine("[CLIENT] User name: {0}\t User message: {1}", textUsername, textMsg);
@@ -190,22 +198,19 @@ 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);
string randomWord = JSONConvert.GetRandomWord(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) if (data.Lobby?.ID == lobbyId && data.User.TurnToDraw)
RandomWord?.Invoke(randomWord); 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;
@@ -214,13 +219,22 @@ namespace Client
} }
/*
* Updates the current lobby with the joining players,
* their player score is also tracked and should always be zero.
*/
private void updateGameLobby() private void updateGameLobby()
{ {
Debug.WriteLine("[CLIENT] updating game lobby");
foreach (var item in Lobbies) foreach (var item in Lobbies)
{ {
Debug.WriteLine("[CLIENT] lobby data: {0}", item.Users.Count); Debug.WriteLine("[CLIENT] lobby data: {0}", item.Users.Count);
if (item.ID == data.Lobby?.ID) if (item.ID == data.Lobby?.ID)
IncomingPlayer?.Invoke(item); {
//IncomingPlayer?.Invoke(item);
UpdateUserScores?.Invoke(item as Lobby);
}
} }
} }

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,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
{ {
@@ -122,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;
}
} }
}); });

View File

@@ -48,19 +48,12 @@ namespace Client.ViewModels
} }
private string _randomWord; private string _randomWord;
public string RandomWord public string RandomWord
{ {
get { return _randomWord; } get { return _randomWord; }
set { _randomWord = value; } set { _randomWord = value; }
} }
public static string Word
{
get;
set;
}
public bool IsHost public bool IsHost
{ {
get { return data.User.Host; } get { return data.User.Host; }
@@ -69,17 +62,6 @@ namespace Client.ViewModels
public ViewModelGame(GameWindow window) public ViewModelGame(GameWindow window)
{ {
this.window = window; this.window = window;
if (_payload == null)
{
_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[][]>();
@@ -91,6 +73,7 @@ namespace Client.ViewModels
data.Client.RandomWord = HandleRandomWord; data.Client.RandomWord = HandleRandomWord;
data.Client.IncomingMsg = HandleIncomingMsg; data.Client.IncomingMsg = HandleIncomingMsg;
data.Client.IncomingPlayer = HandleIncomingPlayer; data.Client.IncomingPlayer = HandleIncomingPlayer;
data.Client.UpdateUserScores = UpdateUserScores;
} }
public ICommand OnKeyDown { get; set; } public ICommand OnKeyDown { get; set; }
@@ -227,7 +210,7 @@ namespace Client.ViewModels
data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload)); data.Client.SendMessage(JSONConvert.GetMessageToSend(JSONConvert.MESSAGE, _payload));
} }
public static void HandleIncomingMsg(string username, string message) public void HandleIncomingMsg(string username, string message)
{ {
Application.Current.Dispatcher.Invoke(delegate Application.Current.Dispatcher.Invoke(delegate
{ {
@@ -240,12 +223,12 @@ namespace Client.ViewModels
data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID)); data.Client.SendMessage(JSONConvert.ConstructLobbyLeaveMessage(data.Lobby.ID));
} }
public static void HandleRandomWord(string randomWord) public void HandleRandomWord(string randomWord)
{ {
Debug.WriteLine("[CLIENT] Reached the handle random word method!"); Debug.WriteLine("[CLIENT] Reached the handle random word method!");
Application.Current.Dispatcher.Invoke(delegate Application.Current.Dispatcher.Invoke(delegate
{ {
Word = randomWord; RandomWord = randomWord;
}); });
} }
public void HandleIncomingPlayer(Lobby lobby) public void HandleIncomingPlayer(Lobby lobby)
@@ -255,9 +238,34 @@ namespace Client.ViewModels
Players.Clear(); Players.Clear();
foreach (var item in lobby.Users) foreach (var item in lobby.Users)
{ {
Players.Add(item.Username); Players.Add(item.Username + "\n" + item.Score);
} }
}); });
} }
private void UpdateUserScores(Lobby newLobby) {
Debug.WriteLine("[GAME] updating user scores");
List<User> newUsers = newLobby.Users;
// go over all users in current lobby
foreach (User user in data.Lobby?.Users)
{
// check with all users in new lobby
foreach (User newUser in newUsers)
{
// and update the score
if (newUser.Username == user.Username)
{
Debug.WriteLine($"[GAME] setting score of {user.Username} to {newUser.Score}. it was {user.Score}");
user.Score = newUser.Score;
break;
}
}
}
// update all the scores in the player list
HandleIncomingPlayer(newLobby);
}
} }
} }

View File

@@ -38,9 +38,7 @@
<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 Name="GuessWord" Grid.Row="0" Grid.Column="1" Content="{Binding Path=RandomWord, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" 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"/>
<Label Grid.Row="0" Grid.Column="2" FontSize="20" Content="" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<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>

View File

@@ -24,7 +24,7 @@
<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="69" 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"/> <Label Grid.Row="3" Grid.Column="0" Content="Tip of the century: base64 != UTF8!" FontSize="20" FontWeight="Bold"/>
</Grid> </Grid>

View File

@@ -27,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
@@ -42,6 +46,7 @@ namespace Client.Views
}); });
}; };
} }
} }
} }

View File

@@ -22,6 +22,7 @@ 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;
public User User { get; set; } public User User { get; set; }
private ServerCommunication serverCom = ServerCommunication.INSTANCE; private ServerCommunication serverCom = ServerCommunication.INSTANCE;
@@ -145,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;
@@ -234,11 +240,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

@@ -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; }
}
} }
} }