def createBullet(self, spawnx, spawny, mousex, mousey, accuracyLevel, bulletType): self.bulletType.append(bulletType) self.bullet_isActive.append(True) displacement = 0 if bulletType == "spray": displacement = random.randint(0, 16) self.bulletx.append(spawnx - displacement) # Add a bullet x self.bullety.append(spawny - displacement) # Add a bullet y self.bulletRadius.append( self.bulletStartingRadius) # Add a bullet radius self.bouncyBulletBounces.append(0) if bulletType == "spray": _accuracyLevel = accuracyLevel + random.randint(20, 40) else: _accuracyLevel = accuracyLevel accuracy = random.randint(0, _accuracyLevel) playerVector = Vec2d(spawnx, spawny) directionX = random.randint(mousex - accuracy, mousex + accuracy) directionY = random.randint(mousey - accuracy, mousey + accuracy) directionVector = Vec2d(directionX, directionY) self.bulletv.append(Vec2d(directionVector - playerVector)) # Add a bullet vector self.bulletv[self.bullets] = self.bulletv[self.bullets].normalized( ) # normalize the vector just made to minimal length self.bullets += 1 # Increase bullets by 1 (for offset usage) self.ammo -= 1 # take away 1 ammo
def addExplosion(self, x, y): chanceForHugeExplosion = random.randint(1, 30) if chanceForHugeExplosion == 1: # 3%(roughly) chance for a huge particle explosion bloodParticles = 100 # spawn 200 blood particles else: # failed the 5 % chance, normal amounts of particles bloodParticles = random.randint(6, 16) # randomize how many blood particles spawn for i in range(bloodParticles): self.x.append(int(x)) # Pass X self.y.append(int(y)) # Pass Y self.active.append(True) # start the explosion as active x2 = random.randint(0, self.screenWidth) # random x for vector y2 = random.randint(0, self.screenHeight) # random y for vector dv = Vec2d(x2,y2) # set random point as a vector pv = Vec2d(x,y) # set the vector of current pos v = Vec2d(dv - pv) # create the vector v = v.normalized() # normalize the vector self.vector.append(v) # add the new vector vel = random.randint(1, 10) # randomize velocity self.velocity.append(vel) # append the new velocity maxLength = random.randint(17 * vel, 36 * vel) # randomize how long they will travel self.maxLength.append(maxLength) # append the new length max self.length.append(0) # append the new length traveled red = random.randint(50, 190) # random dark red for the explosion red = (red, 0, 0) self.red.append(red) # add the new red
def checkDoubleWallCollision(self): if self.topWallCollided == True and self.leftWallCollided == True and self.bottomWallCollided == True and self.rightWallCollided == True: # If every wall has collided middleVector = Vec2d(int(self.screenWidth / 2), int(self.screenHeight / 2)) # create a vector of the screen middle playerVector = Vec2d(int(self.playerRect.center[0]), int(self.playerRect.center[1])) # create a vector of the player playerToMiddleVector = Vec2d(middleVector - playerVector) # create a vector of the direction between middle and player playerToMiddleVector = playerToMiddleVector.normalized() # normalize to the shortest length playerpos = self.x, self.y # throw player coordinates in a tuple so they can be adjusted via playerToMiddleVector playerpos += playerToMiddleVector * (self.getVelocity() * 2) # translate the player self.x, self.y = playerpos # unpack the tuple back into the x,y coordinates of the player
def addGrenade(self, x, y, mousex, mousey): # Create vector: posVector = Vec2d(x, y) mouseVector = Vec2d(mousex, mousey) vector = Vec2d(mouseVector - posVector) vector = vector.normalized() # Create grenade: self.activeGrenades.append(True) self.grenades.append( Grenade(x, y, self.width, self.height, vector, 6, self.image))
def getSpawnPoint(colour=0): # Spawn locations spawn = [ Vec2d(worldsize[0] / 5, worldsize[1] / 5), Vec2d(worldsize[0] / 5, 4 * worldsize[1] / 5), Vec2d(4 * worldsize[0] / 5, worldsize[1] / 5), Vec2d(4 * worldsize[0] / 5, 4 * worldsize[1] / 5) ] return spawn[colour % 4] + Vec2d( (1 - 2 * random.random()) * worldsize[0] / 5, (1 - 2 * random.random()) * worldsize[1] / 5)
def __init__(self, robot=None): if (robot == None): self.position = Vec2d(0, 0) self.direction = Vec2d(0, 0) return self.UID = robot.UID self.colour = robot.colour self.position = robot.position.copy() self.direction = robot.direction.copy() self.speed = robot.speed self.maxspeed = robot.maxspeed self.hitpoints = robot.hitpoints self.missilesLeft = robot.missilesLeft self.signal = robot.signal
def test_move(self): vp = GameEntity() vp.setPosition(0, 0) vp.setDimensions(1000, 1000) vp.move(10, 10) self.assertEqual(vp.getPosition(), Vec2d(10, 10))
def generate(self): for x in range(0, self.mapHeight / self.cellHeight): temp = [] for y in range(0, self.mapWidth / self.cellWidth): temp.append(Cell.Cell(Vec2d(x, y), snoise2(x, y, 10) * 5.0 + 20.0)) self.map.append(temp)
def checkZombiePlayerCollision(self, player, soundManager): for zombie in range(len(self.zombieManager.getZombies()) ): # run a for loop for all zombies if self.zombieManager.getZombies()[zombie].getLifeStatus() == True: if self.zombieManager.getZombies()[zombie].getAttackStatus( ) == True: if self.zombieManager.getZombies()[zombie].getRect( ).colliderect(player.getRect( )): # if the current zombie is colliding with the player soundManager.playSound( "attack") # play the zombie attack sound player.giveHealth(-1) # take 1 hp away from the player playerVec = Vec2d(player.getRect().center[0], player.getRect().center[1]) zombieVec = Vec2d( self.zombieManager.getZombies() [zombie].getRect().center[0], self.zombieManager.getZombies() [zombie].getRect().center[1]) playerToZombieVec = Vec2d(playerVec - zombieVec) playerToZombieVec = playerToZombieVec.normalized() # translate to the player ( Lunge like ) by half the width and height of it's collision rectangle self.zombieManager.getZombies()[zombie].translate( playerToZombieVec[0] * (player.getRect().width / 2), playerToZombieVec[1] * (player.getRect().height / 2)) self.zombieManager.setZombieAttacked( zombie, self.getGameClock()) # Draw the zombie speech string: zombieQuotes = [ "Scratch!", "Swipe!", "Chomp!", "Slash!", "Whack!", "Slam!", "Grrgah!", "Kick!", "Bite!", "Stomp!" ] zombieSpeech = random.randint( 0, 9) # Select out of the 4 speeches zombieSpeech = zombieQuotes[zombieSpeech] font = pygame.font.SysFont("Trebuchet MS", 10) self.stringManager.addText( zombieSpeech, (255, 25, 25), font, self.zombieManager.getZombies() [zombie].getRect().center, 1, -1, self.getGameClock()) font = None # Delete from memory
def test_distanceTo(self): ge = GameEntity() ge.setPosition(100, 100) ge1 = GameEntity() ge1.setPosition(101, 100) self.assertEqual(ge.distanceTo(ge1), 1) self.assertEqual(ge.distanceTo(Vec2d(101, 100)), 1) self.assertEqual(ge.distanceTo((101, 100)), 1)
def test_setPosition(self): vp = GameEntity() vp.setPosition(101, 202) self.assertEqual(vp._rect.x, 101) self.assertEqual(vp._rect.y, 202) vp = GameEntity() vec = Vec2d(303, 404) vp.setPosition(vec) self.assertEqual(vp._rect.x, 303) self.assertEqual(vp._rect.y, 404)
def __init__(self, position, perlin): self.x = position.x self.y = position.y self.cost = 0 self.passable = True GameEntity.__init__(self) self.setPosition( Vec2d(position.x * config.CELL_WIDTH, position.y * config.CELL_HEIGHT)) self.setDimensions(config.CELL_WIDTH, config.CELL_HEIGHT) self.dirty = True self.terrainHeight = perlin self.getType()
def distanceTo(self, other): vec = None if (hasattr(other, 'getPosition')): # other is a GameEntity vec = other.getPosition() elif (hasattr(other, '__slots__')): # other is a Vec2d vec = other else: # other is a tuple vec = Vec2d(other[0], other[1]) if (vec is None): raise AttributeError return (vec - self.getPosition()).get_length()
def flipVectorX(self, b): vectorX = self.getSpecificBulletVector(b).x vectorY = self.getSpecificBulletVector(b).y vectorX *= -1 vector = (vectorX, vectorY) self.setSpecificBulletVector(b, Vec2d(vector))
def getCentre(self): """ returns the centre point of the cell as a vector """ centre = self._rect.center return Vec2d(centre[0], centre[1])
def getPosition(self): """ Gets the current position of the game entity, as a Vector2D """ return Vec2d(self._rect.x, self._rect.y)
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) viewport = Viewport.Viewport(SCREEN) viewport.setPosition(0, 0) viewport.setLimit(0, -CELL_WIDTH) viewport.setLimit(1, (MAP_WIDTH + CELL_WIDTH)) viewport.setLimit(2, -CELL_HEIGHT) viewport.setLimit(3, (MAP_HEIGHT + CELL_HEIGHT)) theMap = Map.Map() theMap.setViewport(viewport) SCREEN.fill(pygame.locals.Color(255, 255, 255)) test = StrategyEntity.StrategyEntity() test.setPosition(Vec2d(4 * CELL_WIDTH, 0)) test.setDimensions(CELL_WIDTH, CELL_HEIGHT) test.setImage(pygame.Surface((test.getRect().width, test.getRect().height))) test.setPath(theMap.findPath(theMap[4][0], theMap[14][12])) # main loop running = True while running: for event in pygame.event.get(): if (event.type == locals.QUIT): pygame.quit() sys.exit() if (event.type == locals.KEYDOWN): if (event.key == locals.K_ESCAPE): pygame.quit() sys.exit()
def flipVector(self, b): vector = self.getSpecificBulletVector(b) vector *= -1 self.setSpecificBulletVector(b, Vec2d(vector))
class Robot(Sprite): colour = 0 viewangle = 180 viewdistance = 900 staticMissile = Missile(Vec2d(0, 0), 0, Vec2d(1, 0)) def __init__(self, col, pos, maxspeed, dirn, hp, ai): self.signal = Move.Signals.NONE self.missilesLeft = 1 self.laser_cooldown = 0 self.laser_max_cooldown = 2 self.laser_overheated = False rad = 8 self.ai = ai Sprite.__init__(self, pos, maxspeed, dirn, hp, rad) self.colour = col def die(self): self.ai.die() def gameOver(self): self.ai.gameOver() def draw(self, cr, simple=False): cr.set_line_width(4) rgb = Teams.RGB[self.colour] cr.set_source_rgb(rgb[0], rgb[1], rgb[2]) if simple: r = cr.device_to_user_distance(0.3 * self.boundingradius, 1.0)[0] cr.arc(0, 0, r, 0, 2 * math.pi) cr.fill() return cr.move_to(0, 0) cr.rel_line_to(20 * self.direction[0], 20 * self.direction[1]) cr.stroke() cr.arc(0, 0, self.boundingradius, 0, 2 * math.pi) cr.stroke_preserve() health = self.hitpoints / float(100) cr.set_source_rgb(health, health, health) cr.fill() cr.set_source_rgb(0, 0, 1) theta = self.directionAngle() cr.rotate(theta) cr.scale(0.5, 0.5) for i in range(0, self.missilesLeft): #cr.arc(-2 + 6*i, self.boundingradius*2, 2, 0, 2 * math.pi) #cr.fill() cr.translate(0, self.boundingradius * 4 + 15 * i) Robot.staticMissile.draw(cr) cr.translate(0, -self.boundingradius * 4 - 15 * i) if not self.signal == Move.Signals.NONE: rgb = Move.Signals.RGB[self.signal] cr.set_source_rgb(rgb[0], rgb[1], rgb[2]) cr.translate(0, -self.boundingradius * 5) cr.arc(0, 0, 11, 0, 2 * math.pi) cr.fill() cr.translate(0, self.boundingradius * 5) cr.scale(2.0, 2.0) cr.rotate(-theta) #Sprite.drawViewCone(self, cr) self.ai.decorateSprite(cr) def getMove(self, worldstate): robotstate = RobotState(self) move = self.ai.getMove(robotstate, worldstate) if (move == Move.FIRE_MISSILE): if (self.missilesLeft > 0): self.missilesLeft -= 1 return move else: move = Move.NONE if (move == Move.FIRE_LASER): if (self.laser_overheated): self.laser_cooldown -= 1 if (self.laser_cooldown == 0): self.laser_overheated = False move = Move.NONE else: self.laser_cooldown += 1 if (self.laser_cooldown == self.laser_max_cooldown): self.laser_overheated = True return move return move