def __init__(self): image = pygame.image.load("images/player/player1.gif") MovingObject.__init__(self, 25, 25, 5, image, 0, 0) self.imageCode = 1 self.live = 5 self.point = 0 self.level = 1 self.rect.x = self.screenwidth / 2 self.rect.y = self.screenheight - 100 self.counterMax = 9 self.counter = self.counterMax self.rebornCounterMax = 150 self.rebornCounter = 0 self.fireSound = pygame.mixer.Sound("sounds/fire.ogg") self.activeStuff = pygame.mixer.Sound("sounds/activeStuff.ogg") self.mushroomSound = pygame.mixer.Sound("sounds/mushroom.ogg") self.liveReduce = pygame.mixer.Sound("sounds/liveReduce.ogg") self.levelPassing = pygame.mixer.Sound("sounds/levelPassing.ogg") self.isReborn = True
def __init__(self, screen, size, pos=None, vel=Coord(0, 0)): if pos == None: pos = Coord(size.x / 2, size.y / 2) MovingObject.__init__(self, screen, size, pos, vel) self.angle = 0 self.r = 20 self.bulletcooldown = 0 self.dead = False
def __init__(self): image = pygame.image.load("images/ghost/ghost1.gif") #x = self.screenwidth - 25 #y = random.randint(0, self.screenheight / (25 * 2) - 1) * 25 MovingObject.__init__(self, 25, 25, 5, image, 0, 0) self.rect.x = self.screenwidth - 25 self.rect.y = random.randint(0, self.screenheight / (25 * 2) - 1) * 25 self.imageCode = 1 self.directionX = -1
def __init__(self, x, y, image, angle, directionX, directionY): image = pygame.transform.rotate( pygame.image.load("images/centipede/centipede" + image + ".gif"), angle) MovingObject.__init__(self, 23, 23, 5, image, x, y) self.totalAngle = angle self.directionX = directionX self.directionY = directionY self.curveCounter = 0 self.feet = CentipedeFeet(self.rect.x, self.rect.y) self.feetPosition = random.randint(1, 3) self.updateFeetPosition()
def opportunisticAI(self, asteroids, heading, framesToFire): if len(asteroids) == 0: return (False, 0) bullet = MovingObject(1, Point2(0, 0), 90, self.bulletSpeed, self.bulletRad) if (asteroids[0].collideWithObject(bullet)): return (True, 0) return (False, 0)
def killAsteroid(self, asteroid, heading, framesToFire, asteroids): bullet = MovingObject(1, origin, heading, self.bulletSpeed, self.bulletRad) buttleTime = asteroid.collideWithObject(bullet) if (buttleTime != None): newPos = asteroid.pos + asteroid.vel * buttleTime if newPos.getX() < -350 or newPos.getX() >= 350 or newPos.getY( ) <= -350 or newPos.getY() >= 350: return (False, 0) else: self.bulletCollion(bullet, buttleTime, asteroids, asteroid, framesToFire) self.count += 1 if self.count == 5: self.hittedAst = [] self.count = 0 return (True, 0) else: dirToAsteroids = normalizeDegrees( math.degrees( math.atan2(asteroid.pos.getY(), asteroid.pos.getX()))) if dirToAsteroids > heading: if abs(dirToAsteroids - heading) > 180: return (False, -self.turnRate) elif abs(dirToAsteroids - heading) < 180: return (False, self.turnRate) else: if abs(dirToAsteroids - heading) > 180: return (False, self.turnRate) elif abs(dirToAsteroids - heading) < 180: return (False, -self.turnRate)
def getAICommand(self, asteroids, heading, framesToFire): if len(asteroids) == 0: return (False, 0) ship = MovingObject(1, origin, heading, 0, 10) firstAttack = [] secondAttack = [] for asteroid in asteroids: nextDtPos = asteroid.pos + asteroid.vel * self.dt if (nextDtPos - ship.pos).length() < asteroid.rad + ship.rad: return None elif (asteroid.collideWithObject(ship)): asteroidInfo = (asteroid, asteroid.collideWithObject(ship)) firstAttack.append(asteroidInfo) else: asteroidInfo = (asteroid, asteroid.speed / asteroid.rad) secondAttack.append(asteroidInfo) newFirstAttack = sorted(firstAttack, key=lambda astInfo: astInfo[1]) newSecontAttack = sorted(secondAttack, key=lambda astInfo: astInfo[1], reverse=True) for asteroidInfo in newFirstAttack: if (asteroidInfo != None): #newFirstAttack.pop() if not self.hittedAst.__contains__(asteroidInfo[0].id): return self.killAsteroid(asteroidInfo[0], heading, framesToFire, asteroids) for asteroidInfo in newSecontAttack: if (asteroidInfo != None): #newSecontAttack.pop() if not self.hittedAst.__contains__(asteroidInfo[0].id): return self.killAsteroid(asteroidInfo[0], heading, framesToFire, asteroids) return (False, 0)
def aggressiveAI(self, asteroids, heading, framesToFire): if len(asteroids) == 0: return (False, 0) bullet = MovingObject(1, Point2(0, 0), heading, self.bulletSpeed, self.bulletRad) if asteroids[0].collideWithObject(bullet): return (True, 0) else: directionToAsteroid = normalizeDegrees( math.degrees( math.atan2(asteroids[0].pos.getY(), asteroids[0].pos.getX()))) if directionToAsteroid > heading: if directionToAsteroid - heading > 180: return (False, -1) else: return (False, +1) else: if heading - directionToAsteroid > 180: return (False, +1) else: return (False, -1)
def __init__(self): image = pygame.image.load("images/mushroomer.gif") MovingObject.__init__(self, 25, 25, 5, image, 0, 25) self.rect.x = random.randint(0, self.screenwidth / 25 - 1) * 25
def update(self): MovingObject.update(self)
def update(self): if not MovingObject.update(self, False): self.dead = True
def __init__(self, screen, size, pos , vel): MovingObject.__init__(self, screen, size, pos, vel) self.r = 5 self.dead = False
def __init__(self, x, y): image = pygame.image.load("images/centipede/centipedeFeet.gif") MovingObject.__init__(self, 3, 25, 0, image, x, y)
def __init__(self, screen, size, r, pos=Coord(0, 0), vel=Coord(0, 0)): MovingObject.__init__(self, screen, size, pos, vel) self.r = r self.speed = 0.15 self.dead = False
def gameLoop(self, task): global globalClock # If the ship is not alive, do nothing. Tasks return Task.cont to # signify that the task should continue running. If Task.done were # returned instead, the task would be removed and would no longer be # called every frame. if not self.alive: return Task.cont # 0. gather information about asteroids rocks = [] for r in self.asteroids: v = self.getTag("velocity", r) idNum = self.getTag("ID", r) heading = degrees(atan2(v.getY(), v.getX())) obj = MovingObject(idNum, Point2(r.getX(), r.getY()), heading, v.length(), r.getScale()[0]/2) rocks.append(obj) # 1. Get ship's command startTime = globalClock.getLongTime() cmd = self.shipAI.getAICommand(rocks, normalizeDegrees(self.ship.getH()+90), self.framesToFire) #cmd = self.shipAI.opportunisticAI(rocks, normalizeDegrees(self.ship.getH()+90), self.framesToFire) #cmd = self.shipAI.trackingAI(rocks, normalizeDegrees(self.ship.getH()+90), self.framesToFire) #cmd = self.shipAI.aggressiveAI(rocks, normalizeDegrees(self.ship.getH()+90), self.framesToFire) if cmd == None: if not self.shieldUsed: self.ship.setColor(0,1,0) self.shieldUsed = True self.shieldFrames = SHIELD_LIFE self.shieldActive = True cmd = (False, 0) endTime = globalClock.getLongTime() if endTime - startTime > AI_TIME: print("Exceeded time limit") #2 Perform ship's command self.updateShip(cmd[0], cmd[1]); #3 Update asteroids- for obj in self.asteroids: self.updatePos(obj) #4 Update bullets newBulletArray = [] for obj in self.bullets: self.updatePos(obj) # Update the bullet maxCoord = FIELD_SZ / 2 if obj.getX() == -maxCoord or obj.getX() == maxCoord or \ obj.getY() == -maxCoord or obj.getY() == maxCoord: obj.removeNode() # Otherwise, remove it from the scene. else: newBulletArray.append(obj) self.bullets = newBulletArray #5 Check bullet collision with asteroids # In short, it checks every bullet against every asteroid. This is # quite slow. A big optimization would be to sort the objects left to # right and check only if they overlap. Framerate can go way down if # there are many bullets on screen, but for the most part it's okay. activeBullets = [] for bullet in self.bullets: # This range statement makes it step though the asteroid list # backwards. This is because if an asteroid is removed, the # elements after it will change position in the list. If you go # backwards, the length stays constant. hit = False for i in range(len(self.asteroids)-1, -1, -1): asteroid = self.asteroids[i] # Panda's collision detection is more complicated than we need # here. This is the basic sphere collision check. If the # distance between the object centers is less than sum of the # radii of the two objects, then we have a collision. We use # lengthSquared() since it is faster than length(). if touching(bullet, asteroid): self.asteroidHit(i) # Handle the hit hit = True if hit: bullet.removeNode() else: activeBullets.append(bullet) self.bullets = activeBullets #6 Update scoreboard gameScore = self.hits[0] * PTS[0] + \ self.hits[1] * PTS[1] + \ self.hits[2] * PTS[2] - \ self.hits[3] * PTS[3] scoreText = "#%d (%d) %d@%d %d@%d %d@%d %d@%d= %d" % (self.currGame, self.currFrame, self.hits[0], PTS[0], self.hits[1], PTS[1], self.hits[2], PTS[2], self.hits[3], PTS[3], gameScore ) self.scoreBrd.setText(scoreText) #7 Check if game is over: # A. maximum number of frames processed # B. Check is ship collided with asteroid if self.currFrame == NUM_FRAMES: self.endGame(gameScore) return Task.cont if self.shieldActive: self.shieldFrames -= 1 print(self.shieldFrames) if self.shieldFrames == 0: self.ship.setColor(1,1,1) self.shieldActive = False else: for ast in self.asteroids: # Same sphere collision check for the ship vs. the asteroid if touching(ast, self.ship): print(self.ship.getPos()) print(ast.getPos()) print((ast.getPos()-self.ship.getPos()).length()) self.endGame(gameScore) return Task.cont self.currFrame += 1 return Task.cont # Since every return is Task.cont, the task will
def aggressiveAI(self, asteroids, heading, framesToFire): if len(asteroids) == 0: return (False, 0) ship = MovingObject(1, origin, heading, 0, 8) if (asteroids[0].collideWithObject(ship)): return self.killAsteroid(asteroids[0], heading, framesToFire)
import math import numpy as np import matplotlib.pyplot as plt import numpy.linalg as la from Sensor import Sensor from Filter import Filter from MovingObject import MovingObject movingObject = MovingObject() sensor = Sensor(movingObject) myFilter = Filter(sensor) m , n = movingObject.getStateX().shape """plot ground truth""" position = movingObject.r plt.scatter(position[0], position[1],s=10,label="Ground truth") plt.title("2D Plane", fontsize=19) plt.xlabel("x", fontsize=10) plt.ylabel("y", fontsize=10) plt.tick_params(axis='both', which='major', labelsize=9) plt.legend(loc='lower right') plt.grid() plt.show()
@author: Ismail """ import numpy as np from MovingObject import MovingObject class Sensor: sigma_r = 10 #meter sigma_phi = np.deg2rad(0.1) #rad def __init__(self, position: tuple): self.x_s, self.y_s, self.z_s = position def observe_object(self, moving_object: MovingObject): #extract position list in the 2 dimensions we observe x, y, _ = moving_object.position z = np.zeros((2, x.size)) z[0] = np.sqrt((x - self.x_s)**2 + (y - self.y_s)**2 + self.z_s**2) z[1] = np.arctan2(y - self.y_s, x - self.x_s) noise = np.random.normal(0, 1, (2, x.size)) * np.array([[Sensor.sigma_r], [Sensor.sigma_phi]]) print(noise) z += noise return z mo = MovingObject()
def setUp(self): self.moving_object = MovingObject(100, 100, 5, 5, "empty.png", 1, 1000)
class TestMovingObject(unittest.TestCase): def setUp(self): self.moving_object = MovingObject(100, 100, 5, 5, "empty.png", 1, 1000) def test_move_up(self): self.moving_object.move_up() expected = (100, 99) self.assertEqual(self.moving_object.position(), expected) def test_move_right(self): self.moving_object.move_right() expected = (101, 100) self.assertEqual(self.moving_object.position(), expected) def test_move_down(self): self.moving_object.move_down() expected = (100, 101) self.assertEqual(self.moving_object.position(), expected) def test_move_left(self): self.moving_object.move_left() expected = (99, 100) self.assertEqual(self.moving_object.position(), expected) def test_move_according_direction(self): self.moving_object.direction = Direction.UP self.moving_object.move() self.assertEqual(self.moving_object.position(), (100, 99)) self.moving_object.direction = Direction.RIGHT self.moving_object.move() self.assertEqual(self.moving_object.position(), (101, 99)) self.moving_object.direction = Direction.DOWN self.moving_object.move() self.assertEqual(self.moving_object.position(), (101, 100)) self.moving_object.direction = Direction.LEFT self.moving_object.move() self.assertEqual(self.moving_object.position(), (100, 100)) def test_set_xy(self): self.moving_object.set_xy(19, 14) self.assertEqual(self.moving_object.position(), (19, 14))