Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from threading import Thread

host = gethostname() # #
#host = '10.129.5.203'
port = 5555

s = socket(AF_INET, SOCK_STREAM)
Expand Down Expand Up @@ -32,6 +33,6 @@ def from_server():

while True:
try:
s.send(input().encode())
s.send(input().encode())
except OSError:
exit(0)
53 changes: 53 additions & 0 deletions player.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
class Player:

def __init__(self,ip):
self.ip = ip
#[nazwa, ilość]
self.possesions = [["gold", 0], ["silver", 0], ["copper", 0]]
self.money = 3000
self.name=""

def set_name(self,name):
self.name = name

def to_string(self):
string = "\n\nName: " + self.name + "\nMoney: " + str(self.money) + "\nPossesions: "
for p in self.possesions:
string = string + "\n " + p[0] + " " + str(p[1])
string = string + "\n"
return string



def has_enough_possesions(self,product_id,amount):
return self.possesions[product_id][1] >= amount

def add_possesions(self,product_id,amount):
self.possesions[product_id][1] += amount


def reduce_possesions(self,product_id,amount):
self.possesions[product_id][1] -= amount


def has_enough_money(self,price):
return self.money >= price

def add_money(self,price):
self.money += price


def reduce_money(self,price):
self.money -= price












67 changes: 64 additions & 3 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sys
import threading
import queue
from stock import Stock
from time import sleep

host = socket.gethostname() # #
Expand All @@ -15,6 +16,7 @@
sys.exit(0)



try:
s.bind((host, port))
print("SOCKET BOUND TO PORT: " + str(port))
Expand All @@ -24,16 +26,21 @@

s.listen(7)

#clients_left
#clients_current


def client_thread(conn, lock, q):
conn.setblocking(False)
global clients_current

while True:
try:



if conn.recv(1024).decode() == "START":
conn.sendall("OK, WAITING FOR OTHERS".encode())

# locking global value from other threads
lock.acquire()
clients_current += 1
Expand All @@ -53,6 +60,7 @@ def client_thread(conn, lock, q):

# GAME IN PROGRESS
while True:
conn.sendall(st.player_state(conn.getpeername()[0] + ':' + str(conn.getpeername()[1])).encode())
conn.sendall("STARTING IN:".encode())

for i in reversed(range(1, 6)):
Expand All @@ -70,9 +78,11 @@ def client_thread(conn, lock, q):
while q.empty():
try:
data = conn.recv(1024)
reply = handle_request(data.decode(),conn.getpeername()[0] +
':' + str(conn.getpeername()[1]))
print('RECEIVED: ' + data.decode() + ', FROM: ' + conn.getpeername()[0] + ':' +
str(conn.getpeername()[1]))
reply = "->" + data.decode()
#reply = "->" + data.decode()
conn.sendall(reply.encode())
except socket.error:
pass
Expand Down Expand Up @@ -101,6 +111,8 @@ def client_thread(conn, lock, q):
conn.close()




def connect_clients():
is_first_client = True
global clients_total
Expand All @@ -115,6 +127,8 @@ def connect_clients():
if clients_left:
thread_conn, address = s.accept()
print("CONNECTED TO " + address[0] + ":" + str(address[1]))
st.add_player(address[0] + ":" + str(address[1]))
st.players[-1].set_name("player " + str(len(st.players)))

if is_first_client:
thread_conn.sendall("YOU'RE CONNECTED TO THE SERVER. ENTER THE NUMBER OF PLAYERS (2-8)".encode())
Expand Down Expand Up @@ -152,29 +166,71 @@ def connect_clients():
break


def handle_request(data,player):
try:

split = data.split()
for i in range(len(st.players)):
if player == st.players[i].ip:
player_id = i

if split[0] == "buy":
for i in range(len(st.stock)):
if st.stock[i][0] == split[1]:
return(st.sell_to_player(player_id,i,int(split[2])))

if split[0] == "sell":
for i in range(len(st.stock)):
if st.stock[i][0] == split[1]:
return(st.buy_from_player(player_id,i,int(split[2])))

return "Wrong request."

except (ValueError, IndexError):
return("Wrong request.")

def set_player_name(name,player_ip):
try:
for i in range(len(st.players)):
if player_ip == st.players[i].ip:
st.players[i].set_name(name)
except IndexError:
pass


clients_total = 1
clients_current = 0
clients_left = 1

clients=[]

rounds_total = 3
rounds_current = 1

threads = []
queues = []
round_time = 5
round_time = 10
break_time = 3

st=Stock()
connect_clients()


# WAITING FOR CLIENTS TO CONFIRM START
while clients_total != clients_current:
sleep(1)
print("WAITING FOR: " + str(clients_total-clients_current) + " MORE CLIENTS")

print("\n\nALL CLIENTS READY. STARTING THE GAME")
print("\n\nREQUEST SHOULD BE <action> <product> <amount>")
print("\n\nE.G. buy gold 10; sell copper 15")
st.print_state()

for q in queues:
q.put(".")



while True:
print("\nCOUNTING DOWN")
sleep(5)
Expand All @@ -192,13 +248,17 @@ def connect_clients():
q.put("EXIT")

print("THE GAME HAS ENDED")
st.print_state()
break
else:
for q in queues:
q.put(".")

print("START BREAK")
# TIME FOR PRICE CHANGE ETC.

st.calculate_new_prices()
st.print_state()
sleep(break_time)
print("END BREAK")

Expand All @@ -213,4 +273,5 @@ def connect_clients():
t.join()

print("THE END")
st.show_results()
exit(0)
75 changes: 75 additions & 0 deletions stock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
from player import Player

class Stock:

def __init__(self):
self.players = []
#[nazwa,aktualna ilość,aktualna cena, początkowa ilość, początkowa cena]
#początkowe wartości są używane tylko do policzenia zmian ceny
self.stock = [["gold", 200, 150.0, 200, 150.0], ["silver", 200, 120.0, 200, 120.0], ["copper", 200, 80.0, 200, 80.0]]

def add_player(self,name):
self.players.append(Player(name))

def print_state(self): #w tej chwili printuje też posiadłości graczy, zamiast tego powinien to wysyłać do client.py(?)
#for p in self.players:
# print(p.to_string())
print("Available stock:")
for s in self.stock:
print("Product: " + s[0] + " Available: " + str(s[1]) + " Price: " + str(s[2]))

def player_state(self,player_ip):
for p in self.players:
if p.ip == player_ip:
return p.to_string()


def sell_to_player(self,player_id,product_id,amount):
price = amount * self.stock[product_id][2]
if amount <= 0:
return "Wrong amount."
if not (self.players[player_id].has_enough_money(price)):
return "Not enough money."
if self.stock[product_id][1] < amount:
return "Not enough products in stock."

self.players[player_id].reduce_money(price)
self.players[player_id].add_possesions(product_id,amount)
self.stock[product_id][1] -= amount

return "Transaction succesful."

def buy_from_player(self,player_id,product_id,amount):
price = amount * self.stock[product_id][2]
if amount <= 0:
return "Wrong amount."
if not self.players[player_id].has_enough_possesions(product_id,amount):
return "Not enough products in possesion."

self.players[player_id].add_money(price)
self.players[player_id].reduce_possesions(product_id,amount)
self.stock[product_id][1] += amount


return "Transcation succesful."

def calculate_new_prices(self):
for s in self.stock:
if s[1] <= s[3]:
s[2] = s[4] + ((s[1] - s[3])*(s[1] - s[3]))*0.01
if s[1] > s[3]:
s[2] = s[4] - ((s[1] - s[3])*(s[1] - s[3]))*0.01

def show_results(self):
results = []
for p in self.players:
score = p.money
for i in range(len(self.stock)):
score += self.stock[i][2] * p.possesions[i][1]
results.append((p.name, score))
results.sort(key = lambda x: x[1], reverse = True)
print("\n\n\t\tRESULTS:")
for r in results:
print("\n\t" + str(r[0]) + " score: " + str(r[1]) )