Example #1
0
class Train:
    def __init__(self, maxVel, maxAcceleration, lineName1, lineName2,
                 relation_dict, line_dict, way_dict, node_dict, idObject):

        self.line1 = lineName1
        self.line2 = lineName2
        self.line1Bool = True

        self.way_list = line_dict[
            self.line1]  #make sure this is a list of ways by id's
        wayId = self.way_list[0]
        way = way_dict[wayId]
        self.node_list = way['nodes']

        self.stop_list = line.getStopListFromLineName(relation_dict, way_dict,
                                                      self.line1)

        self.traverseForward = True

        self.reachedEnd = False
        self.wayIndex = 0
        self.nodeIndex = 1
        self.stopIndex = 0

        self.send = True
        self.remove = False
        self.currentWay = self.way_list[self.wayIndex]
        self.currentStop = self.stop_list[self.stopIndex]
        self.nextStop = self.stop_list[self.stopIndex]
        self.currentNode = self.node_list[self.nodeIndex - 1]
        self.nextNode = self.node_list[self.nodeIndex]
        nodeCurrent = node_dict[self.currentNode]
        nodeNext = node_dict[self.nextNode]
        self.acceleration = 0
        self.maxVel = maxVel
        self.maxAcceleration = maxAcceleration

        vel = Vector(nodeNext['x'], nodeNext['y']).subtract(
            Vector(nodeCurrent['x'], nodeCurrent['y']))
        if vel.length() != 0:
            vel.normalize()

        self.directionVect = vel
        self.cooldown = nodeCurrent['delay']
        if self.maxVel == 50:
            self.cooldown = 10

        self.currentTime = time.time()
        self.idObject = idObject
        self.particle = Particle(Vector(nodeCurrent['x'], nodeCurrent['y']),
                                 Vector(0, 0), self.idObject)

    def update(self, nodeTraffic_dict, relation_dict, line_dict, way_dict,
               node_dict, simulation_speed):

        if not self.reachedEnd:
            if self.cooldown > 0:  #wait for cooldown
                self.cooldown -= ((time.time() - self.currentTime) *
                                  simulation_speed)
                if self.cooldown == 0:
                    stop = nodeTraffic_dict[self.currentStop]
                    # self.remove=True
                    if self.idObject in stop:
                        stop.pop(self.idObject)

            elif self.cooldown < 0:
                self.cooldown = 0
                stop = nodeTraffic_dict[self.currentStop]
                # self.remove=True
                if self.idObject in stop:
                    stop.pop(self.idObject)

            else:
                self.updateVelocity(nodeTraffic_dict, relation_dict, line_dict,
                                    way_dict, node_dict, simulation_speed)
        else:
            self.particle.vel.multiply(0)

        self.particle.update(simulation_speed)
        self.currentTime = time.time()

    def updateVelocity(self, nodeTraffic_dict, relation_dict, line_dict,
                       way_dict, node_dict, simulation_speed):

        # check for condition of index incrementation
        self.checkIfReachedNode(way_dict, node_dict)

        currentVel = self.particle.vel.copy().length()
        nextNode = node_dict[self.nextNode]
        nextStop = node_dict[self.nextStop]
        if (Vector(nextNode['x'], nextNode['y']).subtract(
                self.particle.pos)).dot(self.particle.vel) < 0:
            currentVel *= -1
        if currentVel < nextNode['maxVel'] or nextNode == nextStop:
            self.acceleration = self.maxAcceleration

        elif currentVel > nextNode['maxVel'] and nextNode != nextStop:
            self.acceleration = -self.maxAcceleration

        else:
            self.acceleration = 0

        self.checkDecelForStop(node_dict)

        #second distance check with trains in the same stop location of the dictionary:
        stop = nodeTraffic_dict[self.nextStop]
        for id in stop:
            if id != self.idObject:
                particle = stop[id]
                velocityA = self.particle.vel.copy()
                velocityB = particle.vel.copy()
                if velocityA.dot(velocityB) > 0:
                    distanceToStop = self.particle.pos.copy().distanceTo(
                        particle.pos)
                    distanceToDecel = self.particle.vel.copy().multiply(
                        (self.particle.vel.length() /
                         self.maxAcceleration)).length()

                    if distanceToStop - 100 < distanceToDecel and self.particle.vel.copy(
                    ).dot(particle.pos.copy().subtract(self.particle.pos)) > 0:
                        self.acceleration = -self.maxAcceleration
                        if self.particle.vel.length() < 1:
                            self.acceleration = 0
                            self.particle.vel.multiply(0)

        #update velocity in relation to acceleration
        if self.currentNode == self.nextNode:
            self.incrementIndexes(way_dict, node_dict)
        if self.directionVect.length() != 0 and self.acceleration != 0:
            velToAdd = self.directionVect.copy().multiply(self.acceleration)
            velToAdd.multiply(
                (time.time() - self.currentTime) * simulation_speed)
            self.particle.vel.add(velToAdd)

        #check if reached stop
        self.checkIfReachedStop(nodeTraffic_dict, relation_dict, line_dict,
                                way_dict, node_dict)

    def incrementIndexes(self, way_dict, node_dict):
        self.currentNode = self.nextNode
        if (self.nodeIndex < len(self.node_list) - 1 and self.traverseForward
            ) or (self.nodeIndex > 0 and not self.traverseForward):  #next node
            if self.traverseForward:

                self.nodeIndex += 1
            else:
                self.nodeIndex -= 1
            self.nextNode = self.node_list[self.nodeIndex]
        elif (self.nodeIndex >= len(self.node_list) - 1
              and self.traverseForward) or (self.nodeIndex <= 0
                                            and not self.traverseForward):
            if self.wayIndex >= len(self.way_list) - 1:  #reached end
                self.reachedEnd = True
                self.nodeIndex = 1
                self.wayIndex = 0
            else:  #next way
                self.wayIndex += 1
                self.nodeIndex = 0
                self.currentWay = self.way_list[self.wayIndex]
                way = way_dict[self.currentWay]
                self.node_list = way['nodes']
                self.nextNode = self.node_list[self.nodeIndex]
                currentNode = node_dict[self.currentNode]
                nextNode = node_dict[self.nextNode]
                nodeId = self.node_list[self.nodeIndex + 1]
                nextNextNode = node_dict[nodeId]
                if self.currentNode == self.nextNode:
                    self.traverseForward = True
                elif Vector(currentNode['x'], currentNode['y']).distanceTo(
                        Vector(nextNode['x'], nextNode['y'])) < Vector(
                            currentNode['x'], currentNode['y']).distanceTo(
                                Vector(nextNextNode['x'], nextNextNode['y'])):
                    self.traverseForward = True
                else:
                    self.traverseForward = False
                    self.nodeIndex = len(self.node_list) - 1
                    self.nextNode = self.node_list[self.nodeIndex]

    def getNodeFromId(self, node_dict, nodeId):
        return node_dict[nodeId]

    def getPosVectorFromNode(self, node_dict, nodeId):
        node = node_dict[nodeId]
        return Vector(node['x'], node['y'])

    def checkIfReachedNode(self, way_dict, node_dict):
        if self.particle.vel.getX() != 0 or self.particle.vel.getY() != 0:
            if self.particle.vel.copy().dot(
                    self.getPosVectorFromNode(node_dict,
                                              self.nextNode).subtract(
                                                  self.particle.pos)) < 0:
                # if traveling away from node and close to it (reached it)

                # if doCirclesIntersect(self.particle.pos,2,self.getPosVectorFromNode(node_dict,self.nextNode),2):
                self.incrementIndexes(way_dict, node_dict)

                self.cooldown = node_dict[self.currentNode]['delay']

                vel = self.getPosVectorFromNode(
                    node_dict, self.nextNode).subtract(
                        self.getPosVectorFromNode(node_dict, self.currentNode))
                if vel.length() != 0:
                    vel.normalize()
                    self.directionVect = vel.copy()
                    vel.multiply(self.particle.vel.length())

                    self.particle.vel = vel.copy()
                    self.particle.pos = self.getPosVectorFromNode(
                        node_dict, self.currentNode)
        elif self.particle.pos == self.getPosVectorFromNode(
                node_dict, self.nextNode):
            self.incrementIndexes(way_dict, node_dict)

            self.cooldown = node_dict[self.currentNode]['delay']

            vel = self.getPosVectorFromNode(node_dict, self.nextNode).subtract(
                self.getPosVectorFromNode(node_dict, self.currentNode))
            if vel.length() != 0:
                vel.normalize()
                self.directionVect = vel.copy()
                vel.multiply(self.particle.vel.length())

                self.particle.vel = vel.copy()
                self.particle.pos = self.getPosVectorFromNode(
                    node_dict, self.currentNode)

    def checkDecelForStop(self, node_dict):
        nextStop = node_dict[self.nextStop]
        distanceToStop = self.particle.pos.copy().distanceTo(
            Vector(nextStop['x'], nextStop['y']))
        distanceToDecel = self.particle.vel.copy().multiply(
            (self.particle.vel.length() / self.maxAcceleration)).length()

        if distanceToStop < distanceToDecel:
            self.acceleration = -self.maxAcceleration

    def checkIfReachedStop(self, nodeTraffic_dict, relation_dict, line_dict,
                           way_dict, node_dict):
        nextStop = node_dict[self.nextStop]
        pos = Vector(nextStop['x'], nextStop['y'])
        if self.currentNode == self.nextStop or (
                self.particle.pos.copy().distanceTo(pos) < 300 and
            (pos.copy().subtract(self.particle.pos)).dot(self.particle.vel) < 0
        ):
            self.stopIndex += 1
            self.send = True
            self.currentStop = self.nextStop
            # if in current remove, add yourself to

            if self.stopIndex < len(self.stop_list):
                self.nextStop = self.stop_list[self.stopIndex]
                nextStopDic = nodeTraffic_dict[self.nextStop]
                nextStopDic.update({self.idObject: self.particle})
            elif self.nextStop == self.stop_list[len(self.stop_list) - 1]:
                self.reachedEnd = True
                if self.line1Bool:
                    self.setLine(relation_dict, line_dict, way_dict, node_dict,
                                 self.line2)
                    self.line1Bool = False
                else:
                    self.setLine(relation_dict, line_dict, way_dict, node_dict,
                                 self.line1)
                    self.line1Bool = True
            self.particle.vel.multiply(0)

    def setLine(self, relation_dict, line_dict, way_dict, node_dict,
                line_name):
        self.way_list = line_dict[
            line_name]  # make sure this is a list of ways by id's
        wayId = self.way_list[0]
        way = way_dict[wayId]
        self.node_list = way['nodes']

        self.stop_list = line.getStopListFromLineName(relation_dict, way_dict,
                                                      line_name)
        self.reachedEnd = False

        self.wayIndex = 0
        self.nodeIndex = 1
        self.stopIndex = 0

        self.currentWay = self.way_list[self.wayIndex]
        self.currentStop = self.stop_list[self.stopIndex]
        self.nextStop = self.stop_list[self.stopIndex]
        self.currentNode = self.node_list[self.nodeIndex - 1]
        self.nextNode = self.node_list[self.nodeIndex]
        nodeCurrent = node_dict[self.currentNode]
        nodeNext = node_dict[self.nextNode]
        self.acceleration = 0

        vel = Vector(nodeNext['x'], nodeNext['y']).subtract(
            Vector(nodeCurrent['x'], nodeCurrent['y']))
        if vel.length() != 0:
            vel.normalize()
        self.directionVect = vel
        self.cooldown = nodeCurrent['delay']
        self.currentTime = time.time()

    def checkVel(self):
        pass

    def encode(self, node_dict):
        dict = {}
        a = 0
        for id in self.stop_list:

            stop = node_dict[id]
            dict.update({stop['name']: a})
            a += 1
        data = {
            'id': str(self.idObject),
            'pos': {
                'x': self.particle.pos.getX(),
                'y': self.particle.pos.getY()
            },
            'stop_dict': dict,
            'stop_index': self.stopIndex,
            'stop': self.currentStop,
        }

        return data
Example #2
0
class Player:
    def __init__(self, pos, vel, nextPosTime, nextPos, maxVel, angle, radius,
                 spriteKey, spriteDictionary, spriteFps, idObject, hasFired,
                 clickPosition, spriteState, numRows, numColumns, startRow,
                 startColumn, endRow, endColumn):
        # id's
        self.remove = False
        self.idClass = 3
        self.idObject = idObject

        # vectors
        self.clickPosition = clickPosition
        # Sprite Attributes
        self.spriteState = spriteState
        self.currentTime = 0
        self.hasFired = hasFired

        self.totalLife = 6000
        self.life = 6000
        self.range = 600
        self.melee = 600  #OPTIONAL,NOT IMPLEMENTED (REQUIRES SPRITE STATES AND MORE TIME)
        self.magic = 600
        self.weapon = 1
        # sub class
        self.particle = Particle(True, pos, vel, nextPosTime, nextPos, maxVel,
                                 0, angle, radius, spriteKey, spriteDictionary,
                                 spriteFps, False, False, self.idObject,
                                 numRows, numColumns, startRow, startColumn,
                                 endRow, endColumn)

    def recieve(self, hasFired, clickPosition, nextPos, nextPosTime, maxVel,
                maxRange, angle, updateSprite, spriteKey, fps, numRows,
                numColumns, startRow, startColumn, endRow, endColumn, radius,
                spriteDictionary, life, range, melee, magic):

        self.life = life
        self.melee = melee
        self.range = range
        self.magic = magic
        self.hasFired = hasFired
        self.clickPosition = clickPosition
        self.particle.recieve(nextPos, nextPosTime, maxVel, maxRange, angle,
                              updateSprite, spriteKey, fps, numRows,
                              numColumns, startRow, startColumn, endRow,
                              endColumn, radius, spriteDictionary)

    def update(self):
        self.particle.update()
        self.setCorrectSpriteState()
        self.currentTime = time.time()

    def draw(self, canvas, cam):
        self.particle.draw(canvas, cam)

    def move(self, pos):
        self.particle.move(pos)

    def setCorrectSpriteState(self):
        if self.spriteState == 0:
            self.setCorrectAnimation(1)
        # CORRECT SPRITE ROW AND UPDATE FPS
        if self.hasFired and self.particle.spriteSheet.hasLooped:
            self.hasFired = False
            self.setCorrectAnimation(1)

        if self.particle.vel.getX() == 0 and self.particle.vel.getY(
        ) == 0 and not self.hasFired:
            self.particle.spriteSheet.currentColumn = 1

    def setCorrectAnimation(self, action):
        if action == 1:
            self.particle.spriteSheet.fps = 20
        if action == 2:
            self.particle.spriteSheet.fps = 30
        if action == 3:
            self.particle.spriteSheet.fps = 5
        x, y = self.particle.pos.copy().distanceToVector(self.clickPosition)
        if y < 0:
            if action == 2:
                self.setSpriteState(6)
            elif action == 3:
                self.setSpriteState(11)
            else:
                self.setSpriteState(3)

        if y > 0:
            if action == 2:
                self.setSpriteState(8)
            elif action == 3:
                self.setSpriteState(9)
            else:
                self.setSpriteState(1)

        if y != 0:
            if (x + y) / y > 2 and y < 0:
                if action == 2:
                    self.setSpriteState(5)
                elif action == 3:
                    self.setSpriteState(12)
                else:
                    self.setSpriteState(4)

            if (x + y) / y < 0 and y < 0:
                if action == 2:
                    self.setSpriteState(7)
                elif action == 3:
                    self.setSpriteState(10)

                else:
                    self.setSpriteState(2)

    def walkUp(self):
        self.particle.spriteSheet.setRow(21, 13, 9, 1, 9, 9)

    def walkLeft(self):
        self.particle.spriteSheet.setRow(21, 13, 10, 1, 10, 9)

    def walkDown(self):
        self.particle.spriteSheet.setRow(21, 13, 11, 1, 11, 9)

    def walkRight(self):
        self.particle.spriteSheet.setRow(21, 13, 12, 1, 12, 9)

    def fireRight(self):
        self.particle.spriteSheet.setRow(21, 13, 20, 1, 20, 13)

    def fireDown(self):
        self.particle.spriteSheet.setRow(21, 13, 19, 1, 19, 13)

    def fireLeft(self):
        self.particle.spriteSheet.setRow(21, 13, 18, 1, 18, 13)

    def fireUp(self):
        self.particle.spriteSheet.setRow(21, 13, 17, 1, 17, 13)

    def magicUp(self):
        self.particle.spriteSheet.setRow(21, 13, 1, 1, 1, 7)

    def magicRight(self):
        self.particle.spriteSheet.setRow(21, 13, 4, 1, 4, 7)

    def magicDown(self):
        self.particle.spriteSheet.setRow(21, 13, 3, 1, 3, 7)

    def magicLeft(self):
        self.particle.spriteSheet.setRow(21, 13, 2, 1, 2, 7)

    def setSpriteState(self, id):
        self.spriteState = id
        self.particle.spriteSheet.resetLoop()
        if id == 1:
            self.walkUp()
        elif id == 2:
            self.walkLeft()
        elif id == 3:
            self.walkDown()
        elif id == 4:
            self.walkRight()
        elif id == 5:
            self.fireRight()
        elif id == 6:
            self.fireDown()
        elif id == 7:
            self.fireLeft()
        elif id == 8:
            self.fireUp()
        elif id == 9:
            self.magicUp()
        elif id == 10:
            self.magicLeft()
        elif id == 11:
            self.magicDown()
        elif id == 12:
            self.magicRight()

    def turn(self, angle):
        self.particle.angle += angle

    def encode(self):

        data = {
            'spriteState': self.spriteState,
            'clickPosition': {
                'x': self.clickPosition.x,
                'y': self.clickPosition.y
            },
            'hasFired': self.hasFired,
            'idObject': self.idObject,
            'idClass': self.idClass,
            'pos': {
                'x': self.particle.pos.x,
                'y': self.particle.pos.y
            },
            'vel': {
                'x': self.particle.vel.x,
                'y': self.particle.vel.y
            },
            'maxVel': self.particle.maxVel,
            'angle': self.particle.angle,
            'radius': self.particle.radius,
            'spriteKey': self.particle.spriteKey,
            'currentTime': self.currentTime,
            'nextPos': {
                'x': self.particle.nextPos.x,
                'y': self.particle.nextPos.y
            },
            'nextPosTime': self.particle.nextPosTime,
            'fps': self.particle.spriteSheet.fps,
            'remove': self.remove,
            'updateSprite': self.particle.updateSprite,
            'maxRange': self.particle.maxRange,
            'numColumns': self.particle.spriteSheet.numColumns,
            'numRows': self.particle.spriteSheet.numRows,
            'startColumn': self.particle.spriteSheet.startColumn,
            'startRow': self.particle.spriteSheet.startRow,
            'endRow': self.particle.spriteSheet.endRow,
            'endColumn': self.particle.spriteSheet.endColumn,
            'magic': self.magic,
            'melee': self.melee,
            'range': self.range,
            'life': self.life,
        }
        c = json.dumps(data)
        return data
Example #3
0
class Train:
    def __init__(self, maxVel, maxAcceleration, lineName1, lineName2,
                 relation_dict, line_dict, way_dict, node_dict, angle, radius,
                 spriteKey, spriteDictionary, spriteFps, idObject, numRows,
                 numColumns, startRow, startColumn, endRow, endColumn, color):

        self.line1 = lineName1
        self.line2 = lineName2
        self.line1Bool = True

        self.way_list = line_dict[
            self.line1]  #make sure this is a list of ways by id's
        wayId = self.way_list[0]
        way = way_dict[wayId]
        self.node_list = way['nodes']

        self.stop_list = line.getStopListFromLineName(relation_dict, way_dict,
                                                      self.line1)

        self.traverseForward = True

        self.reachedEnd = False
        self.wayIndex = 0
        self.nodeIndex = 1
        self.stopIndex = 0

        self.color = color
        self.send = True
        self.remove = False
        self.currentWay = self.way_list[self.wayIndex]
        self.currentStop = self.stop_list[self.stopIndex]
        self.nextStop = self.stop_list[self.stopIndex]
        self.currentNode = self.node_list[self.nodeIndex - 1]
        self.nextNode = self.node_list[self.nodeIndex]
        nodeCurrent = node_dict[self.currentNode]
        nodeNext = node_dict[self.nextNode]
        self.acceleration = 0
        self.maxVel = maxVel
        self.maxAcceleration = maxAcceleration

        vel = Vector(nodeNext['x'], nodeNext['y']).subtract(
            Vector(nodeCurrent['x'], nodeCurrent['y']))
        if vel.length() != 0:
            vel.normalize()

        self.directionVect = vel
        self.cooldown = nodeCurrent['delay']
        if self.maxVel == 50:
            self.cooldown = 10

        self.currentTime = time.time()
        self.idObject = idObject
        self.particle = Particle(True,
                                 Vector(nodeCurrent['x'], nodeCurrent['y']),
                                 Vector(0, 0), radius, angle, spriteKey,
                                 spriteDictionary, spriteFps, False, False,
                                 self.idObject, numRows, numColumns, startRow,
                                 startColumn, endRow, endColumn)

    def update(self, nodeTraffic_dict, relation_dict, line_dict, way_dict,
               node_dict, simulation_speed):
        if not self.reachedEnd:
            if self.cooldown > 0:  #wait for cooldown
                self.cooldown -= ((time.time() - self.currentTime) *
                                  simulation_speed)
                if self.cooldown == 0:
                    stop = nodeTraffic_dict[self.currentStop]
                    # self.remove=True
                    if self.idObject in stop:
                        stop.pop(self.idObject)

            elif self.cooldown < 0:
                self.cooldown = 0
                stop = nodeTraffic_dict[self.currentStop]
                # self.remove=True
                if self.idObject in stop:
                    stop.pop(self.idObject)

            else:
                self.updateVelocity(nodeTraffic_dict, relation_dict, line_dict,
                                    way_dict, node_dict, simulation_speed)
        else:
            self.particle.vel.multiply(0)

        self.particle.update(simulation_speed)
        self.currentTime = time.time()

    def draw(self, canvas, cam, node_dict):
        # line.drawNodeList(canvas, cam, node_dict, self.node_list)
        # line.drawNode(canvas,cam,node_dict,self.nextNode,'Green')
        # line.drawNode(canvas,cam,node_dict,self.nextStop,'Red')
        # self.particle.draw(canvas, cam)
        distance = cam.origin.copy().subtract(self.particle.pos)
        if distance.getX() < 0:
            distance.x *= -1
        if distance.getY() < 0:
            distance.y *= -1

        if distance.getX() < cam.dim.getX() and distance.getY() < cam.dim.getY(
        ):
            pos3 = self.particle.pos.copy().transformToCam(cam).getP()

            currentNode = node_dict[self.currentNode]
            nextNode = node_dict[self.nextNode]
            directVector = Vector(nextNode['x'], nextNode['y']).subtract(
                Vector(currentNode['x'], currentNode['y']))
            if directVector.length() != 0:
                directVector.normalize().negate()
                rad = self.particle.radius
                ratio = cam.ratioToCam()
                length = rad * ratio.getX()
                pos1 = directVector.copy().rotate(30)
                pos2 = directVector.copy().rotate(-30)
                pos1.multiply(length).add(self.particle.pos)
                pos2.multiply(length).add(self.particle.pos)

                canvas.draw_polygon([
                    pos1.transformToCam(cam).getP(),
                    pos2.transformToCam(cam).getP(), pos3
                ], 2, 'red', self.color)

    def incrementIndexes(self, way_dict, node_dict):
        self.currentNode = self.nextNode
        if (self.nodeIndex < len(self.node_list) - 1 and self.traverseForward
            ) or (self.nodeIndex > 0 and not self.traverseForward):  #next node
            if self.traverseForward:

                self.nodeIndex += 1
            else:
                self.nodeIndex -= 1
            self.nextNode = self.node_list[self.nodeIndex]
        elif (self.nodeIndex >= len(self.node_list) - 1
              and self.traverseForward) or (self.nodeIndex <= 0
                                            and not self.traverseForward):
            if self.wayIndex >= len(self.way_list) - 1:  #reached end
                self.reachedEnd = True
                self.nodeIndex = 1
                self.wayIndex = 0
            else:  #next way
                self.wayIndex += 1
                self.nodeIndex = 0
                self.currentWay = self.way_list[self.wayIndex]
                way = way_dict[self.currentWay]
                self.node_list = way['nodes']
                self.nextNode = self.node_list[self.nodeIndex]
                currentNode = node_dict[self.currentNode]
                nextNode = node_dict[self.nextNode]
                wayId = self.way_list[self.wayIndex]
                way = way_dict[wayId]
                nodeId = self.node_list[self.nodeIndex + 1]
                nextNextNode = node_dict[nodeId]
                if self.currentNode == self.nextNode:
                    self.traverseForward = True
                elif Vector(currentNode['x'], currentNode['y']).distanceTo(
                        Vector(nextNode['x'], nextNode['y'])) < Vector(
                            currentNode['x'], currentNode['y']).distanceTo(
                                Vector(nextNextNode['x'], nextNextNode['y'])):
                    self.traverseForward = True
                else:
                    self.traverseForward = False
                    self.nodeIndex = len(self.node_list) - 1
                    self.nextNode = self.node_list[self.nodeIndex]

    def getNodeFromId(self, node_dict, nodeId):
        return node_dict[nodeId]

    def getPosVectorFromNode(self, node_dict, nodeId):
        node = node_dict[nodeId]
        return Vector(node['x'], node['y'])

    def checkIfReachedNode(self, way_dict, node_dict):
        if self.particle.vel.getX() != 0 or self.particle.vel.getY() != 0:
            if self.particle.vel.copy().dot(
                    self.getPosVectorFromNode(node_dict,
                                              self.nextNode).subtract(
                                                  self.particle.pos)) < 0:
                # if traveling away from node and close to it (reached it)

                # if doCirclesIntersect(self.particle.pos,2,self.getPosVectorFromNode(node_dict,self.nextNode),2):
                self.incrementIndexes(way_dict, node_dict)

                self.cooldown = node_dict[self.currentNode]['delay']

                vel = self.getPosVectorFromNode(
                    node_dict, self.nextNode).subtract(
                        self.getPosVectorFromNode(node_dict, self.currentNode))
                if vel.length() != 0:
                    vel.normalize()
                    self.directionVect = vel.copy()
                    vel.multiply(self.particle.vel.length())

                    self.particle.vel = vel.copy()
                    self.particle.pos = self.getPosVectorFromNode(
                        node_dict, self.currentNode)
        elif self.particle.pos == self.getPosVectorFromNode(
                node_dict, self.nextNode):
            self.incrementIndexes(way_dict, node_dict)

            self.cooldown = node_dict[self.currentNode]['delay']

            vel = self.getPosVectorFromNode(node_dict, self.nextNode).subtract(
                self.getPosVectorFromNode(node_dict, self.currentNode))
            if vel.length() != 0:
                vel.normalize()
                self.directionVect = vel.copy()
                vel.multiply(self.particle.vel.length())

                self.particle.vel = vel.copy()
                self.particle.pos = self.getPosVectorFromNode(
                    node_dict, self.currentNode)

    def checkDecelForStop(self, node_dict):
        nextStop = node_dict[self.nextStop]
        distanceToStop = self.particle.pos.copy().distanceTo(
            Vector(nextStop['x'], nextStop['y']))
        distanceToDecel = self.particle.vel.copy().multiply(
            (self.particle.vel.length() / self.maxAcceleration)).length()

        if distanceToStop < distanceToDecel:
            self.acceleration = -self.maxAcceleration

    def updateVelocity(self, nodeTraffic_dict, relation_dict, line_dict,
                       way_dict, node_dict, simulation_speed):

        # check for condition of index incrementation
        self.checkIfReachedNode(way_dict, node_dict)

        currentVel = self.particle.vel.copy().length()
        nextNode = node_dict[self.nextNode]
        nextStop = node_dict[self.nextStop]
        if (Vector(nextNode['x'], nextNode['y']).subtract(
                self.particle.pos)).dot(self.particle.vel) < 0:
            currentVel *= -1
        if currentVel < nextNode['maxVel'] or nextNode == nextStop:
            self.acceleration = self.maxAcceleration

        elif currentVel > nextNode['maxVel'] and nextNode != nextStop:
            self.acceleration = -self.maxAcceleration

        else:
            self.acceleration = 0

        self.checkDecelForStop(node_dict)

        #second distance check with trains in the same stop location of the dictionary:
        stop = nodeTraffic_dict[self.nextStop]
        for id in stop:
            if id != self.idObject:
                particle = stop[id]
                velocityA = self.particle.vel.copy()
                velocityB = particle.vel.copy()
                if velocityA.dot(velocityB) > 0:
                    distanceToStop = self.particle.pos.copy().distanceTo(
                        particle.pos)
                    distanceToDecel = self.particle.vel.copy().multiply(
                        (self.particle.vel.length() /
                         self.maxAcceleration)).length()

                    if distanceToStop - 100 < distanceToDecel and self.particle.vel.copy(
                    ).dot(particle.pos.copy().subtract(self.particle.pos)) > 0:
                        self.acceleration = -self.maxAcceleration
                        if self.particle.vel.length() < 1:
                            self.acceleration = 0
                            self.particle.vel.multiply(0)

        #update velocity in relation to acceleration
        if self.currentNode == self.nextNode:
            self.incrementIndexes(way_dict, node_dict)
        if self.directionVect.length() != 0 and self.acceleration != 0:
            velToAdd = self.directionVect.copy().multiply(self.acceleration)
            velToAdd.multiply(
                (time.time() - self.currentTime) * simulation_speed)
            self.particle.vel.add(velToAdd)

        #check if reached stop
        self.checkIfReachedStop(nodeTraffic_dict, relation_dict, line_dict,
                                way_dict, node_dict)

    def checkIfReachedStop(self, nodeTraffic_dict, relation_dict, line_dict,
                           way_dict, node_dict):
        nextStop = node_dict[self.nextStop]
        pos = Vector(nextStop['x'], nextStop['y'])
        if self.currentNode == self.nextStop or (
                self.particle.pos.copy().distanceTo(pos) < 300 and
            (pos.copy().subtract(self.particle.pos)).dot(self.particle.vel) < 0
        ):
            self.stopIndex += 1
            self.send = True
            self.currentStop = self.nextStop
            # if in current remove, add yourself to

            if self.stopIndex < len(self.stop_list):
                self.nextStop = self.stop_list[self.stopIndex]
                nextStopDic = nodeTraffic_dict[self.nextStop]
                nextStopDic.update({self.idObject: self.particle})
            elif self.nextStop == self.stop_list[len(self.stop_list) - 1]:
                self.reachedEnd = True
                if self.line1Bool:
                    self.setLine(relation_dict, line_dict, way_dict, node_dict,
                                 self.line2)
                    self.line1Bool = False
                else:
                    self.setLine(relation_dict, line_dict, way_dict, node_dict,
                                 self.line1)
                    self.line1Bool = True
            self.particle.vel.multiply(0)

    def setLine(self, relation_dict, line_dict, way_dict, node_dict,
                line_name):
        self.way_list = line_dict[
            line_name]  # make sure this is a list of ways by id's
        wayId = self.way_list[0]
        way = way_dict[wayId]
        self.node_list = way['nodes']

        self.stop_list = line.getStopListFromLineName(relation_dict, way_dict,
                                                      line_name)
        self.reachedEnd = False

        self.wayIndex = 0
        self.nodeIndex = 1
        self.stopIndex = 0

        self.currentWay = self.way_list[self.wayIndex]
        self.currentStop = self.stop_list[self.stopIndex]
        self.nextStop = self.stop_list[self.stopIndex]
        self.currentNode = self.node_list[self.nodeIndex - 1]
        self.nextNode = self.node_list[self.nodeIndex]
        nodeCurrent = node_dict[self.currentNode]
        nodeNext = node_dict[self.nextNode]
        self.acceleration = 0

        vel = Vector(nodeNext['x'], nodeNext['y']).subtract(
            Vector(nodeCurrent['x'], nodeCurrent['y']))
        if vel.length() != 0:
            vel.normalize()
        self.directionVect = vel
        self.cooldown = nodeCurrent['delay']
        self.currentTime = time.time()

    def checkVel(self):
        pass

    def encode(self):

        data = {
            'id': str(self.idObject),
            'pos': {
                'x': self.particle.pos.getX(),
                'y': self.particle.pos.getY()
            },
            'stop_list': self.stop_list,
            'stop_index': self.stopIndex,
            'stop': self.currentStop,
        }

        return data
Example #4
0
class Weapon:
    def __init__(self, pos, vel, nextPosTime, nextPos, maxVel, angle, radius,
                 spriteKey, spriteDictionary, spriteFps, idObject, numRows,
                 numColumns, startRow, startColumn, endRow, endColumn,
                 removeOnVelocity0, removeOnAnimationLoop, damage):
        # id's
        self.remove = False
        self.idClass = 5
        self.idPlayer = 0  #set on weapon creation.
        self.idObject = idObject
        self.updateSprite = True
        # non-vectors (attributes)
        self.damage = damage
        self.applied = False
        self.sent = False  #the above has a bug that i can't solve, continuous damage application accross network, so I will limit to sending this object once

        # vectors

        # Sprite Attributes
        self.currentTime = 0
        self.removeOnVelocity0 = removeOnVelocity0
        self.removeOnAnimationLoop = removeOnAnimationLoop

        # sub class
        self.particle = Particle(
            self.updateSprite,
            pos,
            vel,
            nextPosTime,
            nextPos,
            maxVel,
            0,
            angle,
            radius,
            spriteKey,  #0 is the range, as this is a weapon, no need.
            spriteDictionary,
            spriteFps,
            self.removeOnVelocity0,
            self.removeOnAnimationLoop,
            self.idObject,
            numRows,
            numColumns,
            startRow,
            startColumn,
            endRow,
            endColumn)

    def recieve(self, nextPos, nextPosTime, maxVel, angle, spriteKey, fps,
                numRows, numColumns, startRow, startColumn, endRow, endColumn,
                radius, spriteDictionary, applied):

        self.particle.recieve(nextPos, nextPosTime, maxVel, 0, angle, True,
                              spriteKey, fps, numRows, numColumns, startRow,
                              startColumn, endRow, endColumn, radius,
                              spriteDictionary)
        self.applied = applied

    def draw(self, canvas, cam):
        self.particle.draw(canvas, cam)

    def move(self, pos):
        self.particle.move(pos)

    def update(self):
        self.particle.update()
        self.currentTime = time.time()

    def turn(self, angle):
        self.particle.angle += angle

    def encode(self):
        data = {
            'pos': {
                'x': self.particle.pos.x,
                'y': self.particle.pos.y
            },
            'vel': {
                'x': self.particle.vel.x,
                'y': self.particle.vel.y
            },
            'nextPosTime': self.particle.nextPosTime,
            'nextPos': {
                'x': self.particle.nextPos.x,
                'y': self.particle.nextPos.y
            },
            'maxVel': self.particle.maxVel,
            'angle': self.particle.angle,
            'radius': self.particle.radius,
            'spriteKey': self.particle.spriteKey,
            'fps': self.particle.spriteSheet.fps,
            'idObject': self.idObject,
            'removeOnVelocity0': self.removeOnVelocity0,
            'removeOnAnimationLoop': self.removeOnAnimationLoop,
            'idClass': self.idClass,
            'currentTime': self.currentTime,
            'applied': self.applied,
            'numColumns': self.particle.spriteSheet.numColumns,
            'numRows': self.particle.spriteSheet.numRows,
            'startColumn': self.particle.spriteSheet.startColumn,
            'startRow': self.particle.spriteSheet.startRow,
            'endRow': self.particle.spriteSheet.endRow,
            'endColumn': self.particle.spriteSheet.endColumn,
            'damage': self.damage
        }
        e = json.dumps(data)
        return data
Example #5
0
class Monster:
    def __init__(self, pos, vel, nextPosTime, nextPos, maxVel, angle, radius,
                 spriteKey, spriteDictionary, spriteFps, idObject, hasFired,
                 clickPosition, spriteState, numRows, numColumns, startRow,
                 startColumn, endRow, endColumn, tier, aBack, external,
                 totalLife, operationOrigin, operationRange, attackRange,
                 followDistance):
        # id's
        self.remove = False
        self.idClass = 4
        self.idObject = idObject
        self.external = external
        # non-vectors (attributes)
        self.operationOrigin = operationOrigin
        self.operationRange = operationRange
        self.attackRange = attackRange
        self.followDistance = followDistance
        self.returning = False
        self.hasSelectedReturn = False
        self.tier = tier
        self.life = totalLife
        self.lifePrev = self.life
        self.range = 0
        self.melee = 0
        self.magic = 0
        self.tier = 0
        self.totalLife = totalLife
        self.hitByWeapon = 0  #used for when external arrow hits local monster... need to save that arrows id as it can reapear even if removed locally

        # vectors
        self.clickPosition = clickPosition
        # Sprite Attributes
        self.spriteState = spriteState
        self.currentTime = 0
        self.hasFired = hasFired
        self.fireCooldown = 0

        self.aBack = aBack

        #sub class
        self.particle = Particle(True, pos, vel, nextPosTime, nextPos, maxVel,
                                 0, angle, radius, spriteKey, spriteDictionary,
                                 spriteFps, False, False, self.idObject,
                                 numRows, numColumns, startRow, startColumn,
                                 endRow, endColumn)

    def recieve(self, hasFired, clickPosition, nextPos, nextPosTime, maxVel,
                maxRange, angle, updateSprite, spriteKey, fps, numRows,
                numColumns, startRow, startColumn, endRow, endColumn, radius,
                spriteDictionary, life, range, melee, magic, remove):

        self.life = life
        self.melee = melee
        self.range = range
        self.magic = magic
        self.remove = remove
        self.hasFired = hasFired
        self.clickPosition = clickPosition
        self.particle.recieve(nextPos, nextPosTime, maxVel, maxRange, angle,
                              updateSprite, spriteKey, fps, numRows,
                              numColumns, startRow, startColumn, endRow,
                              endColumn, radius, spriteDictionary)

    def update(self):

        self.particle.update()
        self.setCorrectSpriteState()
        self.checkFireCooldown()
        self.currentTime = time.time()

    def setSpriteState(self, state):
        self.spriteState = state
        if state == 1:  # FIRST HALF OF SPRITE SHEET GOING LEFT

            self.particle.spriteSheet.startRow = 1
            self.particle.spriteSheet.endRow = self.particle.spriteSheet.numRows / 2
            self.particle.spriteSheet.currentRow -= self.particle.spriteSheet.numRows / 2
        elif state == 2:  # SECOND HALF OF SPRITE SHEET GOING RIGHT

            self.particle.spriteSheet.endRow = self.particle.spriteSheet.numRows
            self.particle.spriteSheet.startRow = self.particle.spriteSheet.numRows / 2 + 1

            self.particle.spriteSheet.currentRow += self.particle.spriteSheet.numRows / 2

        if self.aBack and self.spriteState == 1 and self.particle.spriteSheet.startColumn < self.particle.spriteSheet.endColumn:
            self.particle.spriteSheet.startColumn = self.particle.spriteSheet.numColumns
            self.particle.spriteSheet.endColumn = self.particle.spriteSheet.numColumns - self.particle.spriteSheet.endColumn
        elif not self.aBack and self.spriteState == 1 and self.particle.spriteSheet.startColumn > self.particle.spriteSheet.endColumn:
            self.particle.spriteSheet.startColumn = 1
            self.particle.spriteSheet.endColumn = self.particle.spriteSheet.numColumns - self.particle.spriteSheet.endColumn
        elif not self.aBack and self.spriteState == 2 and self.particle.spriteSheet.startColumn < self.particle.spriteSheet.endColumn:
            self.particle.spriteSheet.startColumn = self.particle.spriteSheet.numColumns
            self.particle.spriteSheet.endColumn = self.particle.spriteSheet.numColumns - self.particle.spriteSheet.endColumn
        elif self.aBack and self.spriteState == 2 and self.particle.spriteSheet.startColumn > self.particle.spriteSheet.endColumn:
            self.particle.spriteSheet.startColumn = 1
            self.particle.spriteSheet.endColumn = self.particle.spriteSheet.numColumns - self.particle.spriteSheet.endColumn

    def draw(self, canvas, cam):

        self.particle.draw(canvas, cam)
        if SHOW_MONSTER_THOUGHTS:
            ratio = cam.ratioToCam()

            percentage = -self.life / self.totalLife
            simplegui_lib_draw.draw_rect(
                canvas,
                self.particle.pos.copy().add(Vector(
                    0, -100)).transformToCam(cam).getP(),
                Vector(100, 20).multiplyVector(Vector(
                    percentage, 0.2)).multiplyVector(ratio).getP(),
                1,
                'Red',
                fill_color='red')

        if SHOW_MONSTER_THOUGHTS:
            ratio = cam.ratioToCam()

            radius1 = int(self.attackRange * ratio.getX())
            radius2 = int(self.followDistance * ratio.getX())
            canvas.draw_circle(
                self.particle.pos.copy().transformToCam(cam).getP(), radius1,
                1, 'Red')
            canvas.draw_circle(
                self.particle.pos.copy().transformToCam(cam).getP(), radius2,
                1, 'Pink')
            simplegui_lib_draw.draw_rect(
                canvas,
                self.operationOrigin.copy().transformToCam(cam).subtract(
                    self.operationRange.copy().multiplyVector(ratio)).getP(),
                self.operationRange.copy().add(
                    self.operationRange).multiplyVector(ratio).getP(),
                1,
                'White',
                fill_color=None)

    def move(self, pos):
        self.particle.move(pos)

    def checkFireCooldown(self):
        if self.hasFired:
            self.fireCooldown += time.time() - self.currentTime
            if self.fireCooldown > 5:
                self.hasFired = False
                self.fireCooldown = 0

    def turn(self, angle):
        self.particle.angle += angle

    def setCorrectSpriteState(self):
        if self.particle.pos.getX() - self.particle.nextPos.getX(
        ) < 0 and not self.spriteState == 2:
            self.setSpriteState(2)
        elif self.particle.pos.getX() - self.particle.nextPos.getX(
        ) > 0 and not self.spriteState == 1:
            self.setSpriteState(1)

    def encode(self):
        data = {
            'spriteState': self.spriteState,
            'clickPosition': {
                'x': self.clickPosition.x,
                'y': self.clickPosition.y
            },
            'hasFired': self.hasFired,
            'idObject': self.idObject,
            'idClass': self.idClass,
            'pos': {
                'x': self.particle.pos.x,
                'y': self.particle.pos.y
            },
            'vel': {
                'x': self.particle.vel.x,
                'y': self.particle.vel.y
            },
            'maxVel': self.particle.maxVel,
            'angle': self.particle.angle,
            'radius': self.particle.radius,
            'spriteKey': self.particle.spriteKey,
            'currentTime': self.currentTime,
            'nextPos': {
                'x': self.particle.nextPos.x,
                'y': self.particle.nextPos.y
            },
            'nextPosTime': self.particle.nextPosTime,
            'fps': self.particle.spriteSheet.fps,
            'remove': self.remove,
            'updateSprite': self.particle.updateSprite,
            'maxRange': self.particle.maxRange,
            'numColumns': self.particle.spriteSheet.numColumns,
            'numRows': self.particle.spriteSheet.numRows,
            'startColumn': self.particle.spriteSheet.startColumn,
            'startRow': self.particle.spriteSheet.startRow,
            'endRow': self.particle.spriteSheet.endRow,
            'endColumn': self.particle.spriteSheet.endColumn,
            'magic': self.magic,
            'melee': self.melee,
            'range': self.range,
            'life': self.life,
            'tier': self.tier,
            'aBack': self.aBack,
            'external': True,
            'totalLife': self.totalLife,
            'operationOrigin': {
                'x': self.operationOrigin.x,
                'y': self.operationOrigin.y
            },
            'operationRange': {
                'x': self.operationRange.x,
                'y': self.operationRange.y
            },
            'attackRange': self.attackRange,
            'followDistance': self.followDistance
        }
        b = json.dumps(data)
        return data