Exemplo n.º 1
0
def shutdown(client, arg):
    if client in clients:
        broadcast(Participant.Bot("server"),
                  f"{clients[client].name} is shutting down the server")
    else:
        broadcast(Participant.Bot("server"),
                  f"The host is shutting down the server")
    for c in clients:
        c.close()
    clients.clear()
    server.close()
    raise SystemExit
Exemplo n.º 2
0
    def resetGame(self):
        self.matchID = None
        # dummy entries, overridden on first newGame packet
        self.leftOpp = Participant()
        self.rightOpp = Participant()
        self.numHands = None
        self.stackSize = None
        self.bigB = None
        self.smallB = None
        self.timebank = None

        self.numArrivalsAtStreet = [0,0,0,0]
        self.hand = Hand()
Exemplo n.º 3
0
def listen_for_data(c):
    while True:
        try:
            sender, message = pickle.loads(c.recv(1024))
            if not perform_command(c, message) and len(message) > 0:
                print(f"{sender.name}: {message}")
                broadcast(sender, message)
        except ConnectionResetError:
            p = clients.pop(c, Participant.Bot("Someone"))
            print(f"{p.name} left the server")
            broadcast(Participant.Person("server"), f"{p.name} left the chat!")
            c.close()
            break
        except ConnectionAbortedError:
            break
Exemplo n.º 4
0
def createParticipants(surveyData):
    participants = []
    for participantAnswers in surveyData:
        participant = Participant.Participant(participantAnswers)
        if participant.personalData[8] != "Muito baixo":
            participants.insert(0, participant)
    extroversions = list(map(lambda p: p.ocean.extroversion, participants))
    qt = stats.mstats.mquantiles(extroversions,
                                 prob=[0.2, 0.4, 0.6, 0.8],
                                 alphap=0.5,
                                 betap=0.5)

    # shapiro_test = stats.shapiro(extroversions)
    # print(shapiro_test)
    # print("n=" + str(len(extroversions)))
    # print("pontos de extroversão =" + str(extroversions))
    desvio = statistics.pstdev(extroversions)
    # print("desvio " + str(desvio))
    media = statistics.mean(extroversions)
    # print("media " + str(media))
    lIntro = media - desvio / 2
    lExtro = media + desvio / 2
    # print("intro<=" + str(lIntro) + " // extro>=" + str(lExtro))
    for p in participants:
        p.rankExtroversionLevel(lIntro, lExtro)

    return participants
Exemplo n.º 5
0
def Solution():
    """docstring for Solution"""
    questions = int(input())
    options = []
    quesObj = Question()
    quiz = Quiz()
    for i in range(questions):
        question = str(input())
        for i in range(4):
            options.append(str(input()))
        quesObj = Question(question, options)
        quiz.addQuestion(quesObj)
    participants = int(input())
    for i in range(participants):
        name = str(input())
        for i in range(questions):
            lines = input().split(" ")
            q = int(lines[0])
            parsObj = Participant(name, q - 1, lines[1])
            x = quesObj.indexOf((lines[1]))
            quesObj.setOptionVotes(x)

    for i in range(questions):
        print("Highest number of votes for question : " +
              quiz.getQuestion(i).getText() + " : " +
              quiz.getQuestion(i).commonSelectedOption())
Exemplo n.º 6
0
    def __accept_button_clicked(self, button):
        print("Accept button clicked")

        if (self.__mode == ActionMode.ADD):
            entry = self._builder.get_object("entry")
            text = entry.get_text()
            print("Value:|{}|".format(text))

            if (text != ""):
                listboxRow = Gtk.ListBoxRow()
                listboxRow.add(Gtk.Label(text))
                listboxRow.set_size_request(60, 60)
                if (self._insertController.isParticipant(text)):
                    print("Participant already exists!")
                else:
                    self.__listBox.add(listboxRow)
                    self._insertController.addParticipant(Participant(text))
                    self._window.show_all()
            elif (self.__mode == ActionMode.MODIFY):
                pass
            elif (self.__mode == ActionMode.DELETE):
                pass

        self.__addButtonSetSensitive(True)
        self.__deleteButtonSetSensitive(True)
        self.__modifyButtonSetSensitive(True)
        self.__enteringAreaSetSensitive(False)
        self.__clearEntry()
Exemplo n.º 7
0
    def addParticipant(self, participant):

        if (isinstance(participant, Participant)):
            self._participants.append(participant)
        elif (isinstance(participant, str)):
            newParticipant = Participant(participant)
            self._participants.append(newParticipant)
        else:
            raise ValueError
Exemplo n.º 8
0
def kick(client, participant):
    to_be_kicked = None
    for c in clients:
        if clients[c].name.lower() == participant.lower():
            to_be_kicked = c
            broadcast(Participant.Bot("server"),
                      f"{clients[c].name} has been kicked from the chat!")
            print(f"{clients[c].name} has been kicked from the server!")
    if isinstance(to_be_kicked, socket.socket):
        clients.pop(to_be_kicked)
        to_be_kicked.close()
Exemplo n.º 9
0
def update_name(client, new_name):
    #  Do not let host change name:
    if client == host:
        print(
            "Sorry, as a host we have chosen that you should remained named as \"Host\""
        )
    else:
        # If a command has been performed, broadcast it to all the other clients:
        # Broadcast as bot because we don't want the bots to respond
        broadcast(
            Participant.Bot("server"),
            f"{clients[client].name} has changed their name to {new_name}")

        # Then update the clients new name:
        clients[client].name = new_name
Exemplo n.º 10
0
def send_help(client, arg):
    available_commands = list(commands.keys())
    available_commands.append("/logout")

    help_message = f"These are the following available commands:\n{available_commands}"
    for c in clients:
        if isinstance(clients[c], Participant.Bot):
            help_message += f"\n{clients[c].name} " \
                            f"responds to any sentences that includes one or more of thse keywords:" \
                            f"\n{clients[c].get_help()}"

    if client == host:
        print(help_message)
    else:
        package = pickle.dumps((Participant.Bot("server"), help_message))
        client.send(package)
Exemplo n.º 11
0
 def __get_participants(self):
     all = {}
     for participant in self.__participants:
         all[participant] = Participant(participant)
     return all
Exemplo n.º 12
0
class GameState:
    def __init__(self):
        self.state = None
        self.me = Participant()
        self.resetGame()
        self.resetHand()

    def resetGame(self):
        self.matchID = None
        # dummy entries, overridden on first newGame packet
        self.leftOpp = Participant()
        self.rightOpp = Participant()
        self.numHands = None
        self.stackSize = None
        self.bigB = None
        self.smallB = None
        self.timebank = None

        self.numArrivalsAtStreet = [0,0,0,0]
        self.hand = Hand()
        #self.trackedHands = [CHECK,BET,RAISE,CALL, POST]

    def resetHand(self):
        self.handID = None
        self.me.newHand()
        self.leftOpp.newHand()
        self.rightOpp.newHand()
        self.holeCard1 = None
        self.holeCard2 = None

        self.potSize = None
        self.pot = 0
        self.numBoardCards = None

        self.boardCards = "__,__,__,__,__"#["__","__","__","__","__"]
        self.numLastActions = None
        self.lastActions = None
        self.numLegalActions = None
        self.legalActions = None

        self.hand.clearHand()

        self.lastBet = 0
        self.street = PREFLOP
        self.activePlayers = 3
        self.lastActor = None


    def parseInput(self, input):
        numOptArgs = 0
        packet = input.split(" ")
        self.state = packet[0]
        if self.state == NEWGAME:
            self.resetGame()

            self.matchID = int(packet[1])
            self.leftOpp = Participant(packet[2])
            self.rightOpp = Participant(packet[3])
            self.numHands = int(packet[4])
            self.stackSize = int(packet[5])
            self.bigB = int(packet[6])
            self.smallB = int(packet[7])
            self.timebank = float(packet[8])

        elif self.state == NEWHAND:
            self.resetHand()

            self.handID = int(packet[1])
            self.me.position = int(packet[2])
            self.rightOpp.position = (self.me.position - 1)%3
            self.leftOpp.position = (self.me.position + 1)%3
            self.holeCard1 = Card(packet[3])
            self.holeCard2 = Card(packet[4])
            self.me.holeCard1 = packet[3]
            self.me.holeCard2 = packet[4]
            self.me.bankroll = int(packet[5])
            self.leftOpp.bankroll = int(packet[6])
            self.rightOpp.bankroll  = int(packet[7])
            self.timeBank = float(packet[8])
            self.numArrivalsAtStreet[self.street] += 1

        elif self.state == GETACTION:
            self.potSize = int(packet[1])
            self.numBoardCards = int(packet[2])
            if self.numBoardCards>0:
                numOptArgs += 1
                self.boardCards = packet[3]    #Card(packet[3+i])
            #parse action
            self.numLastActions = int(packet[3+numOptArgs])
            if self.numLastActions>0:
                numOptArgs += 1
                self.lastActions = packet[3+numOptArgs]
            self.numLegalActions = int(packet[4+numOptArgs])
            if self.numLegalActions > 0:
                self.legalActions = packet[5+numOptArgs]

            self.timebank = float(packet[-1])

            self.parseBoardCards()
            self.parseLastActions()
            self.parseLegalActions()
            print self.potSize, "=?", self.pot

        elif self.state == HANDOVER:
            self.me.bankroll = int(packet[1])
            self.leftOpp.bankroll = int(packet[2])
            self.rightOpp.bankroll = int(packet[3])
            self.numLastActions = int(packet[4])
            #parse actions
            if self.numLastActions>0:
                numOptArgs += 1
                self.lastActions = packet[5]
            self.numBoardCards = int(packet[5+numOptArgs])
            if self.numBoardCards>0:
                numOptArgs += 1
                self.boardCards = packet[5+numOptArgs]
            self.timebank = float(packet[-1])

            self.parseBoardCards()
            self.parseLastActions()
            self.hand.splitActionsList()
            #self.calculatePlayerStats()
            self.leftOpp.archive.update(self)
            self.rightOpp.archive.update(self)

            print "my bankroll:", self.me.bankroll
            print self.leftOpp.name, " bank:", self.leftOpp.bankroll
            print self.rightOpp.name, " bank:", self.rightOpp.bankroll

    def parseLastActions(self):
        if self.lastActions:
            self.lastActions = self.lastActions.split(",")
            for i in range(self.numLastActions):
                self.lastActions[i] = self.lastActions[i].split(":")
                #add each action into structure, Hand

                c1 = None
                c2 = None

                sla = self.lastActions[i][0]
                actor = self.lastActions[i][1]
                if actor == self.leftOpp.name:
                    player = self.leftOpp
                elif actor == self.rightOpp.name:
                    player = self.rightOpp
                else:
                    player = self.me

                player.totalPot = self.pot + self.me.pip + self.leftOpp.pip + self.rightOpp.pip
                potamt = 0
                betamt = 0
                amt = self.lastBet
                if len(self.lastActions[i]) == 3:
                    amt = float(self.lastActions[i][2])

                if sla == "RAISE":
                    betamt = amt/float(self.lastBet)
                    potamt = amt/float(player.totalPot)
                    self.lastBet = amt
                    player.stack -= amt - player.pip

                    if not player.aggFreqChanged:
                        player.numBets[self.street] += 1
                        player.aggFreqChanged = True
                    player.amountContributed[self.street] += amt - player.pip
                    player.amountBetRaise[self.street] += amt - player.pip
                    player.pip = amt
                elif sla == "CALL":
                    betamt = 1.0
                    potamt = amt/float(player.totalPot)
                    player.stack -= self.lastBet - player.pip

                    player.amountContributed[self.street] += amt - player.pip
                    player.pip = self.lastBet
                elif sla == "CHECK":
                    if self.street != PREFLOP:
                        amt = 0
                elif sla == "BET":
                    betamt = amt/float(self.lastBet)
                    potamt = amt/float(player.totalPot)
                    self.lastBet = float(self.lastActions[i][2])
                    player.stack -= self.lastBet
                    player.pip = self.lastBet

                    if not player.aggFreqChanged:
                        player.numBets[self.street] += 1
                        player.aggFreqChanged = True
                    player.amountContributed[self.street] += amt
                    player.amountBetRaise[self.street] += amt
                elif sla == "DEAL":
                    amt = 0
                    self.pot += self.me.pip + self.leftOpp.pip + self.rightOpp.pip
                    self.me.pip = 0
                    self.leftOpp.pip = 0
                    self.rightOpp.pip = 0
                    self.street += 1
                    self.numArrivalsAtStreet[self.street] += 1
                    for pl in [self.me, self.leftOpp, self.rightOpp]:
                        pl.aggFreqChanged = False
                        if pl.active==1 and pl.stack>0:
                            pl.numArrivalsAtStreet[self.street] += 1
                        print pl.name, "active:", pl.active, "stack size:", pl.stack, "arrivals:", pl.numArrivalsAtStreet
                elif sla == "POST":
                    self.lastBet = float(self.lastActions[i][2])
                    player.stack -= self.lastBet
                    player.pip = self.lastBet

                    player.amountContributed[self.street] += self.lastBet
                elif sla == "SHOWS":
                    c1 = self.lastActions[i][2]
                    c2 = self.lastActions[i][3]
                    amt = 0
                elif sla == "FOLD":
                    player.active = 0
                    self.activePlayers -= 1
                #elif sla == "REFUND":
                #elif sla == "TIE":
                #elif sla == "WIN":
                if sla in ["POST","BET", "RAISE"]:
                    self.lastActor = player
                    print "lastactor:",self.lastActor.name

                a = Action(ACTION_TYPES.index(sla), self.lastActions[i][1], self.street, c1,
                           c2, potamt, betamt, amt)
                self.hand.actions.append(a)
                player.lastActions.append(a)

#                print "processed action: " + str(a)
#                print "resulting in: stacks",self.me.stack, self.leftOpp.stack, self.rightOpp.stack, "and pips", self.me.pip, self.leftOpp.pip, self.rightOpp.pip
#        print "lastActions", self.lastActions

    def parseLegalActions(self):
        if self.legalActions:
            self.legalActions = self.legalActions.split(",")
            for i in range(self.numLegalActions):
                self.legalActions[i] = self.legalActions[i].split(":")

    def parseBoardCards(self):
        if(type(self.boardCards) == type("STRING")):
            self.boardCards = self.boardCards.split(",")
        for i in range(5-len(self.boardCards)):
            self.boardCards += ["__"]

    def calculatePlayerStats(self):
        for p in [self.leftOpp, self.rightOpp]:
            for s in [0,1,2,3]:
                rounds = p.numArrivalsAtStreet[s]
                if s==0:
                    rounds = self.handID
                if rounds == 0:
                    p.aggFreq[s] = 0
                    p.avgChips[s] = 0
                else:
                    p.avgChips[s] = float(p.amountContributed[s])/rounds
                    p.aggFreq[s] = float(p.numBets[s])/rounds
                if p.numBets[s] >0:
                    p.avgRaiseAmt[s] = float(p.amountBetRaise[s])/p.numBets[s]
                if self.handID !=0:
                    p.percentArrivals[s] = float(rounds)/self.handID
Exemplo n.º 13
0
 def __init__(self):
     self.state = None
     self.me = Participant()
     self.resetGame()
     self.resetHand()
Exemplo n.º 14
0
        print(
            "To start a server that should connect to specified ip and port:\n"
            "$python3 server.py <u>ip</u> <u>port</u>")
        sys.exit()
    port = int(sys.argv[2])
except (IndexError, ValueError):
    print(
        "IP and port must be specified. Correct usage e.g $py server.py localhost 2410"
    )
    sys.exit()

server = socket.socket()
server.bind((ip, port))
server.listen()

host = Participant.Person("Host")

clients = {}

print("Server is running...")


# broadcast to all clients:
def broadcast(sender, message):
    for c in clients:
        data = pickle.dumps((sender, message))
        c.send(data)


# constantly listen if any clients has sent any data:
def listen_for_data(c):
Exemplo n.º 15
0
    def parseInput(self, input):
        numOptArgs = 0
        packet = input.split(" ")
        self.state = packet[0]
        if self.state == NEWGAME:
            self.resetGame()

            self.matchID = int(packet[1])
            self.leftOpp = Participant(packet[2])
            self.rightOpp = Participant(packet[3])
            self.numHands = int(packet[4])
            self.stackSize = int(packet[5])
            self.bigB = int(packet[6])
            self.smallB = int(packet[7])
            self.timebank = float(packet[8])

        elif self.state == NEWHAND:
            self.resetHand()

            self.handID = int(packet[1])
            self.me.position = int(packet[2])
            self.rightOpp.position = (self.me.position - 1)%3
            self.leftOpp.position = (self.me.position + 1)%3
            self.holeCard1 = Card(packet[3])
            self.holeCard2 = Card(packet[4])
            self.me.holeCard1 = packet[3]
            self.me.holeCard2 = packet[4]
            self.me.bankroll = int(packet[5])
            self.leftOpp.bankroll = int(packet[6])
            self.rightOpp.bankroll  = int(packet[7])
            self.timeBank = float(packet[8])
            self.numArrivalsAtStreet[self.street] += 1

        elif self.state == GETACTION:
            self.potSize = int(packet[1])
            self.numBoardCards = int(packet[2])
            if self.numBoardCards>0:
                numOptArgs += 1
                self.boardCards = packet[3]    #Card(packet[3+i])
            #parse action
            self.numLastActions = int(packet[3+numOptArgs])
            if self.numLastActions>0:
                numOptArgs += 1
                self.lastActions = packet[3+numOptArgs]
            self.numLegalActions = int(packet[4+numOptArgs])
            if self.numLegalActions > 0:
                self.legalActions = packet[5+numOptArgs]

            self.timebank = float(packet[-1])

            self.parseBoardCards()
            self.parseLastActions()
            self.parseLegalActions()
            print self.potSize, "=?", self.pot

        elif self.state == HANDOVER:
            self.me.bankroll = int(packet[1])
            self.leftOpp.bankroll = int(packet[2])
            self.rightOpp.bankroll = int(packet[3])
            self.numLastActions = int(packet[4])
            #parse actions
            if self.numLastActions>0:
                numOptArgs += 1
                self.lastActions = packet[5]
            self.numBoardCards = int(packet[5+numOptArgs])
            if self.numBoardCards>0:
                numOptArgs += 1
                self.boardCards = packet[5+numOptArgs]
            self.timebank = float(packet[-1])

            self.parseBoardCards()
            self.parseLastActions()
            self.hand.splitActionsList()
            #self.calculatePlayerStats()
            self.leftOpp.archive.update(self)
            self.rightOpp.archive.update(self)

            print "my bankroll:", self.me.bankroll
            print self.leftOpp.name, " bank:", self.leftOpp.bankroll
            print self.rightOpp.name, " bank:", self.rightOpp.bankroll
Exemplo n.º 16
0
import Appointment
import Participant
import TimeSlotFinder

#Create dummy praticipants
p1 = Participant("Juergen", [])
p2 = Participant("Harald", [])
p3 = Participant("Markus", [])

#Create dummy appointments
for i in range(0, 100):
    start = random.randint(10, 50)
    end = random.randint(70, 100)
    a = Appointment(start, end, "A test appointment")
    p1.addAppointment(a)
for i in range(0, 100):
    start = random.randint(10, 50)
    end = random.randint(70, 100)
    a = Appointment(start, end, "A test appointment")
    p2.addAppointment(a)
for i in range(0, 100):
    start = random.randint(10, 50)
    end = random.randint(70, 100)
    a = Appointment(start, end, "A test appointment")
    p3.addAppointment(a)

print("Done creating appointments")

#Merge and negate appointments of all participants

participants = []
 def make(self, clients_id=None, n=1):
     for _ in range(n):
         res = Participant(self.next_participant_id, self.faker, clients_id)
         self.next_participant_id += 1
         self.participants.append(res)
Exemplo n.º 18
0
import socket
import sys
import Util
import Participant
import Coordinator
ROLE, myip, myport, ip, port = Util.R_Conf(sys.argv)
#print(myip,myport)
if ROLE == 1:
    coor = Coordinator.Coordinator(ip, port, myip, myport)
    coor.TPC_Coordinator()
elif ROLE == 0:
    part = Participant.Participant(ip, port, myip, myport)
    part.TPC_Participant()
Exemplo n.º 19
0
import sys
import Participant
import socket
import pickle
import threading
import re
import time

# Define a dictionary of available bots:
available_bots = {
    'alice': Participant.Alice(),
    'bob': Participant.Bob(),
    'batman': Participant.Batman(),
    'james': Participant.James(),
    'yoda': Participant.Yoda()
}

# Force user to specify ip and port
try:
    ip = sys.argv[1]
    if ip == '--help' or ip == '-h':
        print(
            "To start a client that should connect to specified ip and port:\n"
            "$python3 client.py <u>ip</u> <u>port</u> [ <u>bot_name</u> ]\n\n"
            "> -b <u>bot_name</u>: specify the bot you want this client to be from the list of available bots\n"
            ">> Current available bots: Alice, Bob, Eve\n\n"
            "> Example usage (connecting as a person to localhost:2410):\n"
            ">> $python3 client.py localhost 2410\n\n"
            "> Example usage (connecting as a bot (Alice) to localhost:2410):\n"
            ">> $python3 client.py localhost 2410 alice")
        sys.exit()