Skip to content

Commit

Permalink
You can now drop into games, and the port is taken from an external i…
Browse files Browse the repository at this point in the history
…ni file
  • Loading branch information
FenixFeather committed Dec 7, 2013
1 parent ac583e2 commit a72b004
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 31 deletions.
29 changes: 26 additions & 3 deletions cards_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pickle
import socket
import sys
import ConfigParser

class ClientPlayer():
def __init__(self,ip,port,name):
Expand Down Expand Up @@ -159,11 +160,33 @@ def update(s):
sys.stdout.write("\r ")
sys.stdout.flush()
sys.stdout.write("\r" + (s))
sys.stdout.flush()

sys.stdout.flush()

class ConfigReader():
@staticmethod
def getPort():
Config = ConfigParser.ConfigParser()
try:
with open("settings.ini",'r') as cfgfile:
Config.readfp(cfgfile)
Config.sections()
port = Config.getint('Settings', 'Port')
cfgfile.close()
return port
except:
print("Error getting settings, reverting to default.")
Config = ConfigParser.ConfigParser()
Config.add_section('Settings')
Config.set('Settings','Port',2809)
with open("settings.ini",'w') as cfgfile:
Config.write(cfgfile)
cfgfile.close()
return 2809

if __name__ == "__main__":
serverIp = raw_input("Enter server IP address: ")
port = int(raw_input("Enter server port: "))
# port = int(raw_input("Enter server port: "))
port = ConfigReader.getPort()
me = ClientPlayer(serverIp, port, raw_input("Enter name: "))
game = Game(serverIp, port, me)
# time.sleep(30)
Expand Down
17 changes: 11 additions & 6 deletions cards_gui_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from threading import Thread
from PyQt4 import QtGui, QtCore
import pdb
import ConfigParser

class MainWindow(QtGui.QMainWindow):
def __init__(self):
Expand Down Expand Up @@ -128,8 +129,9 @@ def start(self):
print("start")
try:
print(self.ipEdit.text())
self.me = cards_client.ClientPlayer(self.ipEdit.text(), 12345, str(self.nameEdit.text()) if self.nameEdit.text() != '' else "FNG")
self.game = cards_client.Game(self.ipEdit.text(), 12345, self.me)
port = cards_client.ConfigReader.getPort()
self.me = cards_client.ClientPlayer(self.ipEdit.text(), port, str(self.nameEdit.text()) if self.nameEdit.text() != '' else "FNG")
self.game = cards_client.Game(self.ipEdit.text(), port, self.me)

for widget in self.gridWidgets:
while not widget.isHidden():
Expand Down Expand Up @@ -171,16 +173,21 @@ def start(self):
def submit(self):
self.me.directSubmit(self.choice,self.me.isJudge)
self.submitButton.setDisabled(True)
self.discard()
self.judged = True
# self.descriptionLabel.setText("The description for the round was: {0}.".format(self.description.strip('\n')))

def discard(self):
cardList = self.guiPool if not self.guiHand[0].isEnabled() else self.guiHand
cardList[self.choice].setText("")


def choose(self, cardList=[]):
if not self.guiHand[0].isEnabled():
cardList = self.guiPool
else:
cardList = self.guiHand

sender = self.sender()
sender = self.sender()
self.choice = cardList.index(sender)
for button in cardList:
button.setChecked(False)
Expand Down Expand Up @@ -211,8 +218,6 @@ def updateGuiPool(self):
self.grid.addWidget(card,2,i)
card.show()
self.submitButton.setDisabled(False)

# time.sleep(30)

for i,button in enumerate(self.guiPool):
button.setText(self.me.pool[i].text)
Expand Down
82 changes: 60 additions & 22 deletions cards_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import socket
import pickle
import time
import ConfigParser

class SocketManager:

Expand Down Expand Up @@ -115,7 +116,8 @@ def __init__(self, Deck):
self.players = []
self.deck = Deck
HOST = '' #we are the host
PORT = int(raw_input("Port: ")) #arbitrary port not currently in use
# PORT = int(raw_input("Port: ")) #arbitrary port not currently in use
PORT = ConfigReader.getPort()
ADDR = (HOST,PORT) #we need a tuple for the address
self.BUFSIZE = 4096 #reasonably sized buffer for data

Expand All @@ -130,7 +132,8 @@ def __init__(self, Deck):
print [player.name for player in self.players]
self.judge = random.choice(self.players)
self.winnerName = "Nobody"
self.playerToRemove = None
self.playersToRemove = []
self.playersToAdd = []

def initPlayers(self,numPlayers):
while len(self.players) != numPlayers:
Expand Down Expand Up @@ -159,6 +162,9 @@ def handleRequests(self,player):
conn,addr = self.serv.accept()
data = pickle.loads(conn.recv(self.BUFSIZE))
print(data)
if not any([data[0] == hash(person) for person in self.players]) and not any([data[0] == hash(person) for person in self.playersToAdd]):
self.playersToAdd.append(Player(*data))
print("Added {0}".format(data[0]))
if str(data[1]) == 'myturn':
conn.send(pickle.dumps((hash(player) == data[0],player.name)))
conn.close()
Expand Down Expand Up @@ -188,22 +194,27 @@ def handleRequests(self,player):
conn.close()
return
elif data[1] == 'disconnect':
shouldReturn = False
for person in self.players:
shouldReturn = (person == player)
if data[0] == hash(person):
if person == self.judge:
self.judge = Player(-1,"Ghost")
self.judge.pool = person.pool
self.judge.dCard = person.dCard
print("{0} has disconnected!".format(person))
if self.players.index(person) > self.players.index(player):
self.players.remove(person)
else:
self.playerToRemove = person
conn.close()
if shouldReturn:
return
if not any([data[0] == hash(candidate) for candidate in self.playersToAdd]):
shouldReturn = False
for person in self.players:
shouldReturn = (person == player)
if data[0] == hash(person):
if person == self.judge:
self.judge = Player(-1,"Ghost")
self.judge.pool = person.pool
self.judge.dCard = person.dCard
print("{0} has disconnected!".format(person))
if self.players.index(person) > self.players.index(player):
self.players.remove(person)
else:
self.playersToRemove.append(person)
conn.close()
if shouldReturn:
return
else:
for candidate in self.playersToAdd:
if data[0] == hash(candidate):
self.playersToAdd.remove(candidate)

elif str(data[1]) == 'winner':
winnerHash = self.judge.judge(data[2])
Expand All @@ -228,7 +239,9 @@ def newRound(self):
self.judge.dCard = None
self.roundEnd = False
self.winnerName = "Nobody"
self.playerToRemove = None
self.playersToRemove = []
self.playersToAdd = []
print [player.name for player in self.players]
try:
self.judge = self.players[(self.players.index(self.judge) + 1)%len(self.players)] #rotate judge position
except ValueError:
Expand All @@ -240,8 +253,9 @@ def newRound(self):
if player != self.judge:
self.handleRequests(player)

if self.playerToRemove:
self.players.remove(self.playerToRemove)
for player in self.playersToRemove:
self.players.remove(player)

#Judging time
random.shuffle(self.judge.pool)
if self.judge.number != -1:
Expand All @@ -255,7 +269,10 @@ def newRound(self):
self.roundEnd = True
while int(time.time()) - start != 3:
self.handleRequests(Player(1,"stragglers"))


self.players += self.playersToAdd
self.drawCards()

def constructScoresDict(self):
result = {}
for player in self.players:
Expand All @@ -278,6 +295,27 @@ def endGame(self):
for player in self.players:
print("{0}: {1}".format(str(player), player.score))

class ConfigReader():
@staticmethod
def getPort():
Config = ConfigParser.ConfigParser()
try:
with open("settings.ini",'r') as cfgfile:
Config.readfp(cfgfile)
Config.sections()
port = Config.getint('Settings', 'Port')
cfgfile.close()
return port
except:
print("Error getting settings, reverting to default.")
Config = ConfigParser.ConfigParser()
Config.add_section('Settings')
Config.set('Settings','Port',2809)
with open("settings.ini",'w') as cfgfile:
Config.write(cfgfile)
cfgfile.close()
return 2809

if __name__ == "__main__":
Deck = deck() #Begin by initializing a deck
Deck.shuffleCards()
Expand Down

0 comments on commit a72b004

Please sign in to comment.