Commit b08281b8 authored by Linda Sekawati's avatar Linda Sekawati
Browse files
parents 3321ec86 5a257e08
......@@ -10,12 +10,13 @@ hostTracker = "167.205.32.46"
portTracker = 8000
hostLaptop = ""
# config MongoDB
database = ''
playerCollection = ''
inventoriCollection = ''
offerCollection = ''
marketCollection = ''
# list server yang aktif
listActiveServer = []
def createDatabase():
......@@ -40,31 +41,32 @@ def getIPAdress():
def getItemName(index):
nama = ""
if (index == 1):
if (index == 0):
nama = "honey"
elif (index == 2):
elif (index == 1):
nama = "herbs"
elif (index == 3):
elif (index == 2):
nama = "clay"
elif (index == 4):
elif (index == 3):
nama = "mineral"
elif (index == 5):
elif (index == 4):
nama = "potion"
elif (index == 6):
elif (index == 5):
nama = "incense"
elif (index == 7):
elif (index == 6):
nama = "gems"
elif (index == 8):
elif (index == 7):
nama = "elixir"
elif (index == 9):
elif (index == 8):
nama = "crystal"
elif (index == 10):
elif (index == 9):
nama = "stone"
return nama
def join(portLaptop):
print("join")
listActiveServer = []
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostTracker,portTracker))
......@@ -74,20 +76,27 @@ def join(portLaptop):
s.send(str.encode(message))
tm = s.recv(4096)
print(tm.decode('utf-8'))
tmString = tm.decode('utf-8')
tmJSON = json.JSONDecoder().decode(tmString)
# update list server aktif
listServer = tmJSON["value"]
global listActiveServer
for ip in listServer:
listActiveServer.append(ip["ip"])
s.close()
# jalankan thread server utama
playserver(portLaptop)
def playserver(portLaptop):
#global database
#global playerCollection
#global inventoriCollection
#global offerCollection
#global marketCollection
#def accept(portLaptop, offer_token):
#print("accept_broadcast")
#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# BROADCAST KE SEMUA SERVER UNTUK KONFIRMASI SERVER LAIN OFFER YANG SUDAH DITERIMA
#s.connect((,portTracker))
def playserver(portLaptop):
# config database mongodb
client = MongoClient('localhost',27107)
database = client['quest']
playerCollection = database['player']
......@@ -95,8 +104,8 @@ def playserver(portLaptop):
offerCollection = database['offer']
marketCollection = database['market']
# Mulai open socket server
print("playserver")
print(hostLaptop)
s = socket.socket()
s.bind((hostLaptop,portLaptop))
s.listen(5) # tunggu koneksi dari socket client
......@@ -128,7 +137,7 @@ def playserver(portLaptop):
# insert player baru di playerCollection, insert inventori kosong
kriteria1Object = {"token" : tokenuser, "username" : username, "password" : password, "posisiX" : 0, "posisiY" : 0, "player_time" : 0}
kriteria2Object = {"token" : tokenuser, "honey" : 0, "herbs" : 0, "clay" : 0, "mineral" : 0, "potion" : 0, "incense" : 0, "gems" : 0, "elixir" : 0, "crystal" : 0, "stone" : 0}
kriteria2Object = {"token" : tokenuser, "honey" : 3, "herbs" : 3, "clay" : 3, "mineral" : 0, "potion" : 0, "incense" : 0, "gems" : 0, "elixir" : 0, "crystal" : 0, "stone" : 0}
database.playerCollection.insert(kriteria1Object)
database.inventoriCollection.insert(kriteria2Object)
......@@ -141,11 +150,13 @@ def playserver(portLaptop):
# tulis response
response = "{'status' : 'ok'}"
elif (method == 'serverStatus'):
status = "error"
global listActiveServer
del listActiveServer[:] # hapus list
#update ulang list server aktif
for server in dataJSON['server']:
if ((server['ip'] == hostLaptop) and (server['port'] == portLaptop)):
status = "ok"
response = "{'status':'" + status + "'}"
listActiveServer.append(server["ip"])
response = "{'status':'ok'}"
print(listActiveServer)
elif (method == 'login'):
username = dataJSON['username']
password = dataJSON['password']
......@@ -170,46 +181,59 @@ def playserver(portLaptop):
kriteria1Object = {"token":token}
row = database.inventoriCollection.find_one(kriteria1Object)
inventori = "["
for i in range(11):
if (i != 0):
inventori += str(row[getItemName(i)])
if (i != 10):
inventori += ", "
else:
inventori += "]"
for i in range(10):
inventori += str(row[getItemName(i)])
if (i != 9):
inventori += ", "
else:
inventori += "]"
response = "{'status' : 'ok','inventory' : " + inventori + "}";
elif (method == 'mixitem'):
token = dataJSON['token']
item1 = dataJSON['item1']
item2 = dataJSON['item2']
itemresult = ""
if ((item2 == item1 + 1) and ((item1 != 3) or (item1 != 6) or (item != 8))):
itemresult = -1
if ((item2 == item1 + 1) and ((item1 != 3) or (item1 != 6) or (item1 != 8) or (item1 != 9))):
name_item1 = getItemName(item1)
name_item2 = getItemName(item2)
kriteria1Object = {"token":token}
n_item = database.inventoriCollection.find_one(kriteria1Object)
if ((n_item[name_item1] != 3) or (n_item[name_item2] != 3)):
itemresult += "wrong mixture"
if ((n_item[name_item1] < 3) or (n_item[name_item2] < 3)):
itemresult = -1
else:
if (item1 == 0):
itemresult += str(4)
elif (item1 == 1):
itemresult += str(5)
elif (item1 == 2):
itemresult += str(6)
elif (item1 == 4):
itemresult += str(7)
elif (item1 == 5):
itemresult += str(8)
elif (item1 == 7):
itemresult += str(9)
if ((item1 != 3) and (item1 != 6) and (item1 != 8) and (item1 != 9)):
if (item1 == 0):
itemresult = 4
elif (item1 == 1):
itemresult = 5
elif (item1 == 2):
itemresult = 6
elif (item1 == 4):
itemresult = 7
elif (item1 == 5):
itemresult = 8
elif (item1 == 7):
itemresult = 9
# kurangi jumlah item 1 dan 2 sebanyak 3 item
n_item1_baru = n_item[name_item1] - 3
n_item2_baru = n_item[name_item2] - 3
kriteriaItem1 = {"$set":{name_item1:n_item1_baru}}
kriteriaItem2 = {"$set":{name_item2:n_item2_baru}}
database.inventoriCollection.update(kriteria1Object,kriteriaItem1)
database.inventoriCollection.update(kriteria1Object,kriteriaItem2)
# tambah jumlah item campuran sebanyak 1 item
name_mixture = getItemName(itemresult)
n_item_mixture = n_item[getItemName(itemresult)] + 1
kriteriaItemMixture = {"$set":{name_mixture:n_item_mixture}}
database.inventoriCollection.update(kriteria1Object,kriteriaItemMixture)
else:
itemresult += "wrong mixture"
itemresult = -1
else:
itemresult += "wrong mixture"
itemresult = -1
if (itemresult != "wrong mixture"):
response = "{'status':'ok','item':'" + itemresult + "'}"
if (itemresult != -1):
response = "{'status':'ok','item':'" + str(itemresult) + "'}"
else:
response = "{'status':'fail','description':'wrong mixture'}"
elif (method == 'fetchitem'):
......@@ -243,21 +267,84 @@ def playserver(portLaptop):
elif (method == 'offer'):
token = dataJSON['token']
offered_item = dataJSON['offered_item']
n1 = dataJSON['n1']
demand_item = dataJSON['demand_item']
n2 = dataJSON['n2']
n_item1 = dataJSON['n1']
demanded_item = dataJSON['demanded_item']
n_item2 = dataJSON['n2']
kriteria1Object = {"token" : token}
if (database.playerCollection.find(kriteria1Object).count() != 0):
player = database.playerCollection.find_one(kriteria1Object)
objectOfferToken = hashlib.md5(str.encode(username + str(player['time'])))
offered_token = objectOfferToken.hexdigest();
inventory = database.inventoriCollection.find_one(kriteria1Object)
kriteria2Object = {'offered_item' : offered_item, 'n1' : n1, 'demand_item' : demand_item, 'n1' : n1, 'availability' : 'true', 'offered_token' : offered_token}
database.offerCollection.insert(kriteria2Object)
response = "{'status' : 'ok'}"
n_item1_inventory = inventory[getItemName(offered_item)]
if (n_item1_inventory >= n_item1):
objectOfferToken = hashlib.md5(str.encode(str(player['username']) + str(player['player_time'])))
offered_token = objectOfferToken.hexdigest();
#kurangi offered item di inventori
kriteria2Object = {"token":token}
kriteria3Object = {"$set": {getItemName(offered_item) : n_item1_inventory - n_item1}}
database.inventoriCollection.update(kriteria2Object,kriteria3Object)
kriteria2Object = {'offered_item' : offered_item, 'n_item1' : n_item1, 'demanded_item' : demanded_item, 'n_item2' : n_item2, 'availability' : 'true', 'offered_token' : offered_token, 'user_token' : token}
database.offerCollection.insert(kriteria2Object)
response = "{'status' : 'ok'}"
else:
response = "{'status' : 'fail', 'description' : 'items not enough'}"
else:
response = "{'status' : 'fail', 'description' : 'wrong token'}"
elif (method == 'tradebox'):
token = dataJSON['token']
kriteria1Object = {"user_token" : token}
offer_self = []
for temp in database.offerCollection.find(kriteria1Object):
data = []
data.append( temp["offered_item"] )
data.append( temp["n_item1"] )
data.append( temp["demanded_item"] )
data.append( temp["n_item2"] )
data.append( temp["availability"] )
data.append( temp["offered_token"] )
offer_self.append(data)
dictResponse = { "status" : "ok", "offers" : offer_self }
response = str(dictResponse)
elif (method == 'sendfind'):
token = dataJSON['token']
item = dataJSON['item']
kriteria1Object = {"offered_item" : item}
offer_all = []
for temp in database.marketCollection.find(kriteria1Object):
data = []
data.append( temp["offered_item"] )
data.append( temp["n_item1"] )
data.append( temp["demanded_item"] )
data.append( temp["n_item2"] )
data.append( temp["availability"] )
data.append( temp["offered_token"] )
offer_self.append(data)
dictResponse = { "status" : "ok", "offers" : offer_self }
response = str(dictResponse)
elif (method == 'findoffer'):
item = dataJSON['item']
kriteria1Object = {"offered_item" : item}
offer_all = []
for temp in offerCollection.find(kriteria1Object):
data = []
data.append( temp["offered_item"] )
data.append( temp["n_item1"] )
data.append( temp["demanded_item"] )
data.append( temp["n_item2"] )
data.append( temp["availability"] )
data.append( temp["offered_token"] )
offer_self.append(data)
dictResponse = { "status" : "ok", "offers" : offer_self }
response = str(dictResponse)
elif (method == 'canceloffer'):
token = dataJSON['token']
offer_token = dataJSON['offer_token']
......@@ -282,7 +369,36 @@ def playserver(portLaptop):
response = "{'status':'ok'}"
else:
response = "{'status':'fail','description':'not exists'}"
response = "{'status':'fail','description':'not exists'}"
elif (method == 'sendaccept'):
token = dataJSON['token']
offer_token = dataJSON['offer_token']
kriteria1Object = {"offered_token": offer_token}
if (database.marketCollection.find(kriteria1Object).count() != 0):
# Dapat jumlah item yang dioffer beserta nama itemnya
offer = database.marketCollection.find_one(kriteria1Object)
n_offer = offer['n_item1']
name_offer = getItemName(offer['offer_item'])
# Tambahkan jumlah item offer yang diterima dengan item lama
kriteria2Object = {"token": token}
inventoriLama = database.inventoriCollection.find_one(kriteria2Object)
n_item_baru = n_offer + inventoriLama[name_offer]
# Set data offering jadi unavailable
database.marketCollection.update(kriteria1Object,{"$set":{"availability":"false"}})
# Update inventori setelah accept offer
database.inventoriCollection.update(kriteria2Object,{"$set":{name_offer:n_item_baru}})
response = "{'status':'ok'}"
else:
kriteria2Object = {"offered_token":offer_token}
response = "{'status' : 'fail', 'description' : 'not exists'}"
elif (method == 'accept'):
offer_token = dataJSON['offer_token']
kriteria1Object = {"offered_token" : offer_token,"availability" : "false"}
if (database.marketCollection.find(kriteria1Object).count() != 0):
response = "{'status':'ok'}"
else:
response = "{'status' : 'fail', 'description' : 'offer is not available'}"
elif (method == 'map'):
response = '{"status" : "ok", "name" : "Bandar Behari", "width" : 10, "height" : 10}'
elif (method == 'move'):
......@@ -291,7 +407,8 @@ def playserver(portLaptop):
response = '{"status" : "ok", "item" : 2}'
else:
response = "{'status' : 'error'}"
print("+ " + response)
#kirim response ke client
a.sendall(str.encode(response))
#tutup koneksi socket client
......@@ -319,10 +436,6 @@ def playserver(portLaptop):
if __name__ == '__main__':
#try:
#thread.start_new_thread(join,(8500,))
#except:
#print("Error : unable to start thread")
join(8500)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thealchemist.controller;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author toshibapc
*/
public class ConnectionControler {
private Socket socket;
public static String host;
public static int port;
public ConnectionControler(String host, int port)
{
try {
socket = new Socket(host, port);
} catch (IOException ex) {
Logger.getLogger(ConnectionControler.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Boolean sendMessage(JSONObject jSONObject)
{
try {
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
PrintWriter printWriter = new PrintWriter(dataOutputStream);
printWriter.println(jSONObject.toString());
printWriter.flush();
return true;
} catch (IOException ex) {
return false;
}
}
public JSONObject receiveMessage ()
{
DataInputStream dataInputStream = null;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(dataInputStream));
return new JSONObject(br.readLine());
} catch (IOException | JSONException ex) {
Logger.getLogger(ConnectionControler.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
dataInputStream.close();
} catch (IOException ex) {
Logger.getLogger(ConnectionControler.class.getName()).log(Level.SEVERE, null, ex);
}
}
return null;
}
public void closeConnection ()
{
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ConnectionControler.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thealchemist.controller;
/**
*
* @author toshibapc
*/
public class Controller {
public boolean MixItem ()
{
return true;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thealchemist.model;
/**
*
* @author toshibapc
*/
public class Avatar {
public static int posX, posY;
public static String token;
public static int findItem;
public static String findItemId;
public static long time;
public Avatar()
{
}
/**
* @return the posX
*/
public int getPosX() {
return posX;
}
/**
* @param posX the posX to set
*/
public void setPosX(int posX) {
this.posX = posX;
}
/**
* @return the posY
*/
public int getPosY() {
return posY;
}
/**
* @param posY the posY to set
*/
public void setPosY(int posY) {
this.posY = posY;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thealchemist.model;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
/**
*
* @author toshibapc
*/
public class Clay {
private int amount;
private JLabel label;
private String offerToken;
public Clay() {
amount = 2;
ImageIcon imageIcon = new ImageIcon("F:\\Tubes Sister\\Clay.PNG");
label = new JLabel(imageIcon);
offerToken="";
}
/**
* @return the amount
*/
public int getAmount() {
return amount;
}
/**
* @param amount the amount to set
*/
public void setAmount(int amount) {
this.amount = amount;
}
/**
* @return the label
*/
public JLabel getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(JLabel label) {
this.label = label;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package thealchemist.model;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
/**
*