up
This commit is contained in:
parent
429eb1cb02
commit
5512f1a358
52 changed files with 5537 additions and 1557 deletions
|
|
@ -23,14 +23,16 @@ public class AccountsManager {
|
|||
}
|
||||
|
||||
private AccountsManager(){
|
||||
users.add(new User("a","a"));
|
||||
users.add(new User("b","b"));
|
||||
users.add(new User("c","c"));
|
||||
users.add(new User("a","a",0));
|
||||
users.add(new User("b","b",0));
|
||||
users.add(new User("c","c",0));
|
||||
users.add(new User("d","d",0));
|
||||
|
||||
}
|
||||
|
||||
public boolean register(String userName, String password) {
|
||||
if(!exists(userName)){
|
||||
return users.add(new User(userName, password));
|
||||
return users.add(new User(userName, password,0));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,14 +5,17 @@ import com.texttwist.server.models.Dictionary;
|
|||
import com.texttwist.server.models.Match;
|
||||
import com.texttwist.server.tasks.SendInvitations;
|
||||
import com.texttwist.server.tasks.WaitForPlayers;
|
||||
import constants.Config;
|
||||
import jdk.nashorn.internal.parser.JSONParser;
|
||||
import models.Message;
|
||||
import models.Session;
|
||||
import org.json.simple.JsonObject;
|
||||
import utilities.Logger;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.io.InputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
|
|
@ -21,7 +24,10 @@ import java.nio.ByteBuffer;
|
|||
import java.nio.channels.*;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
|
@ -35,13 +41,15 @@ public class GameServer implements Runnable{
|
|||
protected int serverPort;
|
||||
protected ServerSocketChannel serverSocketChannel = null;
|
||||
protected ThreadProxy proxy;
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
DatagramSocket datagramSocket;
|
||||
protected Selector selector = null;
|
||||
protected ExecutorService threadPool = Executors.newCachedThreadPool();
|
||||
private String dictionaryPath = "./Server/resources/dictionary";
|
||||
public static Dictionary dict;
|
||||
|
||||
|
||||
public static DefaultListModel<Match> activeMatches = new DefaultListModel<Match>();
|
||||
public static List<Match> activeMatches = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
public GameServer(int port){
|
||||
this.serverPort = port;
|
||||
|
|
@ -50,14 +58,14 @@ public class GameServer implements Runnable{
|
|||
public void run(){
|
||||
|
||||
dict = new Dictionary(dictionaryPath);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
try {
|
||||
selector = Selector.open();
|
||||
serverSocketChannel = ServerSocketChannel.open();
|
||||
serverSocketChannel.configureBlocking(false);
|
||||
serverSocketChannel.socket().bind(new InetSocketAddress(serverPort));
|
||||
serverSocketChannel.register(selector, OP_ACCEPT);
|
||||
Logger.write("Game Service is running at "+this.serverPort+" port...");
|
||||
datagramSocket = new DatagramSocket(Config.WordsReceiverServerPort);
|
||||
Logger.write("GamePage Service is running at "+this.serverPort+" port...");
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
|
@ -71,6 +79,7 @@ public class GameServer implements Runnable{
|
|||
|
||||
Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
|
||||
while (iter.hasNext()) {
|
||||
buffer = ByteBuffer.allocate(1024);
|
||||
SocketChannel client = null;
|
||||
SelectionKey key = iter.next();
|
||||
iter.remove();
|
||||
|
|
@ -85,19 +94,18 @@ public class GameServer implements Runnable{
|
|||
|
||||
case OP_READ:
|
||||
client = (SocketChannel) key.channel();
|
||||
buffer.clear();
|
||||
//buffer.clear();
|
||||
if (client.read(buffer) != -1) {
|
||||
buffer.flip();
|
||||
String line = new String(buffer.array(), buffer.position(), buffer.remaining());
|
||||
|
||||
if (line.startsWith("MESSAGE")) {
|
||||
SessionsManager.getInstance().printAll();
|
||||
Message msg = Message.toMessage(line);
|
||||
proxy = new ThreadProxy(msg, client);
|
||||
proxy = new ThreadProxy(msg, client, datagramSocket);
|
||||
Future<Boolean> identifyMessage = threadPool.submit(proxy);
|
||||
key.cancel();
|
||||
}
|
||||
|
||||
|
||||
if (line.startsWith("CLOSE")) {
|
||||
client.close();
|
||||
} else if (line.startsWith("QUIT")) {
|
||||
|
|
@ -114,7 +122,6 @@ public class GameServer implements Runnable{
|
|||
break;
|
||||
|
||||
default:
|
||||
System.out.println("unhandled " + key.readyOps());
|
||||
break;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
|
|
|
|||
|
|
@ -36,12 +36,16 @@ public class NotificationServer implements INotificationServer {
|
|||
}
|
||||
}
|
||||
|
||||
public synchronized void sendInvitations(String username, DefaultListModel<String> users) throws RemoteException {
|
||||
public synchronized void sendInvitations(String username, DefaultListModel<String> users){
|
||||
System.out.println("Starting callbacks");
|
||||
Iterator i = clients.iterator();
|
||||
while(i.hasNext()){
|
||||
INotificationClient client = (INotificationClient) i.next();
|
||||
client.sendInvite(username, users);
|
||||
try{
|
||||
client.sendInvite(username, users);
|
||||
} catch (RemoteException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package com.texttwist.server.components;
|
||||
import models.Session;
|
||||
import models.User;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
|
|
@ -25,7 +26,17 @@ public class SessionsManager {
|
|||
|
||||
public boolean add(String userName, String token) {
|
||||
remove(userName);
|
||||
return sessions.add(new Session(userName, token));
|
||||
return sessions.add(new Session(new User(userName,"",0), token));
|
||||
}
|
||||
|
||||
public void printAll(){
|
||||
synchronized(sessions) {
|
||||
Iterator<Session> i = sessions.iterator();
|
||||
while (i.hasNext()) {
|
||||
Session elem = i.next();
|
||||
System.out.println(elem.account.userName + " | " + elem.token);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public boolean remove(String userName){
|
||||
|
|
@ -44,7 +55,7 @@ public class SessionsManager {
|
|||
Iterator<Session> i = sessions.iterator();
|
||||
while (i.hasNext()) {
|
||||
Session elem = i.next();
|
||||
if (elem.userName.equals(userName)) {
|
||||
if (elem.account.userName.equals(userName)) {
|
||||
return elem;
|
||||
}
|
||||
}
|
||||
|
|
@ -57,7 +68,7 @@ public class SessionsManager {
|
|||
Iterator<Session> i = sessions.iterator();
|
||||
while (i.hasNext()) {
|
||||
Session elem = i.next();
|
||||
if (elem.userName.equals(userName)) {
|
||||
if (elem.account.userName.equals(userName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import models.Message;
|
|||
import javax.swing.*;
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MulticastSocket;
|
||||
import java.nio.ByteBuffer;
|
||||
|
|
@ -24,11 +25,13 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
protected ExecutorService threadPool = Executors.newCachedThreadPool();
|
||||
private Message request;
|
||||
private SocketChannel socketChannel;
|
||||
private DatagramSocket datagramSocket;
|
||||
|
||||
|
||||
ThreadProxy(Message request, SocketChannel socketChannel){
|
||||
ThreadProxy(Message request, SocketChannel socketChannel, DatagramSocket datagramSocket){
|
||||
this.request = request;
|
||||
this.socketChannel = socketChannel;
|
||||
this.datagramSocket = datagramSocket;
|
||||
}
|
||||
|
||||
|
||||
|
|
@ -55,8 +58,9 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
|
||||
//Crea nuova partita e attendi i giocatori
|
||||
request.data.addElement(request.sender);
|
||||
|
||||
Match match = new Match(request.sender, request.data);
|
||||
activeMatches.addElement(match);
|
||||
activeMatches.add(match);
|
||||
|
||||
DefaultListModel<String> matchName = new DefaultListModel<>();
|
||||
matchName.addElement(request.sender);
|
||||
|
|
@ -78,6 +82,7 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
|
||||
Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get();
|
||||
if(!sendMessageJoinTimeoutRes){
|
||||
activeMatches.remove(Match.findMatchIndex(activeMatches,match.matchCreator));
|
||||
return sendMessageJoinTimeoutRes;
|
||||
}
|
||||
}
|
||||
|
|
@ -98,8 +103,7 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
buffer.clear();
|
||||
buffer = ByteBuffer.wrap(byteMessage);
|
||||
this.socketChannel.write(buffer);
|
||||
//socketChannel.close();
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
|
|
@ -112,7 +116,6 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
case "FETCH_HIGHSCORES":
|
||||
Future<DefaultListModel<String>> computeHighscores = threadPool.submit(new ComputeHighscores());
|
||||
try {
|
||||
System.out.println("FETCHHH");
|
||||
DefaultListModel<String> computeHighscoresRes = computeHighscores.get();
|
||||
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
|
||||
byteMessage = message.toString().getBytes();
|
||||
|
|
@ -123,13 +126,12 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
break;
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return true;
|
||||
|
||||
|
||||
case "JOIN_GAME":
|
||||
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel));
|
||||
|
|
@ -138,11 +140,10 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
if(joinMatchRes){
|
||||
System.out.print("START THE GAME!!!!");
|
||||
|
||||
Match match = Match.findMatch(activeMatches, request.data.get(0));
|
||||
|
||||
Match match = Match.findMatch(request.data.get(0));
|
||||
|
||||
Future<DefaultListModel<String>> generateWords = threadPool.submit(new GenerateLetters());
|
||||
match.setLetters(generateWords.get());
|
||||
Future<DefaultListModel<String>> generateLetters = threadPool.submit(new GenerateLetters());
|
||||
match.setLetters(generateLetters.get());
|
||||
match.letters.addElement(String.valueOf(match.multicastId));
|
||||
|
||||
for (int i =0; i< match.playersSocket.size(); i++) {
|
||||
|
|
@ -166,7 +167,7 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
}
|
||||
|
||||
//Start receive words: tempo masimo 5 minuti per completare l'invio delle lettere.
|
||||
Future<Boolean> receiveWords = threadPool.submit(new ReceiveWords(match));
|
||||
Future<Boolean> receiveWords = threadPool.submit(new ReceiveWords(match, datagramSocket));
|
||||
Boolean receiveWordsRes = receiveWords.get();
|
||||
if(!receiveWordsRes){
|
||||
match.setUndefinedScorePlayersToZero();
|
||||
|
|
@ -174,19 +175,18 @@ public class ThreadProxy implements Callable<Boolean> {
|
|||
} else {
|
||||
System.out.println("TUTTI I GIOCATORI HANNO CONSEGNATO IN TEMPO");
|
||||
}
|
||||
System.out.println(match.playersScore);
|
||||
|
||||
Message msg = new Message("FINALSCORE","SERVER","", match.getMatchPlayersScoreAsStringList());
|
||||
|
||||
MulticastSocket s = new MulticastSocket(4000);
|
||||
MulticastSocket multicastSocket = new MulticastSocket(match.multicastId);
|
||||
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
|
||||
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(),
|
||||
ia, 4000);
|
||||
s.send(hi);
|
||||
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
|
||||
multicastSocket.send(hi);
|
||||
activeMatches.remove(Match.findMatchIndex(activeMatches,match.matchCreator));
|
||||
|
||||
|
||||
//RISPONDI CON LA CLASSIFICA
|
||||
//TODO
|
||||
return receiveWordsRes;
|
||||
break;
|
||||
//ULTIMO A JOINARE! INIZIA GIOCO
|
||||
} else {
|
||||
System.out.print("WAIT FRIENDS");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,215 @@
|
|||
package com.texttwist.server.components;
|
||||
|
||||
import com.texttwist.client.App;
|
||||
import com.texttwist.server.models.Match;
|
||||
import com.texttwist.server.tasks.*;
|
||||
import constants.Config;
|
||||
import models.Message;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.MulticastSocket;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.concurrent.*;
|
||||
|
||||
import static com.texttwist.server.components.GameServer.activeMatches;
|
||||
|
||||
/**
|
||||
* Created by loke on 18/06/2017.
|
||||
*/
|
||||
public class ThreadProxy implements Callable<Boolean> {
|
||||
protected ExecutorService threadPool = Executors.newCachedThreadPool();
|
||||
private Message request;
|
||||
private SocketChannel socketChannel;
|
||||
private DatagramSocket datagramSocket;
|
||||
|
||||
|
||||
ThreadProxy(Message request, SocketChannel socketChannel, DatagramSocket datagramSocket){
|
||||
this.request = request;
|
||||
this.socketChannel = socketChannel;
|
||||
this.datagramSocket = datagramSocket;
|
||||
}
|
||||
|
||||
|
||||
private Boolean isValidToken(String token){
|
||||
return SessionsManager.getInstance().isValidToken(token);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean call() {
|
||||
ByteBuffer buffer = ByteBuffer.allocate(1024);
|
||||
byte[] byteMessage = null;
|
||||
System.out.println("Selecting right task for new thread");
|
||||
if(isValidToken(request.token)){
|
||||
switch(request.message){
|
||||
case "START_GAME":
|
||||
Future<Boolean> onlineUsers = threadPool.submit(new CheckOnlineUsers(request.data));
|
||||
try {
|
||||
Boolean usersOnline = onlineUsers.get();
|
||||
if(usersOnline){
|
||||
Future<Boolean> sendInvitations = threadPool.submit(new SendInvitations(request.sender, request.data));
|
||||
try {
|
||||
Boolean invitationSended = sendInvitations.get();
|
||||
if (invitationSended) {
|
||||
|
||||
//Crea nuova partita e attendi i giocatori
|
||||
request.data.addElement(request.sender);
|
||||
|
||||
Match match = new Match(request.sender, request.data);
|
||||
activeMatches.add(match);
|
||||
|
||||
DefaultListModel<String> matchName = new DefaultListModel<>();
|
||||
matchName.addElement(request.sender);
|
||||
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, matchName, socketChannel));
|
||||
Boolean joinMatchRes = joinMatch.get();
|
||||
|
||||
if(!joinMatchRes){
|
||||
//NON FARE NULLA, ASPETTA GLI ALTRI
|
||||
Message message = new Message("INVITES_ALL_SENDED", "", "", new DefaultListModel<String>());
|
||||
byteMessage = message.toString().getBytes();
|
||||
buffer = ByteBuffer.wrap(byteMessage);
|
||||
socketChannel.write(buffer);
|
||||
|
||||
|
||||
Future<Boolean> joinTimeout = threadPool.submit(new JoinTimeout(match));
|
||||
Boolean joinTimeoutRes = joinTimeout.get();
|
||||
if(!joinTimeoutRes){
|
||||
Future<Boolean> sendMessageJoinTimeout = threadPool.submit(
|
||||
new SendMessageToAllPlayers(match, new Message("JOIN_TIMEOUT", "", "", new DefaultListModel<>()), socketChannel));
|
||||
Boolean sendMessageJoinTimeoutRes = sendMessageJoinTimeout.get();
|
||||
if(!sendMessageJoinTimeoutRes){
|
||||
activeMatches.remove(Match.findMatchIndex(activeMatches,match.matchCreator));
|
||||
return sendMessageJoinTimeoutRes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
} else {
|
||||
|
||||
Message message = new Message("USER_NOT_ONLINE", "", "", new DefaultListModel<String>());
|
||||
byteMessage = new String(message.toString()).getBytes();
|
||||
buffer.clear();
|
||||
buffer = ByteBuffer.wrap(byteMessage);
|
||||
this.socketChannel.write(buffer);
|
||||
break;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
case "FETCH_HIGHSCORES":
|
||||
Future<DefaultListModel<String>> computeHighscores = threadPool.submit(new ComputeHighscores());
|
||||
try {
|
||||
DefaultListModel<String> computeHighscoresRes = computeHighscores.get();
|
||||
Message message = new Message("HIGHSCORES", "", "", computeHighscoresRes);
|
||||
byteMessage = message.toString().getBytes();
|
||||
|
||||
buffer = ByteBuffer.wrap(byteMessage);
|
||||
try {
|
||||
socketChannel.write(buffer);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
break;
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
case "JOIN_GAME":
|
||||
Future<Boolean> joinMatch = threadPool.submit(new JoinMatch(request.sender, request.data, socketChannel));
|
||||
try {
|
||||
Boolean joinMatchRes = joinMatch.get();
|
||||
if(joinMatchRes){
|
||||
System.out.print("START THE GAME!!!!");
|
||||
|
||||
Match match = Match.findMatch(activeMatches, request.data.get(0));
|
||||
|
||||
Future<DefaultListModel<String>> generateWords = threadPool.submit(new GenerateLetters());
|
||||
match.setLetters(generateWords.get());
|
||||
match.letters.addElement(String.valueOf(match.multicastId));
|
||||
|
||||
for (int i =0; i< match.playersSocket.size(); i++) {
|
||||
System.out.println("INVIO");
|
||||
socketChannel = match.playersSocket.get(i).getValue();
|
||||
if(socketChannel != null) {
|
||||
buffer.clear();
|
||||
Message message = new Message("GAME_STARTED", "", "", match.letters);
|
||||
match.startGame();
|
||||
byteMessage = message.toString().getBytes();
|
||||
|
||||
buffer = ByteBuffer.wrap(byteMessage);
|
||||
try {
|
||||
socketChannel.write(buffer);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
//clientSocket.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Start receive words: tempo masimo 5 minuti per completare l'invio delle lettere.
|
||||
Future<Boolean> receiveWords = threadPool.submit(new ReceiveWords(match, datagramSocket));
|
||||
Boolean receiveWordsRes = receiveWords.get();
|
||||
if(!receiveWordsRes){
|
||||
match.setUndefinedScorePlayersToZero();
|
||||
System.out.println("ZERO PUNTI a chi non ha ancora inviato le lettere, TIMER SCADUTO");
|
||||
} else {
|
||||
System.out.println("TUTTI I GIOCATORI HANNO CONSEGNATO IN TEMPO");
|
||||
}
|
||||
|
||||
Message msg = new Message("FINALSCORE","SERVER","", match.getMatchPlayersScoreAsStringList());
|
||||
|
||||
MulticastSocket multicastSocket = new MulticastSocket(match.multicastId);
|
||||
InetAddress ia = InetAddress.getByName(Config.ScoreMulticastServerURI);
|
||||
DatagramPacket hi = new DatagramPacket(msg.toString().getBytes(), msg.toString().length(), ia, match.multicastId);
|
||||
multicastSocket.send(hi);
|
||||
activeMatches.remove(Match.findMatchIndex(activeMatches,match.matchCreator));
|
||||
|
||||
|
||||
//RISPONDI CON LA CLASSIFICA
|
||||
break;
|
||||
//ULTIMO A JOINARE! INIZIA GIOCO
|
||||
} else {
|
||||
System.out.print("WAIT FRIENDS");
|
||||
//NON FARE NULLA, ASPETA GLI ALTRI
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
} catch (ExecutionException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
default:
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
} else {
|
||||
System.out.print("TOKEN NON VALIDO");
|
||||
return false;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -56,6 +56,9 @@ public class Dictionary {
|
|||
}
|
||||
|
||||
public static Boolean isContainedInDictionary(String word){
|
||||
if(word.equals("")){
|
||||
return true;
|
||||
}
|
||||
for(int i = 0; i< wordList.size(); i++){
|
||||
if(wordList.get(i).equals(word)) {
|
||||
return true;
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
package com.texttwist.server.models;
|
||||
|
||||
import constants.Config;
|
||||
import javafx.util.Pair;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.Socket;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.*;
|
||||
|
|
@ -13,34 +15,53 @@ import static com.texttwist.server.components.GameServer.activeMatches;
|
|||
* Created by loke on 23/06/2017.
|
||||
*/
|
||||
public class Match {
|
||||
public DefaultListModel<Pair<String,Integer>> playersStatus = new DefaultListModel<Pair<String, Integer>>();
|
||||
public DefaultListModel<Pair<String,SocketChannel>> playersSocket = new DefaultListModel<Pair<String, SocketChannel>>();
|
||||
public List<Pair<String,Integer>> playersStatus = Collections.synchronizedList(new ArrayList<>()); //Usare Liste!!!!!!!
|
||||
public List<Pair<String,SocketChannel>> playersSocket = Collections.synchronizedList(new ArrayList<>());
|
||||
private boolean started = false;
|
||||
public String matchCreator;
|
||||
public Integer multicastId;
|
||||
public DefaultListModel<String> letters;
|
||||
public DefaultListModel<Pair<String,Integer>> playersScore = new DefaultListModel<Pair<String, Integer>>();
|
||||
public List<Pair<String,Integer>> playersScore = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
public Match(String matchCreator, DefaultListModel<String> players){
|
||||
for (int i =0; i < players.size(); i++){
|
||||
this.playersStatus.addElement(new Pair<>(players.get(i), 0));
|
||||
this.playersScore.addElement(new Pair<>(players.get(i), -1));
|
||||
this.playersSocket.addElement(new Pair<>(players.get(i), null));
|
||||
this.playersStatus.add(new Pair<>(players.get(i), 0));
|
||||
this.playersScore.add(new Pair<>(players.get(i), -1));
|
||||
this.playersSocket.add(new Pair<>(players.get(i), null));
|
||||
}
|
||||
this.multicastId = this.generateMulticastId();
|
||||
this.matchCreator = matchCreator;
|
||||
}
|
||||
|
||||
public static Match findMatch(String matchName){
|
||||
for(int i = 0; i<activeMatches.size(); i++) {
|
||||
if (activeMatches.get(i).matchCreator.equals(matchName)) {
|
||||
return activeMatches.get(i);
|
||||
public static Match findMatch(List<Match> matches, String matchName){
|
||||
synchronized (matches) {
|
||||
for (int i = 0; i < matches.size(); i++) {
|
||||
if (matches.get(i).matchCreator.equals(matchName)) {
|
||||
return matches.get(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public void printAll(){
|
||||
for (int i = 0; i < playersScore.size(); i++) {
|
||||
System.out.println(playersScore.get(i).getKey() + " : " +playersScore.get(i).getValue());
|
||||
|
||||
}
|
||||
}
|
||||
public static int findMatchIndex(List<Match> matches, String matchName){
|
||||
synchronized (matches) {
|
||||
for (int i = 0; i < matches.size(); i++) {
|
||||
if (matches.get(i).matchCreator.equals(matchName)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isStarted(){
|
||||
return started;
|
||||
}
|
||||
|
|
@ -50,44 +71,57 @@ public class Match {
|
|||
}
|
||||
|
||||
public void setScore(String player, Integer score){
|
||||
for(int i = 0; i<playersScore.size(); i++) {
|
||||
if (playersScore.get(i).getKey().equals(player)) {
|
||||
playersScore.set(i, new Pair<String, Integer>(player, score));
|
||||
System.out.println(player + " prova a settare il suo score a " + score);
|
||||
synchronized (playersScore) {
|
||||
for (int i = 0; i < playersScore.size(); i++) {
|
||||
if (playersScore.get(i).getKey().equals(player)) {
|
||||
playersScore.set(i, new Pair<String, Integer>(player, score));
|
||||
System.out.println("SEtting score of " + playersScore.get(i).getKey() + " to " + score);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean allPlayersSendedHisScore(){
|
||||
for(int i = 0; i<playersScore.size(); i++) {
|
||||
if (playersScore.get(i).getValue() == -1) {
|
||||
return false;
|
||||
printAll();
|
||||
synchronized (playersScore) {
|
||||
for (int i = 0; i < playersScore.size(); i++) {
|
||||
if (playersScore.get(i).getValue() == -1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public void setUndefinedScorePlayersToZero(){
|
||||
for(int i = 0; i<playersScore.size(); i++) {
|
||||
if (playersScore.get(i).getValue() == -1) {
|
||||
playersScore.set(i, new Pair<String, Integer>(playersScore.get(i).getKey(), 0));
|
||||
synchronized (playersScore) {
|
||||
for (int i = 0; i < playersScore.size(); i++) {
|
||||
if (playersScore.get(i).getValue() == -1) {
|
||||
playersScore.set(i, new Pair<String, Integer>(playersScore.get(i).getKey(), 0));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public DefaultListModel<String> getMatchPlayersScoreAsStringList(){
|
||||
DefaultListModel<String> l = new DefaultListModel<>();
|
||||
for(int i = 0; i<playersScore.size(); i++) {
|
||||
l.addElement(playersScore.get(i).getKey()+":"+playersScore.get(i).getValue());
|
||||
synchronized (playersScore) {
|
||||
DefaultListModel<String> l = new DefaultListModel<>();
|
||||
for (int i = 0; i < playersScore.size(); i++) {
|
||||
l.addElement(playersScore.get(i).getKey() + ":" + playersScore.get(i).getValue());
|
||||
}
|
||||
return l;
|
||||
}
|
||||
return l;
|
||||
}
|
||||
|
||||
|
||||
private int generateMulticastId(){
|
||||
if(activeMatches.size() != 0) {
|
||||
return activeMatches.lastElement().multicastId+1;
|
||||
} else {
|
||||
return 4000;
|
||||
synchronized (playersScore) {
|
||||
if (activeMatches.size() != 0) {
|
||||
return activeMatches.get(activeMatches.size()).multicastId + 1;
|
||||
} else {
|
||||
return 4000;
|
||||
}
|
||||
}
|
||||
}
|
||||
public void setLetters(DefaultListModel<String> letters){
|
||||
|
|
|
|||
|
|
@ -25,7 +25,11 @@ public class ComputeScore implements Callable<Integer> {
|
|||
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
System.out.println("INIT SET SCORE");
|
||||
System.out.println(words.size());
|
||||
System.out.println(words);
|
||||
System.out.println("SET SCORE");
|
||||
|
||||
Integer score = 0;
|
||||
for(int i = 0; i< words.size(); i++){
|
||||
if(isValid(words.get(i), match.letters)){
|
||||
|
|
@ -39,7 +43,7 @@ public class ComputeScore implements Callable<Integer> {
|
|||
}
|
||||
|
||||
private Boolean isValid(String word, DefaultListModel<String> letters) {
|
||||
for ( int i =0 ; i< word.length(); i++){
|
||||
for (int i =0 ; i< word.length(); i++){
|
||||
String c = Character.toString(word.charAt(i));
|
||||
Boolean isCharacterPresent = false;
|
||||
for(int j =0 ; j< letters.size(); j++){
|
||||
|
|
@ -47,6 +51,10 @@ public class ComputeScore implements Callable<Integer> {
|
|||
isCharacterPresent = true;
|
||||
}
|
||||
}
|
||||
if(word.equals("")){
|
||||
return true;
|
||||
}
|
||||
|
||||
if(!isCharacterPresent){
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,15 +28,15 @@ public class JoinMatch implements Callable<Boolean> {
|
|||
|
||||
@Override
|
||||
public Boolean call() throws Exception {
|
||||
Match thisMatch= findMatch(this.matchName);
|
||||
Match thisMatch = Match.findMatch(activeMatches, this.matchName);
|
||||
if(thisMatch!=null){
|
||||
for(int j = 0; j<thisMatch.playersStatus.size(); j++){
|
||||
String name = thisMatch.playersStatus.get(j).getKey();
|
||||
if (name.equals(playerName)){
|
||||
thisMatch.playersStatus.remove(j);
|
||||
thisMatch.playersStatus.addElement(new Pair<>(name,1));
|
||||
thisMatch.playersStatus.add(new Pair<>(name,1));
|
||||
thisMatch.playersSocket.remove(j);
|
||||
thisMatch.playersSocket.addElement(new Pair<>(name,socketChannel));
|
||||
thisMatch.playersSocket.add(new Pair<>(name,socketChannel));
|
||||
System.out.println(playerName + ": JOINED");
|
||||
return allJoined(thisMatch);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@ public class MatchTimeout implements Callable<Boolean> {
|
|||
|
||||
public MatchTimeout(Boolean receiveWords) {
|
||||
this.receiveWords = receiveWords;
|
||||
System.out.println("Match started, countdown for end words!");
|
||||
System.out.println("GamePage started, countdown for end words!");
|
||||
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
package com.texttwist.server.tasks;
|
||||
|
||||
import com.texttwist.server.Server;
|
||||
import com.texttwist.server.components.GameServer;
|
||||
import com.texttwist.server.models.Match;
|
||||
import constants.Config;
|
||||
import models.Message;
|
||||
|
||||
import javax.swing.*;
|
||||
import javax.xml.crypto.Data;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
|
|
@ -22,24 +24,27 @@ public class ReceiveWords implements Callable<Boolean>{
|
|||
protected ExecutorService threadPool = Executors.newCachedThreadPool();
|
||||
|
||||
public Boolean receiveWords = true;
|
||||
public DatagramSocket datagramSocket;
|
||||
public Match match;
|
||||
public ReceiveWords(Match match) {
|
||||
public ReceiveWords(Match match, DatagramSocket datagramSocket) {
|
||||
this.match = match;
|
||||
this.datagramSocket = datagramSocket;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Boolean call() throws Exception {
|
||||
System.out.print("READY TO Receive words !!!!");
|
||||
|
||||
DatagramSocket serverSocket = new DatagramSocket(Config.WordsReceiverServerPort);
|
||||
|
||||
byte[] receiveData = new byte[1024];
|
||||
|
||||
Future<Boolean> matchTimeout = threadPool.submit(new MatchTimeout(receiveWords));
|
||||
|
||||
while(receiveWords)
|
||||
{
|
||||
receiveData = new byte[1024];
|
||||
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
|
||||
serverSocket.receive(receivePacket);
|
||||
datagramSocket.receive(receivePacket);
|
||||
String rcv = new String( receivePacket.getData());
|
||||
System.out.println("RECEIVED: " + rcv);
|
||||
Message msg = Message.toMessage(rcv);
|
||||
|
|
@ -47,9 +52,12 @@ public class ReceiveWords implements Callable<Boolean>{
|
|||
|
||||
//Se tutti hanno inviato le parole, blocca il timer e restituisci true
|
||||
computeScore.get();
|
||||
System.out.println("All player sended?");
|
||||
System.out.println(match.allPlayersSendedHisScore());
|
||||
if(match.allPlayersSendedHisScore()){
|
||||
//matchTimeout.cancel(true);
|
||||
System.out.println("TIMEOUT BLOCCATO, OK");
|
||||
matchTimeout.cancel(true);
|
||||
// datagramSocket.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package com.texttwist.server.tasks;
|
|||
|
||||
import com.texttwist.server.Server;
|
||||
import com.texttwist.server.components.NotificationServer;
|
||||
import com.texttwist.server.components.SessionsManager;
|
||||
import constants.Config;
|
||||
import interfaces.INotificationServer;
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue