コード例 #1
0
ファイル: ChatServer.py プロジェクト: codeTony22/PyChat
    def __init__(self,
                 host=socket.gethostbyname('localhost'),
                 port=50000,
                 allowReuseAddress=True):
        self.address = (host, port)
        self.channels = {}  # Channel Name -> Channel
        self.serializer = Serialization()
        self.channels_client_map = {}  # Client Name -> Channel Name
        try:
            self.serverSocket = socket.socket(socket.AF_INET,
                                              socket.SOCK_STREAM)
        except socket.error as errorMessage:
            sys.stderr.write("Failed to initialize the server. Error - %s\n",
                             str(errorMessage))
            raise

        if allowReuseAddress:
            self.serverSocket.setsockopt(socket.SOL_SOCKET,
                                         socket.SO_REUSEADDR, 1)

        try:
            self.serverSocket.bind(self.address)
        except socket.error as errorMessage:
            sys.stderr.write(
                'Failed to bind to ' + self.address + '. Error - %s\n',
                str(errorMessage))
            raise
コード例 #2
0
 def __init__(self):
     self.fxcm = FXCMOrder()
     self.fxopen = FXOpenOrder()
     self.sereliazation = Serialization()
     self.redis_connector = redis.StrictRedis(host='localhost',
                                              port=6379,
                                              db=0)
     self.status = [["New", "To Provider", "Partially Filled", "Filled"],
                    ["New", "To Provider", "Filled"], ["New", "Filled"],
                    ["New", "Partially Filled", "To Provider", "Filled"],
                    [
                        "New", "Partially Filled", "To Provider",
                        "Rejected", "Filled"
                    ], ["To Provider"], ["To Provider", "Rejected"],
                    ["To Provider", "Filled"], ["New", "To Provider"],
                    ["New", "To Provider", "Rejected"],
                    ["New", "Partially Filled"], ["New"],
                    ["New", "To Provider", "Partially Filled"]]
     self.mongo_result = []
コード例 #3
0
ファイル: Request.py プロジェクト: CapreDiam/MongoTestPython
 def __init__(self):
     self.fxcm = FXCMOrder()
     self.fxopen = FXOpenOrder()
     self.sereliazation = Serialization()
     self.redis_connector = redis.StrictRedis(host='localhost', port=6379, db=0)
     self.status = [["New", "To Provider", "Partially Filled", "Filled"], ["New", "To Provider", "Filled"],
                    ["New", "Filled"], ["New", "Partially Filled", "To Provider", "Filled"],
                    ["New", "Partially Filled", "To Provider", "Rejected", "Filled"], ["To Provider"],
                    ["To Provider", "Rejected"], ["To Provider", "Filled"], ["New", "To Provider"],
                    ["New", "To Provider", "Rejected"], ["New", "Partially Filled"], ["New"],
                    ["New", "To Provider", "Partially Filled"]]
     self.mongo_result = []
コード例 #4
0
    def __init__(self):
        self.roundNumber = 1
        self.stockPile = []
        self.layout = []

        self.humanHand = [[], [], []]
        self.computerHand = [[], [], []]
        self.humanCapture = [[], [], []]
        self.computerCapture = [[], [], []]
        self.numComPlayers = 0
        self.numHumPlayers = 0

        #Initalize classes here
        self.s = Serialization()
        self.deck = Deck()
        self.player = Player()
        self.computer1 = Computer()
        self.computer2 = Computer()
        self.computer3 = Computer()
        self.human1 = Human()
        self.human2 = Human()
        self.human3 = Human()
コード例 #5
0
ファイル: SockCollector.py プロジェクト: iamhyc/ff-ctrl
    def send(self, obj):
        _len, _buffer = ser.dump(obj)
        # _len = _len.to_bytes(length=2)
        packet = PKT_HEADER + _buffer
        _success_flag = 0

        while not _success_flag:
            try:
                self.sock.send(packet)
                _success_flag = 1
                if DBG: print('send once')
            except Exception as e:
                self.reconnect()
            pass
        pass
コード例 #6
0
    def get(self, num=1):
        results, _collected, _brokens = list(), 0, 0

        # Synchronization and Appending
        sync_idx = self.sync()
        while _collected < num:
            self.buffer = self.buffer[sync_idx + len(PKT_HEADER):]
            sync_idx = self.sync()
            try:
                _sample = ser.restore(self.buffer[:sync_idx])
                results.append(_sample)
                _collected += 1
            except Exception as e:
                _brokens   += 1
            pass

        return _brokens, results
コード例 #7
0
ファイル: Request.py プロジェクト: CapreDiam/MongoTestPython
class Request:
    def __init__(self):
        self.fxcm = FXCMOrder()
        self.fxopen = FXOpenOrder()
        self.sereliazation = Serialization()
        self.redis_connector = redis.StrictRedis(host='localhost', port=6379, db=0)
        self.status = [["New", "To Provider", "Partially Filled", "Filled"], ["New", "To Provider", "Filled"],
                       ["New", "Filled"], ["New", "Partially Filled", "To Provider", "Filled"],
                       ["New", "Partially Filled", "To Provider", "Rejected", "Filled"], ["To Provider"],
                       ["To Provider", "Rejected"], ["To Provider", "Filled"], ["New", "To Provider"],
                       ["New", "To Provider", "Rejected"], ["New", "Partially Filled"], ["New"],
                       ["New", "To Provider", "Partially Filled"]]
        self.mongo_result = []

    def __prepare_data_mongo(self):
        self.id_by_status()
        self.sum_by_fxcm()
        self.sum_by_fxopen()
        self.count_status_by_id_result()
        self.between_dates()

    def __insert_request(self, string_insert):
        operation = "echo '" + string_insert + "' > .q && mongo < .q"
        return commands.getoutput(operation)

    def generation_request_insert(self):
        x = 0
        for i in range(100):
            if i < 50:
                string_insert = 'db.orders.insert( { "provider": ' + '"' + self.fxopen.provider() + '"' + ', "id": ' + '"' + self.fxopen.id() + '"' + ', "type": ' + '"' + self.fxopen.type() + '"' + ', "price": ' + self.fxopen.price() + ', "direction": ' + '"' + self.fxopen.direction() + '"' ', "currency": ' + '"' + self.fxopen.currency() + '"' + ' ,"duration": ' + '"' + self.fxopen.duration() + '"' + ' ,"comment_length": ' + '"' + self.fxopen.comment_length() + '"' + ' ,"comment": ' + '"' + self.fxopen.comment() + '"' + ', "tag_length": ' + '"' + self.fxopen.tag_length() + '"' + ', "tag": ' + '"' + self.fxopen.tag() + '"' + ' ,"magic_number": ' + '"' + self.fxopen.magicalNumber() + '" ,'
            else:
                string_insert = 'db.orders.insert( { "provider": ' + '"' + self.fxcm.provider() + '"' + ', "id": ' + '"' + self.fxcm.id() + '"' + ', "type": ' + '"' + self.fxcm.type() + '"' + ', "price": ' + self.fxcm.price() + ', "direction": ' + '"' + self.fxcm.direction() + '", "currency": ' + '"' + self.fxcm.currency() + '"' + ', "description": ' + '"' + self.fxcm.description() + '" ,'
            a = random.randint(0, 12)
            b = len(self.status[a])
            for j in range(b):
                date = self.fxcm.date_time()
                string_insert_finally = string_insert + ' "date": new Date(' + date + '), "status": "' + self.status[a][
                    j] + '" })'
                json_insert = string_insert[17:len(string_insert)] + ' "date":' + date + ', "status": "' + \
                              self.status[a][j] + '" }'
                self.redis_connector.set("json" + str(x), self.sereliazation.serialization(json_insert))
                self.__insert_request(string_insert_finally)
                string_insert_finally = ''
                x += 1
        self.redis_connector.set("size", x)
        self.__prepare_data_mongo()

    def insert_request(self, string_insert):
        operation = "echo '" + string_insert + "' > .q && mongo < .q"
        commands.getoutput(operation)

    def id_by_status(self):
        result = []
        statuses = ["New", "To Provider", "Partially Filled", "Filled", "Rejected"]
        for i in range(len(statuses)):
            count_statuses = "db.orders.find( { status: " + '"' + statuses[i] + '"' + " } ).count()"
            result.append(((self.__insert_request(count_statuses)).split())[7])
        self.__append_result(result)

    def sum_by_fxcm(self):
        sum_by_fxcm = "db.orders.aggregate( [ { $match : { provider: " + '"' + '*' + '"' + " } }, { " \
                                                                                           "$group: { _id: " + '"' + "$provider" + '"' + ", sum: { $sum: " + '"' + "$price" + '"' + " } } } ] )"
        self.__append_result([round(float(((self.__insert_request(sum_by_fxcm)).split())[13]), 2)])

    def sum_by_fxopen(self):
        sum_by_fxopen = "db.orders.aggregate( [ { $match : { provider: " + '"' + '~' + '"' + " } }, { $group: { _id: " + '"' + "$provider" + '"' + ", " \
                                                                                                                                                   "sum: { $sum: " + '"' + "$price" + '"' + " } } } ] )"
        self.__append_result([round(float(((self.__insert_request(sum_by_fxopen)).split())[13]), 2)])

    def count_status_by_id(self):
        status_by_id = "db.orders.aggregate( { $group: { _id: " + '"' + "$id" + '"' + ", count: { $sum: 1 } } }, { $limit: 3 } )"
        return self.__insert_request(status_by_id)

    def count_status_by_id_result(self):
        result = []
        status_by_id = "db.orders.aggregate( { $group: { _id: " + '"' + "$id" + '"' + ", count: { $sum: 1 } } }, { $limit: 3 } )"
        count_id = self.__insert_request(status_by_id)
        result.append((count_id.split())[13])
        result.append((count_id.split())[21])
        result.append((count_id.split())[29])
        self.__append_result(result)

    def between_dates(self):
        between_dates = "db.orders.aggregate( [ { $match : { date: { $gte: new Date(" + '"' + "2016" + '-' + "1" + '-' + "15 9:12:24.25" \
                        + '"' + "),$lte: new Date(" + '"' + "2016" + '-' + "1" + '-' + "15 9:12:24.725" + '"' + ") } } }, { $group: { _id:" \
                                                                                                                " null, count: { $sum: 1 } } } ] )"
        self.__append_result([((self.__insert_request(between_dates)).split())[13]])


    def __append_result(self, result):
        self.mongo_result.extend(result)
コード例 #8
0
class Request:
    def __init__(self):
        self.fxcm = FXCMOrder()
        self.fxopen = FXOpenOrder()
        self.sereliazation = Serialization()
        self.redis_connector = redis.StrictRedis(host='localhost',
                                                 port=6379,
                                                 db=0)
        self.status = [["New", "To Provider", "Partially Filled", "Filled"],
                       ["New", "To Provider", "Filled"], ["New", "Filled"],
                       ["New", "Partially Filled", "To Provider", "Filled"],
                       [
                           "New", "Partially Filled", "To Provider",
                           "Rejected", "Filled"
                       ], ["To Provider"], ["To Provider", "Rejected"],
                       ["To Provider", "Filled"], ["New", "To Provider"],
                       ["New", "To Provider", "Rejected"],
                       ["New", "Partially Filled"], ["New"],
                       ["New", "To Provider", "Partially Filled"]]
        self.mongo_result = []

    def __prepare_data_mongo(self):
        self.id_by_status()
        self.sum_by_fxcm()
        self.sum_by_fxopen()
        self.count_status_by_id_result()
        self.between_dates()

    def __insert_request(self, string_insert):
        operation = "echo '" + string_insert + "' > .q && mongo < .q"
        return commands.getoutput(operation)

    def generation_request_insert(self):
        x = 0
        for i in range(100):
            if i < 50:
                string_insert = 'db.orders.insert( { "provider": ' + '"' + self.fxopen.provider(
                ) + '"' + ', "id": ' + '"' + self.fxopen.id(
                ) + '"' + ', "type": ' + '"' + self.fxopen.type(
                ) + '"' + ', "price": ' + self.fxopen.price(
                ) + ', "direction": ' + '"' + self.fxopen.direction(
                ) + '"' ', "currency": ' + '"' + self.fxopen.currency(
                ) + '"' + ' ,"duration": ' + '"' + self.fxopen.duration(
                ) + '"' + ' ,"comment_length": ' + '"' + self.fxopen.comment_length(
                ) + '"' + ' ,"comment": ' + '"' + self.fxopen.comment(
                ) + '"' + ', "tag_length": ' + '"' + self.fxopen.tag_length(
                ) + '"' + ', "tag": ' + '"' + self.fxopen.tag(
                ) + '"' + ' ,"magic_number": ' + '"' + self.fxopen.magicalNumber(
                ) + '" ,'
            else:
                string_insert = 'db.orders.insert( { "provider": ' + '"' + self.fxcm.provider(
                ) + '"' + ', "id": ' + '"' + self.fxcm.id(
                ) + '"' + ', "type": ' + '"' + self.fxcm.type(
                ) + '"' + ', "price": ' + self.fxcm.price(
                ) + ', "direction": ' + '"' + self.fxcm.direction(
                ) + '", "currency": ' + '"' + self.fxcm.currency(
                ) + '"' + ', "description": ' + '"' + self.fxcm.description(
                ) + '" ,'
            a = random.randint(0, 12)
            b = len(self.status[a])
            for j in range(b):
                date = self.fxcm.date_time()
                string_insert_finally = string_insert + ' "date": new Date(' + date + '), "status": "' + self.status[
                    a][j] + '" })'
                json_insert = string_insert[17:len(string_insert)] + ' "date":' + date + ', "status": "' + \
                              self.status[a][j] + '" }'
                self.redis_connector.set(
                    "json" + str(x),
                    self.sereliazation.serialization(json_insert))
                self.__insert_request(string_insert_finally)
                string_insert_finally = ''
                x += 1
        self.redis_connector.set("size", x)
        self.__prepare_data_mongo()

    def insert_request(self, string_insert):
        operation = "echo '" + string_insert + "' > .q && mongo < .q"
        commands.getoutput(operation)

    def id_by_status(self):
        result = []
        statuses = [
            "New", "To Provider", "Partially Filled", "Filled", "Rejected"
        ]
        for i in range(len(statuses)):
            count_statuses = "db.orders.find( { status: " + '"' + statuses[
                i] + '"' + " } ).count()"
            result.append(((self.__insert_request(count_statuses)).split())[7])
        self.__append_result(result)

    def sum_by_fxcm(self):
        sum_by_fxcm = "db.orders.aggregate( [ { $match : { provider: " + '"' + '*' + '"' + " } }, { " \
                                                                                           "$group: { _id: " + '"' + "$provider" + '"' + ", sum: { $sum: " + '"' + "$price" + '"' + " } } } ] )"
        self.__append_result([
            round(float(((self.__insert_request(sum_by_fxcm)).split())[13]), 2)
        ])

    def sum_by_fxopen(self):
        sum_by_fxopen = "db.orders.aggregate( [ { $match : { provider: " + '"' + '~' + '"' + " } }, { $group: { _id: " + '"' + "$provider" + '"' + ", " \
                                                                                                                                                   "sum: { $sum: " + '"' + "$price" + '"' + " } } } ] )"
        self.__append_result([
            round(float(((self.__insert_request(sum_by_fxopen)).split())[13]),
                  2)
        ])

    def count_status_by_id(self):
        status_by_id = "db.orders.aggregate( { $group: { _id: " + '"' + "$id" + '"' + ", count: { $sum: 1 } } }, { $limit: 3 } )"
        return self.__insert_request(status_by_id)

    def count_status_by_id_result(self):
        result = []
        status_by_id = "db.orders.aggregate( { $group: { _id: " + '"' + "$id" + '"' + ", count: { $sum: 1 } } }, { $limit: 3 } )"
        count_id = self.__insert_request(status_by_id)
        result.append((count_id.split())[13])
        result.append((count_id.split())[21])
        result.append((count_id.split())[29])
        self.__append_result(result)

    def between_dates(self):
        between_dates = "db.orders.aggregate( [ { $match : { date: { $gte: new Date(" + '"' + "2016" + '-' + "1" + '-' + "15 9:12:24.25" \
                        + '"' + "),$lte: new Date(" + '"' + "2016" + '-' + "1" + '-' + "15 9:12:24.725" + '"' + ") } } }, { $group: { _id:" \
                                                                                                                " null, count: { $sum: 1 } } } ] )"
        self.__append_result([
            ((self.__insert_request(between_dates)).split())[13]
        ])

    def __append_result(self, result):
        self.mongo_result.extend(result)
コード例 #9
0
import json

from Serialization import Serialization as ser
from classes import Person

a = Person("Andrey", 11)

ser.save_to_file(a, "test1.json", True, False)

print(ser.load_object_from_file("test1.json", "classes"))
コード例 #10
0
ファイル: main.py プロジェクト: akhmedovadaryna/Phonebook
from BusinessLogic import Phonebook
from Config import Config
from Controller2 import Controller
from Serialization import Serialization
import Controller as Control

__author__ = 'alexandr'

if __name__ == "__main__":
    conf = Config()
    if conf.get_controller() == '1\n':
        obj = Controller(Phonebook([]), Serialization("phonebook"), conf)
        obj.start()
    elif conf.get_controller() == '0\n':
        Control.main()
コード例 #11
0
class Round(object):

    ##############################################################
    # Function Name: Constructor
    # Purpose: Constructor
    # Parameters:
    #           self
    # Assistance Received: None
    ##############################################################
    def __init__(self):
        self.roundNumber = 1
        self.stockPile = []
        self.layout = []

        self.humanHand = [[], [], []]
        self.computerHand = [[], [], []]
        self.humanCapture = [[], [], []]
        self.computerCapture = [[], [], []]
        self.numComPlayers = 0
        self.numHumPlayers = 0

        #Initalize classes here
        self.s = Serialization()
        self.deck = Deck()
        self.player = Player()
        self.computer1 = Computer()
        self.computer2 = Computer()
        self.computer3 = Computer()
        self.human1 = Human()
        self.human2 = Human()
        self.human3 = Human()

##############################################################
# Function Name: setRound
# Purpose: sets the round
# Parameters:
#           self, int round
# Assistance Received: None
##############################################################

    def setRound(self, round):
        self.roundNumber = round

##############################################################
# Function Name: getRound
# Purpose: returns the round
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def getRound(self):
        return self.round

##############################################################
# Function Name: showCard
# Purpose: shows the hand
# Parameters:
#           self, hand
# Assistance Received: None
##############################################################

    def showCard(self, hand):

        for c in hand:
            c.print()

##############################################################
# Function Name: setComputer
# Purpose: Sets computer information from file
# Parameters:
#           self, score, hand, capture, players
# Assistance Received: None
##############################################################

    def setComputer(self, score, hand, capture, players):
        self.computer1.setScore(score[0])
        self.computer2.setScore(score[1])
        self.computer3.setScore(score[2])
        self.computerHand = hand
        self.computerCapture = capture
        self.numComPlayers = players

##############################################################
# Function Name: setHuman
# Purpose: Sets human information from file
# Parameters:
#           self, int face
# Assistance Received: None
##############################################################

    def setHuman(self, score, hand, capture, players):
        self.human1.setScore(score[0])
        self.human2.setScore(score[1])
        self.human3.setScore(score[2])
        self.humanHand = hand
        self.humanCapture = capture
        self.numHumPlayers = players

##############################################################
# Function Name: setLayout
# Purpose: sets the layout
# Parameters:
#           self, layout
# Assistance Received: None
##############################################################

    def setLayout(self, layout):
        self.layout = layout

##############################################################
# Function Name: setStockPile
# Purpose: sets the stockPile
# Parameters:
#           self, stockPile
# Assistance Received: None
##############################################################

    def setStockPile(self, stockPile):
        self.stockPile = stockPile

##############################################################
# Function Name: setNextPlayer
# Purpose: sets the nextPlayer
# Parameters:
#           self, nextPlayer
# Assistance Received: None
##############################################################

    def setNextPlayer(self, nextPlayer):
        if nextPlayer == "Human" or nextPlayer == "Human 1\n":
            self.human1.setTurn(True)

        elif nextPlayer == "Human 2\n":
            self.human2.setTurn(True)

        elif nextPlayer == "Human 3\n":
            self.human3.setTurn(True)

        elif nextPlayer == "Computer" or nextPlayer == "Computer 1\n":
            self.computer1.setTurn(True)

        elif nextPlayer == "Computer 2\n":
            self.computer2.setTurn(True)

        elif nextPlayer == "Computer 3\n":
            self.computer3.setTurn(True)

##############################################################
# Function Name: draw
# Purpose: draws a card from deck
# Parameters:
#           self, hand
# Assistance Received: None
##############################################################

    def draw(self, hand):
        hand.append(self.stockPile.pop())
        return self

##############################################################
# Function Name: setUpPlayers
# Purpose: Sets the players and decks
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def setUpPlayers(self):
        while (self.numComPlayers + self.numHumPlayers > 4
               or self.numComPlayers + self.numHumPlayers == 0
               or self.numComPlayers + self.numHumPlayers < 2):
            self.numComPlayers = int(
                input("How many how many computer players? (1-3): "))
            self.numHumPlayers = int(input("How many human Players? (1-3): "))

            if (self.numComPlayers + self.numHumPlayers > 4):
                print("Sorry there can only be four total players :(")

        #Get number of decks
        numofDecks = 0
        while (numofDecks == 0 or numofDecks < 2 or numofDecks > 4):
            numofDecks = int(
                input("How many decks would you like to play with? (2-4): "))

            if (numofDecks < 2 or numofDecks > 4):
                print("Sorry please try again")

        #Set up Decks
        self.deck.shuffle()
        self.stockPile = self.deck.getDeck()

        if numofDecks == 2:
            self.deck.shuffle()
            tempDeck1 = self.deck.getDeck()
            self.stockPile = self.stockPile + tempDeck1

        elif numofDecks == 3:
            self.deck.shuffle()
            tempDeck1 = self.deck.getDeck()
            self.deck.shuffle()
            tempDeck2 = self.deck.getDeck()
            self.stockPile = self.stockPile + tempDeck1 + tempDeck2

        elif numofDecks == 4:
            self.deck.shuffle()
            tempDeck1 = self.deck.getDeck()
            self.deck.shuffle()
            tempDeck2 = self.deck.getDeck()
            self.deck.shuffle()
            tempDeck3 = self.deck.getDeck()
            self.stockPile = self.stockPile + tempDeck1 + tempDeck2 + tempDeck3

        print(self.humanHand)

##############################################################
# Function Name: setUpRound
# Purpose: sets up the round
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def setUpRound(self):
        #Distribute the cards to all the hands
        i = 0
        while i < self.numHumPlayers:
            for j in range(5):
                self.draw(self.humanHand[i])
            i += 1

        i = 0
        while i < self.numComPlayers:
            for j in range(5):
                self.draw(self.computerHand[i])
            i += 1

        for j in range(4):
            self.draw(self.layout)

        i = 0
        while i < self.numHumPlayers:
            for j in range(5):
                self.draw(self.humanHand[i])
            i += 1

        i = 0
        while i < self.numComPlayers:
            for j in range(5):
                self.draw(self.computerHand[i])
            i += 1

        for j in range(4):
            self.draw(self.layout)

##############################################################
# Function Name: determinePlayer
# Purpose: determines player based off hand
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def determinePlayer(self):

        human1Count = 0
        human2Count = 0
        human3Count = 0
        computer1Count = 0
        computer2Count = 0
        computer3Count = 0

        j = 0
        highestCard = [
            "K", "Q", "J", "X", "9", "8", "7", "6", "5", "4", "3", "2", "A"
        ]

        # If the round == 1 or the scores are equal
        # Loop through the deck of each player to
        # determine who has a better hand, the better
        # hand goes first

        if (self.roundNumber == 1):

            while True:
                num = 0
                while num < self.numHumPlayers:
                    for humH in self.humanHand[num]:
                        if humH.compareFace(highestCard[j]):
                            if num == 0:
                                human1Count += 1
                            elif num == 1:
                                human2Count += 1
                            elif num == 3:
                                human3Count += 1
                    num += 1

                num = 0
                while num < self.numComPlayers:
                    for comH in self.computerHand[num]:
                        if comH.compareFace(highestCard[j]):
                            if num == 0:
                                computer1Count += 1
                            elif num == 1:
                                computer2Count += 1
                            elif num == 3:
                                computer3Count += 1
                    num += 1

                if (human1Count > computer1Count
                        and human1Count > computer2Count
                        and human1Count > computer3Count
                        and human1Count > human2Count
                        and human1Count > human3Count):

                    print("Human 1has the better hand and will start\n")
                    self.human1.setTurn(True)
                    break

                elif (human2Count > computer1Count
                      and human2Count > computer2Count
                      and human2Count > computer3Count
                      and human2Count > human3Count):

                    print("Human 2 has the better hand and will start\n")
                    self.human2.setTurn(True)
                    break

                elif (human3Count > computer1Count
                      and human3Count > computer2Count
                      and human3Count > computer3Count):

                    print("Human 3 has the better hand and will start\n")
                    self.human3.setTurn(True)
                    break

                elif (computer1Count > computer2Count
                      and computer1Count > computer3Count):

                    print("Computer 1 has the better hand and will start\n")
                    self.computer1.setTurn(True)
                    break

                elif (computer2Count > computer3Count):

                    print("Computer 2 has the better hand and will start\n")
                    self.computer2.setTurn(True)
                    break

                elif (computer3Count > computer2Count):

                    print("Computer 3 has the better hand and will start\n")
                    self.computer3.setTurn(True)
                    break

                if (j == 13):
                    print("All card mathced the round is starting over\n")
                    round = Round()

                j += 1

        elif (self.roundNumber > 1):

            if (self.human1.getScore() > self.computer1.getScore()
                    and self.human1.getScore() > self.computer2.getScore()
                    and self.human1.getScore() > self.computer3.getScore()
                    and self.human1.getScore() > self.human2.getScore()
                    and self.human1.getScore() > self.human3.getScore()):

                self.human1.setTurn(True)
                self.human2.setTurn(False)
                self.human3.setTurn(False)
                self.computer1.setTurn(False)
                self.computer2.setTurn(False)
                self.computer3.setTurn(False)

            elif (self.human2.getScore() > self.computer1.getScore()
                  and self.human2.getScore() > self.computer2.getScore()
                  and self.human2.getScore() > self.computer3.getScore()
                  and self.human2.getScore() > self.human3.getScore()):

                self.human1.setTurn(False)
                self.human2.setTurn(True)
                self.human3.setTurn(False)
                self.computer1.setTurn(False)
                self.computer2.setTurn(False)
                self.computer3.setTurn(False)

            elif (self.human3.getScore() > self.computer1.getScore()
                  and self.human3.getScore() > self.computer2.getScore()
                  and self.human3.getScore() > self.computer3.getScore()):

                self.human1.setTurn(False)
                self.human2.setTurn(False)
                self.human3.setTurn(True)
                self.computer1.setTurn(False)
                self.computer2.setTurn(False)
                self.computer3.setTurn(False)

            elif (self.computer1.getScore() > self.computer2.getScore()
                  and self.computer1.getScore() > self.computer3.getScore()):

                self.human1.setTurn(False)
                self.human2.setTurn(False)
                self.human3.setTurn(False)
                self.computer1.setTurn(True)
                self.computer2.setTurn(False)
                self.computer3.setTurn(False)

            elif (self.computer2.getScore() > self.computer2.getScore()):

                self.human1.setTurn(False)
                self.human2.setTurn(False)
                self.human3.setTurn(False)
                self.computer1.setTurn(False)
                self.computer2.setTurn(True)
                self.computer3.setTurn(False)

            elif (self.computer3.getScore() > self.computer2.getScore()):

                self.human1.setTurn(False)
                self.human2.setTurn(False)
                self.human3.setTurn(False)
                self.computer1.setTurn(False)
                self.computer2.setTurn(False)
                self.computer3.setTurn(True)

##############################################################
# Function Name: nextPlayer
# Purpose: returns the next player
# Parameters:
#           self, hand
# Assistance Received: None
##############################################################

    def nextPlayer(self):

        if self.human1.getIsTurn() == True:
            return "Human 1"

        elif self.human2.getIsTurn() == True:
            return "Human 2"

        elif self.human3.getIsTurn() == True:
            return "Human 3"

        elif self.computer1.getIsTurn() == True:
            return "Computer 1"

        elif self.computer2.getIsTurn() == True:
            return "Computer 2"

        elif self.computer3.getIsTurn() == True:
            return "Computer 3"
##############################################################
# Function Name: display
# Purpose: shows the display
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def display(self):

        print()
        print("---------------------------")

        print("Round:", self.roundNumber)
        print()

        #Computer
        print("Computer 1:")
        print("Score:", self.computer1.getScore())
        print("Hand:", end=" ")
        self.showCard(self.computerHand[0])
        print()
        print("Capture Pile:", end=" ")
        self.showCard(self.computerCapture[0])

        #Human
        print("\n")
        print("Human 1:")
        print("Score:", self.human1.getScore())
        print("Hand:", end=" ")
        self.showCard(self.humanHand[0])
        print()
        print("Capture Pile:", end=" ")
        self.showCard(self.humanCapture[0])
        print("\n")

        #Computer2
        if self.numComPlayers >= 2:
            print("Computer 2:")
            print("Score:", self.computer2.getScore())
            print("Hand:", end=" ")
            self.showCard(self.computerHand[1])
            print()
            print("Capture Pile:", end=" ")
            self.showCard(self.computerCapture[1])

        #Human 2
        if self.numHumPlayers >= 2:
            print("\n")
            print("Human 2:")
            print("Score:", self.human2.getScore())
            print("Hand:", end=" ")
            self.showCard(self.humanHand[1])
            print()
            print("Capture Pile:", end=" ")
            self.showCard(self.humanCapture[1])
            print("\n")

        #Computer 3
        if self.numComPlayers == 3:
            print("Computer 2:")
            print("Score:", self.computer3.getScore())
            print("Hand:", end=" ")
            self.showCard(self.computerHand[2])
            print()
            print("Capture Pile:", end=" ")
            self.showCard(self.computerCapture[2])

        #Human 3
        if self.numHumPlayers == 3:
            print("\n")
            print("Human 3:")
            print("Score:", self.human3.getScore())
            print("Hand:", end=" ")
            self.showCard(self.humanHand[2])
            print()
            print("Capture Pile:", end=" ")
            self.showCard(self.humanCapture[2])
            print("\n")

        #Layout
        print("Layout:", end=" ")
        self.showCard(self.layout)
        print("\n")

        #Stock pile
        print("Stock Pile:", end=" ")
        self.showCard(self.stockPile)

        #Next Player
        print("\n")
        print("Next Player:", end=" ")
        print(self.nextPlayer())
        print("--------\n")
        self.menu()

##############################################################
# Function Name: menu
# Purpose: menu for human
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def menu(self):

        if sum(len(x) for x in self.humanHand) == 0 and sum(
                len(y) for y in self.computerHand) == 0:
            self.nextRound()

        #Check to make sure hand is not empty of current player
        self.checkHand()

        if (self.computer1.getIsTurn() == True):
            self.computerMenu()
            return

        elif (self.computer2.getIsTurn() == True):
            self.computerMenu()
            return

        elif (self.computer3.getIsTurn() == True):
            self.computerMenu()
            return

        print("1. Save the game")
        print("2. Make a move")
        print("3. Ask for help")
        print("4. Quit the game")

        while True:

            selection = int(input("Selection: "))
            if (selection > 0 and selection < 5):
                break

        if selection == 1:
            computerScores = [0, 0, 0]
            humanScores = [0, 0, 0]
            nextPlayer = self.nextPlayer()

            print("Save the game")
            #Computer Scores
            computerScores[0] = self.computer1.getScore()
            if self.numComPlayers >= 2:
                computerScores[1] = self.computer2.getScore()
            if self.numComPlayers == 3:
                computerScores[2] = self.computer3.getScore()

            #Human Scores
            humanScores[0] = self.human1.getScore()
            if self.numHumPlayers >= 2:
                humanScores[1] = self.human2.getScore()
            if self.numHumPlayers == 3:
                humanScores[2] = self.human3.getScore()

            self.s.saveGame(self.roundNumber, computerScores,
                            self.computerHand, self.computerCapture,
                            self.numComPlayers, humanScores, self.humanHand,
                            self.humanCapture, self.numHumPlayers, self.layout,
                            self.stockPile, nextPlayer)
            #Save the Game

        elif selection == 2:

            self.move()

        elif selection == 3:

            if (self.human1.getIsTurn() == True):
                self.player.play(self.stockPile, self.layout,
                                 self.humanHand[0], self.humanCapture[0],
                                 self.computerCapture[0])

            elif (self.human2.getIsTurn() == True):
                self.player.play(self.stockPile, self.layout,
                                 self.humanHand[1], self.humanCapture[1],
                                 self.computerCapture[0])

            elif (self.human3.getIsTurn() == True):
                self.player.play(self.stockPile, self.layout,
                                 self.humanHand[2], self.humanCapture[2],
                                 self.computerCapture[0])
            self.menu()

        elif selection == 4:

            self.endGame()

##############################################################
# Function Name: computerMenu
# Purpose: Menu for computer
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def computerMenu(self):

        print("1. Save Game")
        print("2. Computer Move")
        print("3. Quit Game")

        while True:

            selection = int(input("Selection: "))
            if (selection > 0 and selection < 4):
                break

        if selection == 1:
            computerScores = [0, 0, 0]
            humanScores = [0, 0, 0]
            nextPlayer = self.nextPlayer()

            print("Save the game")
            #Computer Scores
            computerScores[0] = self.computer1.getScore()
            if self.numComPlayers >= 2:
                computerScores[1] = self.computer2.getScore()
            if self.numComPlayers == 3:
                computerScores[2] = self.computer3.getScore()

            #Human Scores
            humanScores[0] = self.human1.getScore()
            if self.numHumPlayers >= 2:
                humanScores[1] = self.human2.getScore()
            if self.numHumPlayers == 3:
                humanScores[2] = self.human3.getScore()

            self.s.saveGame(self.roundNumber, computerScores,
                            self.computerHand, self.computerCapture,
                            self.numComPlayers, humanScores, self.humanHand,
                            self.humanCapture, self.numHumPlayers, self.layout,
                            self.stockPile, nextPlayer)
            print("Save the game")

        elif selection == 2:

            self.move()

        elif selection == 3:

            self.endGame()

##############################################################
# Function Name: switchPlayer
# Purpose: switches current player
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def switchPlayer(self):
        #Order alternates com hum, com, hum
        if (self.computer1.getIsTurn() == True):
            self.computer1.setTurn(False)
            self.human1.setTurn(True)

        elif (self.human1.getIsTurn() == True):
            self.human1.setTurn(False)
            if self.numComPlayers >= 2:
                self.computer2.setTurn(True)
            elif self.numHumPlayers >= 2:
                self.human2.setTurn(True)
            else:
                self.computer1.setTurn(True)

        elif (self.computer2.getIsTurn() == True):
            self.computer2.setTurn(False)
            if self.numHumPlayers >= 2:
                self.human2.setTurn(True)
            elif self.numComPlayers == 3:
                self.computer3.setTurn(True)
            else:
                self.human1.setTurn(True)

        elif (self.human2.getIsTurn() == True):
            self.human2.setTurn(False)
            if self.numComPlayers == 3:
                self.computer3.setTurn(True)
            elif self.numHumPlayers == 3:
                self.human3.setTurn(True)
            else:
                self.computer1.setTurn(True)

        elif (self.computer3.getIsTurn() == True):
            self.computer3.setTurn(False)
            if self.numHumPlayers == 3:
                self.human3.setTurn(True)
            else:
                self.human1.setTurn(True)

        elif (self.human3.getIsTurn() == True):
            self.human3.setTurn(False)
            self.computer1.setTurn(True)

##############################################################
# Function Name: checkHand
# Purpose: switches current player if no cards in hand
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def checkHand(self):

        if (self.computer1.getIsTurn() and len(self.computerHand[0]) == 0):
            print("Hand is empty, moving to next player")
            self.switchPlayer()

        elif (self.computer2.getIsTurn() and len(self.computerHand[1]) == 0):
            print("Hand is empty, moving to next player")
            self.switchPlayer()

        elif (self.computer3.getIsTurn() and len(self.computerHand[2]) == 0):
            print("Hand is empty, moving to next player")
            self.switchPlayer()

        elif (self.human1.getIsTurn() and len(self.humanHand[0]) == 0):
            print("Hand is empty, moving to next player")
            self.switchPlayer()

        elif (self.human2.getIsTurn() and len(self.humanHand[1]) == 0):
            print("Hand is empty, moving to next player")
            self.switchPlayer()

        elif (self.human3.getIsTurn() and len(self.humanHand[2]) == 0):
            print("Hand is empty, moving to next player")
            self.switchPlayer()

##############################################################
# Function Name: move
# Purpose: Makes a move for current player
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def move(self):

        if (self.computer1.getIsTurn() == True):
            self.computer1.play(self.stockPile, self.layout,
                                self.computerHand[0], self.computerCapture[0],
                                self.humanCapture[0])

        elif (self.computer2.getIsTurn() == True):
            self.computer2.play(self.stockPile, self.layout,
                                self.computerHand[1], self.computerCapture[1],
                                self.humanCapture[0])

        elif (self.computer3.getIsTurn() == True):
            self.computer3.play(self.stockPile, self.layout,
                                self.computerHand[2], self.computerCapture[2],
                                self.humanCapture[0])

        elif (self.human1.getIsTurn() == True):
            self.human1.play(self.stockPile, self.layout, self.humanHand[0],
                             self.humanCapture[0])

        elif (self.human2.getIsTurn() == True):
            self.human2.play(self.stockPile, self.layout, self.humanHand[1],
                             self.humanCapture[1])

        elif (self.human3.getIsTurn() == True):
            self.human3.play(self.stockPile, self.layout, self.humanHand[2],
                             self.humanCapture[2])

        self.switchPlayer()
        self.display()

##############################################################
# Function Name: nextRound
# Purpose: starts the next round
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def nextRound(self):
        str = ""
        while (str != "YES" and str != "NO"):
            str = input(
                "The round is over would you like to play another round? (Yes or No): "
            )
            str = str.upper()

        if str == "YES":
            self.computerHand = [[], [], []]
            self.humanHand = [[], [], []]
            self.layout.clear()
            self.stockPile.clear()
            self.humanCapture = [[], [], []]
            self.computerCapture = [[], [], []]

            self.roundNumber += 1
            self.setUpPlayers()
            self.setUpRound()
            self.determinePlayer()
            self.display()

        else:
            self.endGame()

##############################################################
# Function Name: endGame
# Purpose: ends the game
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def endGame(self):

        if (self.human1.getScore() == self.computer1.getScore()
                and self.human1.getScore() == self.computer2.getScore()
                and self.human1.getScore() == self.computer3.getScore()
                and self.human1.getScore() == self.human2.getScore()
                and self.human1.getScore() == self.human3.getScore()):

            print("TIE GAME")

        elif (self.human1.getScore() > self.computer1.getScore()
              and self.human1.getScore() > self.computer2.getScore()
              and self.human1.getScore() > self.computer3.getScore()
              and self.human1.getScore() > self.human2.getScore()
              and self.human1.getScore() > self.human3.getScore()):

            print("Congrats Human 1 you won!")

        elif (self.human2.getScore() > self.computer1.getScore()
              and self.human2.getScore() > self.computer2.getScore()
              and self.human2.getScore() > self.computer3.getScore()
              and self.human2.getScore() > self.human3.getScore()):

            print("Congrats Human 2 you won!")

        elif (self.human3.getScore() > self.computer1.getScore()
              and self.human3.getScore() > self.computer2.getScore()
              and self.human3.getScore() > self.computer3.getScore()):

            print("Congrats Human 3 you won!")

        elif (self.computer1.getScore() > self.computer2.getScore()
              and self.computer1.getScore() > self.computer3.getScore()):

            print("Computer 1 has won")

        elif (self.computer2.getScore() > self.computer2.getScore()):

            print("Computer 2 has won")

        elif (self.computer3.getScore() > self.computer2.getScore()):

            print("Computer 3 has won")
コード例 #12
0
ファイル: ChatServer.py プロジェクト: codeTony22/PyChat
class Server:
    SERVER_CONFIG = {"MAX_CONNECTIONS": 15}

    HELP_MESSAGE = """\n> The list of commands available are:

/help                   - Show the instructions
/join [channel_name]    - To create or switch to a channel.
/quit                   - Exits the program.
/list                   - Lists all available channels.\n\n""".encode('utf8')

    def __init__(self,
                 host=socket.gethostbyname('localhost'),
                 port=50000,
                 allowReuseAddress=True):
        self.address = (host, port)
        self.channels = {}  # Channel Name -> Channel
        self.serializer = Serialization()
        self.channels_client_map = {}  # Client Name -> Channel Name
        try:
            self.serverSocket = socket.socket(socket.AF_INET,
                                              socket.SOCK_STREAM)
        except socket.error as errorMessage:
            sys.stderr.write("Failed to initialize the server. Error - %s\n",
                             str(errorMessage))
            raise

        if allowReuseAddress:
            self.serverSocket.setsockopt(socket.SOL_SOCKET,
                                         socket.SO_REUSEADDR, 1)

        try:
            self.serverSocket.bind(self.address)
        except socket.error as errorMessage:
            sys.stderr.write(
                'Failed to bind to ' + self.address + '. Error - %s\n',
                str(errorMessage))
            raise

    def listen_thread(
            self,
            defaultGreeting="\n> Welcome to our chat app!!! What is your name?\n"
    ):
        while True:
            print("Waiting for a client to establish a connection\n")
            #Accept connection, returns tuple
            clientSocket, clientAddress = self.serverSocket.accept()

            client = Client(clientSocket)

            # Authorize user
            client = self.serializer.authorize_client(client)

            # client was returned with None
            while client is None:
                # Repeat until the is an authenticated or new client
                client = self.serializer.authorize_client(client)

            print(client.get_clientName())
            print(client.get_clientPassword())
            print(client.get_levels())
            print(str(client.get_status()))

            #Stablish connection
            print("Connection established with IP address {0} and port {1}\n".
                  format(clientAddress[0], clientAddress[1]))

            clientThread = threading.Thread(target=self.client_thread,
                                            args=(client, ))
            clientThread.start()

    def start_listening(self):
        self.serverSocket.listen(Server.SERVER_CONFIG["MAX_CONNECTIONS"])
        listenerThread = threading.Thread(target=self.listen_thread)
        listenerThread.start()
        listenerThread.join()

    def client_thread(self, client, size=4096):

        welcomeMessage = '> Welcome %s, type /help for a list of helpful commands.\n\n' % client.get_clientName(
        )
        client.send_message(welcomeMessage)

        while True:
            chatMessage = client.receive_message(size)

            if not chatMessage:
                break

            if '/quit' in chatMessage:
                self.quit(client.get_socket(), client.get_clientName())
                break
            elif '/list' in chatMessage:
                self.list_all_channels(client.get_clientSocket())
            elif '/help' in chatMessage:
                self.help(client.get_clientSocket())
            elif '/join' in chatMessage:
                self.join(chatMessage, client)
            elif '/away' in chatMessage:
                self.away(client, chatMessage)
            elif '/info' in chatMessage:
                self.info(client.get_clientSocket())
            elif '/ison' in chatMessage:
                query = self.ison(chatMessage)
                if query == []:
                    client.send_message(
                        "\n>None of the nickname/s are connected in the network\n"
                    )
                else:
                    for name in query:
                        client.send_message("\n>" + name + " is connected.\n")
            elif '/kick' in chatMessage:
                self.kick(client, chatMessage)
            elif '/kill' in chatMessage:
                self.kill(client, chatMessage)
            elif '/privmsg' in chatMessage:
                self.privmsg(client, chatMessage)
            elif '/invite' in chatMessage:
                self.invite(client, chatMessage)
            elif '/mode' in chatMessage:
                self.mode(client, chatMessage)
            elif '/nick' in chatMessage:
                self.nick()
            else:
                self.send_message(client.get_clientSocket(),
                                  chatMessage + '\n', client.get_clientName())
        client.get_socket().close()

    def privmsg(self, client, chatMessage):
        args_list = chatMessage.split()
        msg_target = args_list[1]
        message = args_list[2]

        self.channels[self.channels_client_map[msg_target]].broadcast_message(
            message, msg_target)

    def mode(self, client, chatMessage):
        args_list = chatMessage.split()

        if len(args_list) >= 3:
            flag = args_list[2]
            #mode change user flag -u must be set
            if flag == "-u":
                pass
            elif flag == "-c":
                pass

    def get_all_channelName(self):
        result = []
        for channel in self.channels:
            result.append(channel)

        return result

    def invite(self, client, chatMessage):
        arg_list = chatMessage.split()

        if len(arg_list) >= 2:
            msgtarget = arg_list[1]
            channel = arg_list[2]
            if channel in self.channels:
                if channel.get_mode() == True:
                    if client.get_levels() == "channelop" or client.get_levels(
                    ) == "admin":
                        self.join(msgtarget)
                    else:
                        client.send_message(
                            "\n>Invite Incomplete. Not a channel operator.\n")
                else:
                    if client.get_clientName() in self.channels_client_map:
                        target_client = self.find_client_target(msgtarget)
                        target_client.send_message(
                            "\n>" + client.get_clientName() +
                            " has invited you to a channel. Leaving your channel.\n"
                        )
                        self.join(target_client)

            else:
                target_client_object = self.find_client_target(msgtarget)
                self.join_invite(target_client_object, channel)
                self.join_invite(client, channel)
        else:
            client.send_message(
                "\n>Command Usage Error.\n\n>/invite msg_target channel \n")

    def join_invite(self, client, channelName):
        isInSameRoom = False

        if client.get_clientName() in self.channels_client_map:
            if channelName in self.channels_client_map[
                    client.client.get_clientName()]:
                # User already on that channel
                client.send_message("\n> You are already in channel: " +
                                    channelName)
                isInSameRoom = True
            elif not channelName in self.channels_client_map[
                    client.client.get_clientName(
                    )] and channelName in self.channels:
                self.channels[channelName].clients[
                    client.get_clientName()] = client
                self.channels_client_map[client.get_clientName()].append(
                    channelName)

        if not isInSameRoom:
            if not channelName in self.channels:
                newChannel = Channel.Channel(channelName)
                self.channels[channelName] = newChannel
            self.channels[channelName].clients[
                client.get_clientName()] = client
            self.channels[channelName].welcome_client(client.get_clientName())
            self.channels_client_map[client.get_clientName()].append(
                channelName)

    '''
    Find_client_target is a function that find the msgtarget if the user is connected. 
    If given the clientName. returns None if client was not found.
    '''

    def find_client_target(self, msgtarget):
        if msgtarget in self.channels_client_map:
            return self.channels[self.channels_client_map[msgtarget]]
        return None

    def kick(self, client, chatMessage):
        if client.get_levels() == "channelop" or client.get_levels(
        ) == "admin":
            args = chatMessage[5:]
            list_args = args.split()

            channelName = list_args[0]
            clientName = list_args[1]
            message = list_args[2]
            if clientName in self.channels[channelName].clients:
                del self.channels[channelName].clients[clientName]
                client.send_message(message)

    def kill(self, client, chatMessage):
        if client.get_levels() == "channelop" or client.get_levels(
        ) == "admin":
            args_list = chatMessage.split()
            clientName = args_list[1]
            message = args_list[2]

            if clientName in self.channels_client_map:
                self.channels[self.channels_client_map[clientName]].clients[
                    clientName].send_message(message)
                del self.channels[
                    self.channels_client_map[clientName]].clients[clientName]
                del self.channels_client_map[clientName]

    def ison(self, chatMessage):
        nicknames = chatMessage[6:]
        nicknames_list = nicknames.split()

        query = []

        for name in nicknames_list:
            if name in self.channels_client_map:
                query.append(name)

        return query

    """
    Information of the server. Program only uses one 
    server. Add information about the server. 
    """

    def info(self, clientSocket):
        self.serializer.read_ServerConfigInfo(clientSocket)

    def away(self, client, chatMessage):
        PRIVAWAAYMSG = chatMessage[5:]

        if PRIVAWAAYMSG is "":
            client.set_away(False)

        if client.get_away() == False and PRIVAWAAYMSG:
            client.set_away(True)
            client.set_awayMessage(PRIVAWAAYMSG)

    #Kill the server, any user can
    #TO DO - FIX
    def die(self, clientSocket):
        self.server_shutdown()

    def quit(self, clientSocket, clientName):
        clientSocket.sendall('/quit'.encode('utf8'))
        self.remove_client(clientName)

    def list_all_channels(self, clientSocket):
        if len(self.channels) == 0:
            chatMessage = "\n> No rooms available. Create your own by typing /join [channel_name]\n"
            clientSocket.sendall(chatMessage.encode('utf8'))
        else:
            chatMessage = '\n\n> Current channels available are: \n'
            for channel in self.channels:
                chatMessage += "    \n" + channel + ": " + str(
                    len(self.channels[channel].clients)) + " user(s)"
            chatMessage += "\n"
            clientSocket.sendall(chatMessage.encode('utf8'))

    def help(self, socket):
        socket.sendall(Server.HELP_MESSAGE)

    def join(self, chatMessage, client):
        isInSameRoom = False

        if len(chatMessage.split()) >= 2:
            channelName = chatMessage.split()[1]

            if client.get_clientName() in self.channels_client_map:
                if channelName in self.channels_client_map[
                        client.client.get_clientName()]:
                    # User already on that channel
                    client.send_message("\n> You are already in channel: " +
                                        channelName)
                    isInSameRoom = True
                elif not channelName in self.channels_client_map[
                        client.client.get_clientName(
                        )] and channelName in self.channels:
                    self.channels[channelName].clients[
                        client.get_clientName()] = client
                    self.channels_client_map[client.get_clientName()].append(
                        channelName)

            if not isInSameRoom:
                if not channelName in self.channels:
                    newChannel = Channel.Channel(channelName)
                    self.channels[channelName] = newChannel
                self.channels[channelName].clients[
                    client.get_clientName()] = client
                self.channels[channelName].welcome_client(
                    client.get_clientName())
                self.channels_client_map[client.get_clientName()].append(
                    channelName)
        else:
            self.help(client.get_clientSocket())

    def send_message(self, clientSocket, chatMessage, clientName):
        if clientName in self.channels_client_map:
            self.channels[
                self.channels_client_map[clientName]].broadcast_message(
                    chatMessage, clientName + ": ")
        else:
            chatMessage = """\n> You are currently not in any channels:

Use /list to see a list of available channels.
Use /join [channel name] to join a channels.\n\n""".encode('utf8')

            clientSocket.sendall(chatMessage)

    def remove_client(self, clientName):
        if clientName in self.channels_client_map:
            self.channels[self.channels_client_map[
                clientName]].remove_client_from_channel(clientName)
            del self.channels_client_map[clientName]
        print("Client: " + clientName + " has left\n")

    def server_shutdown(self):
        print("Shutting down chat server.\n")
        self.serverSocket.shutdown(socket.SHUT_RDWR)
        self.serverSocket.close()
コード例 #13
0
 def load(self, compress: bool):
     ids_filename = 'Index/ids.mir'
     self.id_manager = Serialization.load_ids(ids_filename)
     index_filename = 'Index/index.mir'
     self.index_db = Serialization.read_from_file(index_filename, compress)
コード例 #14
0
 def save(self, compress: bool):
     ids_filename = 'Index/ids.mir'
     Serialization.write_ids(self.id_manager, ids_filename)
     index_filename = 'Index/index.mir'
     Serialization.write_to_file(self.index_db, index_filename, compress)
コード例 #15
0
class Game(object):

    ##############################################################
    # Function Name: Constructor
    # Purpose: Constructor
    # Parameters:
    #           self
    # Assistance Received: None
    ##############################################################
    def __init__(self):
        self.round = Round()
        self.s = Serialization()

##############################################################
# Function Name: startGame
# Purpose: starts the game
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def startGame(self):
        choice = 0
        while choice < 1 or choice > 2 or choice == 0:
            print("(1) Start new Game")
            print("(2) Load Game")
            choice = int(input("Selection: "))

            if choice < 1 or choice > 2:
                print("Please enter a valid input")

        if choice == 1:
            self.round.setUpPlayers()
            self.round.setUpRound()
            self.round.determinePlayer()
            self.round.display()

        elif choice == 2:
            self.resumeGame()
            self.round.display()

##############################################################
# Function Name: resumeGame
# Purpose: loads game from file
# Parameters:
#           self
# Assistance Received: None
##############################################################

    def resumeGame(self):
        comScore = [0, 0, 0]
        humScore = [0, 0, 0]
        humHand = [[], [], []]
        humCapture = [[], [], []]
        computerHand = [[], [], []]
        computerCapture = [[], [], []]
        layout = []
        stockPile = []
        numComPlayers = 0
        numHumanPlayers = 0
        nextPlayer = ""
        fileName = input(
            "What is the name of the file you would like to resume: ")
        self.s.setFileName(fileName)

        #Round
        roundNum = self.s.getRound()
        self.round.setRound(roundNum)

        #Computer and Human
        comScore, computerHand, computerCapture, numComPlayers = self.s.getComputer(
        )
        self.round.setComputer(comScore, computerHand, computerCapture,
                               numComPlayers)
        humScore, humHand, humCapture, numHumanPlayers = self.s.getHuman()
        self.round.setHuman(humScore, humHand, humCapture, numHumanPlayers)

        #Layout and Stock Pile
        layout = self.s.getLayout()
        self.round.setLayout(layout)
        stockPile = self.s.getStockPile()
        self.round.setStockPile(stockPile)

        #Next Player
        nextPlayer = self.s.getNextPlayer()
        self.round.setNextPlayer(nextPlayer)
コード例 #16
0
 def __init__(self):
     self.round = Round()
     self.s = Serialization()
コード例 #17
0
            if 'm²' in itemContent:
                area = itemContent.split(' ')[0]

            if itemName == 'Liczba pokoi':
                rooms = itemContent

        # Description
        description = bsFlat.find('div', id='textContent').get_text().strip()
        flat = Flat(title, location, 'OLX', buildingType, rooms, str(price), area, description, linkString)

    # Dodawane są tylko te eferty, które spełniają kryteria odnośnie ceny
    if float(flat.price) <= priceMax:
        flatsList.append(flat)

# Tworzenie pliku csv z danymi
Serialization.serialize_to_csv(flatsList)
print("GENERATED .csv FILE")


# Tworzenie pliku html z danymi
Serialization.serialize_to_html(flatsList)
print("GENERATED .html FILE")

# Wysyłanie e-mail
send_email()