def fire(self): '''英雄飛機開火 ''' x, y = self.pos() if not self.firetwo: # 單子彈位置(0, -60) pos = (x, y - 60) b1 = Bullet(self.__canvas, position=pos, destroy_cb=self.__bullet_list.remove) self.__bullet_list.append(b1) else: # 雙子彈位置(-32, -18)和 (32, -18) pos1 = (x - 14, y - 18) pos2 = (x + 14, y - 18) b1 = Bullet(self.__canvas, position=pos1, destroy_cb=self.__bullet_list.remove) b2 = Bullet(self.__canvas, position=pos2, destroy_cb=self.__bullet_list.remove) self.__bullet_list.append(b2) self.__bullet_list.append(b1) self.firetwo -= 1
def start(self): pygame.init() self.stage = Stage(self, 1) self.screen = pygame.display.set_mode((800, 600)) self.background = Background(self) self.background.load() self.player = Player(self) self.player.load() self.bullet = Bullet(self) self.bullet.load() self.enemies = Enemies(self) self.enemies.load() self.game_text = GameText(self) self.game_text.load() self.explosion = Explosion(self) self.explosion.load() self.caption = Caption(self) self.caption.load() self.score = Score(self) self.score.load() while self.running: self.screen.fill((0, 0, 0)) self.background.show() self.handle_event()
def check_input(self): self.keys = key.get_pressed() for e in event.get(): if self.should_exit(e): sys.exit() if e.type == KEYDOWN and e.key == K_SPACE: num_bullets = (self.score // 1000) + 1 center = (self.player.rect.x + 23, self.player.rect.y + 5) distance = 15 leftess_x = self.player.rect.x + 23 - (distance * num_bullets // 2) rightest_x = self.player.rect.x + 23 + (distance * num_bullets // 2) for i in range(0, num_bullets // 2): left_bullet = Bullet(leftess_x + (distance * i), self.player.rect.y + 5, -1, 15, 'laser', 'left_' + str(i)) right_bullet = Bullet(rightest_x - (distance * i), self.player.rect.y + 5, -1, 15, 'laser', 'right_' + str(i)) self.bullets.add(left_bullet) self.bullets.add(right_bullet) if num_bullets % 2 > 0: bullet = Bullet(self.player.rect.x + 23, self.player.rect.y + 5, -1, 15, 'laser', 'center') self.bullets.add(bullet) if 1 == num_bullets: self.sounds['shoot'].play() else: self.sounds['shoot2'].play() self.allSprites.add(self.bullets)
def update(self): """ Update the player position. """ # Move left/right self.rect.x += self.change_x * (2 if self.shoot_mode == 1 else 1) # Did this update cause us to hit a wall? if self.rect.x < 0 or self.rect.x > Constants.SCREEN_WIDTH - self.rect.width: if self.change_x > 0: self.rect.right = Constants.SCREEN_WIDTH else: # Otherwise if we are moving left, do the opposite. self.rect.left = 0 self.rect.y += self.change_y * (2 if self.shoot_mode == 1 else 1) if self.rect.y < 0 or self.rect.y > Constants.SCREEN_HEIGHT - self.rect.height: # Reset our position based on the top/bottom of the object. if self.change_y > 0: self.rect.bottom = Constants.SCREEN_HEIGHT else: self.rect.top = 0 #logic for shooting modes if self.power_counter > 0: self.power_counter -= 1 if self.power_counter == 0: print("Reset time") self.shoot_mode = 0 if self.shoot_countdown == 0: if self.shoot_mode == 0: mx, my = pygame.mouse.get_pos() dx = float(mx - self.rect.x) dy = float(my - self.rect.y) mag = math.sqrt(dx**2 + dy**2) if not (mag == 0): dx *= 10.0 / mag dy *= 10.0 / mag Game.bullets.append( Bullet(self.rect.x, self.rect.y, dx, dy)) self.shoot_countdown = 10 if self.shoot_mode == 3: mx, my = pygame.mouse.get_pos() dx = float(mx - self.rect.x) dy = float(my - self.rect.y) mag = math.sqrt(dx**2 + dy**2) if not (mag == 0): dx *= 10.0 / mag dy *= 10.0 / mag Game.bullets.append( Bullet(self.rect.x, self.rect.y, dx, dy)) self.shoot_countdown = 1 if self.shoot_mode == 2: for i in range(10): th = float(math.pi * 2 * i / 10.0) Game.bullets.append( Bullet(self.rect.x, self.rect.y, 10 * math.cos(th), 10 * math.sin(th))) self.shoot_countdown = 10 else: self.shoot_countdown -= 1
def test_bullet_collision_with_brick(self): terrain = BrickTerrain(150, 150) enemy_bullet = Bullet(150, 141, 5, 500, 1, Direction.DOWN) self.assertFalse(terrain.contains(enemy_bullet)) enemy_bullet.move(); self.assertTrue(terrain.contains(enemy_bullet))
def creatingTheBullets(self): # Bullet self.noOfBullets = [] bulletX = -5 bulletY = -5 bulletX_change = 0 bullet_state = "ready" self.bullet = Bullet(0, 0, bullet_state, bulletX_change)
def testMove(self): map = Game(1, 13) bullet = Bullet(0, 0, map, 2, 2, "right") x, y = bullet.currPos self.assertEqual([x, y], [2, 2]) bullet.move() x, y = bullet.currPos self.assertEqual([x, y], [3, 2])
def addElemListB(self, x, y, direction, type): bullet = Bullet(self.config) bullet.setx(x) bullet.sety(y) bullet.setType(type) bullet.setDirection(direction) self.listB.append(bullet) return time.time_ns()
def cardinal_shoot(self): top_bullet = Bullet(self, self.rect.centerx, self.rect.top, BLACK) bottom_bullet = Bullet(self, self.rect.centerx, self.rect.bottom, BLACK) right_bullet = Bullet(self, self.rect.right, self.rect.centery, BLACK) left_bullet = Bullet(self, self.rect.left, self.rect.centery, BLACK) self.bullet_list.add(top_bullet, bottom_bullet, right_bullet, left_bullet)
def fire(self, screen): nbullet = Bullet(self) nbullet.mx = 1 self.bullets.append(nbullet) # her ateş edilişinde bir ateş edilme animasyonu devreye girmelidir # bu işlem farklı yollarla yapılabilir # burada yaprığımız normalde -1 olan shoot değerini 0 yapıyoruz ve nesnenin çizim fonksiyonunda bir if yapısıyla bu durumu kontrol ediyoruz. self.shootImageOrder = 0
def shoot(self, stage, board): ret = board if time.time() - self.__shoot_time >= 1: obj_bullet = Bullet(self.__x, self.__y, stage) ret = obj_bullet.print(board) self.__bul_arr.append(obj_bullet) self.__shoot_time = time.time() return ret
def diagonal_shoot(self): top_right_bullet = Bullet(self, self.rect.right, self.rect.top, BLACK) top_left_bullet = Bullet(self, self.rect.left, self.rect.top, BLACK) bottom_right_bullet = Bullet(self, self.rect.right, self.rect.bottom, BLACK) bottom_left_bullet = Bullet(self, self.rect.left, self.rect.bottom, BLACK) self.bullet_list.add(top_right_bullet, top_left_bullet, bottom_right_bullet, bottom_left_bullet)
def shoot(self): if len(BULLETS) < 3: self.shot = True self.anim_count_shot = 0 if self.right: bullet = Bullet(self.rect.x, self.rect.y, 'right') BULLETS.add(bullet) elif self.left: bullet = Bullet(self.rect.x, self.rect.y, 'left') BULLETS.add(bullet)
def test_player_tank_collision_with_enemy_bullet(self): # x, y, speed, owner_id, attack, direction enemy_bullet = Bullet(86, 100, 5, 500, 1, Direction.RIGHT) self.assertFalse(self.player.contains(enemy_bullet)) enemy_bullet.move() self.assertFalse(self.player.contains(enemy_bullet)) enemy_bullet.move() self.assertTrue(self.player.contains(enemy_bullet))
def shoot(self, _bulletList, _playerPos): self.shootCounter += 1 if self.shootCounter == self.shootFreq: self.shootCounter = 0 # generuje pociski z zaleznosci od typu strzalu if self.shootType == ShootType.NORMAL: self.bulletAdd(_bulletList, 0, 1) elif self.shootType == ShootType.FOURDIRECTION: self.bulletAdd(_bulletList, 0, 1) self.bulletAdd(_bulletList, 1, 0) self.bulletAdd(_bulletList, 0, -1) self.bulletAdd(_bulletList, -1, 0) elif self.shootType == ShootType.AIMED: xP = _playerPos.x yP = _playerPos.y xE = self.rect.x yE = self.rect.y r = math.sqrt(pow(abs(xP - xE), 2) + pow(abs(yP - yE), 2)) sin = (yP - yE) / r cos = (xP - xE) / r self.bulletAdd(_bulletList, cos, sin) elif self.shootType == ShootType.EIGHTDIRECTION: self.bulletAdd(_bulletList, 0, 1) self.bulletAdd(_bulletList, 1, 0) self.bulletAdd(_bulletList, -1, 0) self.bulletAdd(_bulletList, 0, -1) self.bulletAdd(_bulletList, 1, 1) self.bulletAdd(_bulletList, -1, 1) self.bulletAdd(_bulletList, 1, -1) self.bulletAdd(_bulletList, -1, -1) elif self.shootType == ShootType.DOUBLE: _bulletList.add( Bullet( "data/new_bullet.png", pygame.math.Vector2( self.rect.left, self.rect.top + self.img.get_height() / 2 - 3), 3, pygame.math.Vector2(0, 1), 8)) _bulletList.add( Bullet( "data/new_bullet.png", pygame.math.Vector2( self.rect.right, self.rect.top + self.img.get_height() / 2 - 3), 3, pygame.math.Vector2(0, 1), 8)) elif self.shootType == ShootType.SPUN: sin = math.sin(self.rect.y) cos = math.cos(self.rect.y) self.bulletAdd(_bulletList, cos, sin)
def shootBullet(self, state): #pew pew if self.ammo > 0: #state is 0 use the mouse if state == 0: offset = ( self.mouseY - self.playerY, self.mouseX - self.playerX ) #should calculate angle between player and mouse, unsure if this works angle = 135 - math.degrees(math.atan2(*offset)) #angle = 0 #placeholder playerBullet = Bullet(self.playerX, self.playerY, angle) #state is 1 use space key elif state == 1: if self.currentFace == MoveConstants.UP: playerBullet = Bullet(self.playerX, self.playerY, -135) elif self.currentFace == MoveConstants.DOWN: playerBullet = Bullet(self.playerX, self.playerY, 45) elif self.currentFace == MoveConstants.LEFT: playerBullet = Bullet(self.playerX, self.playerY, -45) elif self.currentFace == MoveConstants.RIGHT: playerBullet = Bullet(self.playerX, self.playerY, 135) elif self.currentFace == MoveConstants.UPRIGHT: playerBullet = Bullet(self.playerX, self.playerY, 180) elif self.currentFace == MoveConstants.UPLEFT: playerBullet = Bullet(self.playerX, self.playerY, -90) elif self.currentFace == MoveConstants.DOWNRIGHT: playerBullet = Bullet(self.playerX, self.playerY, 90) elif self.currentFace == MoveConstants.DOWNLEFT: playerBullet = Bullet(self.playerX, self.playerY, 0) pygame.mixer.Sound(Sounds.SHOOTSOUND).play() self.bulletList.append(playerBullet) self.ammo -= 1
def maybeShoot(self, keys): """ Shoots a bullet if the player pressed the trigger arguments: keys -- A list consisting of keys preseed """ if ( keys[pygame.K_SPACE] and self.bullet.bulletFlag <= 0): self.bullet = Bullet([self.rect.x+self.rect.width/2, self.rect.y-10],"UP") audio.fire() self.bullet.run()
def __init__(self, pos): """Initializes the player ship. arguments: pos -- a list consisting of x and y coordinate of player ship """ self.image = pygame.image.load("images/player-sprite.png") self.rect = self.image.get_rect() self.rect.move_ip(*pos) # The player bullet self.bullet = Bullet([0,0],"UP", isEnemyBullet=False)
def new_bullet(self): if self.bullet == None: self.bullet = Bullet(self.settings, self.screen, self, self.settings.bullet2) self.bullet_number += 1 else: if self.bullet.rect.y < self.settings.screenHeight: self.bullet.rect.y += self.settings.bullet_speed_factor self.bullet.draw_bullet() else: self.bullet = None
def fire(self, mposition): nbullet = Bullet(self) mx = float(mposition[0] - self.width / 2) my = float(mposition[1] - self.height / 2) angle = math.atan2(my, mx) nbullet.mx = float(math.cos(angle)) * 10 nbullet.my = float(math.sin(angle)) * 10 print(nbullet.mx) print(nbullet.my) nbullet.image = pygame.transform.rotate(nbullet.image, -math.degrees(angle)) self.bullets.append(nbullet)
def shoot(self, x, y): xChange = x-self.x-32 yChange = y-self.y-32 size = xChange*xChange + yChange*yChange xChange /= math.sqrt(size) yChange /= math.sqrt(size) return [Bullet(xChange*self.bulletSpeed, yChange*self.bulletSpeed, self.bulletDamage, self), Bullet(xChange*self.bulletSpeed, yChange*self.bulletSpeed + 1, self.bulletDamage, self), Bullet(xChange*self.bulletSpeed, yChange*self.bulletSpeed - 1, self.bulletDamage, self), Bullet(xChange*self.bulletSpeed, yChange*self.bulletSpeed + 2, self.bulletDamage, self), Bullet(xChange*self.bulletSpeed, yChange*self.bulletSpeed - 2, self.bulletDamage, self),]
def single_shoot(self, bullet1_surface): bullet1 = Bullet(bullet1_surface, [self.rect.left + 24, self.rect.top - 8]) bullet2 = Bullet(bullet1_surface, [self.rect.left + 24 - 8, self.rect.top]) bullet3 = Bullet(bullet1_surface, [self.rect.left + 24 + 8, self.rect.top]) self.bullets1.add(bullet1) self.bullets2.add(bullet2) self.bullets3.add(bullet3)
class Alien(Sprite): """description of class""" def __init__(self, **kwargs): super().__init__() self.screen = kwargs['screen'] self.settings = kwargs['settings'] self.image = pygame.image.load(kwargs['image']) self.rect = self.image.get_rect() self.x = -float(self.rect.width) self.y = float(self.rect.height / 2) self.rect.x = self.x self.rect.y = self.y self.is_finish_bullet = False #斜率K self.k = -(self.settings.screenHeight - 200) / self.settings.screenWidth self.bullet = None self.bullet_number = 0 def update(self, *args): if self.rect.x <= self.settings.screenWidth - 100 and self.y == float( self.rect.height / 2): self.x += self.settings.alien_x_speed else: #self.x=(self.y-self.settings.screenHeight+200)/self.k self.y += self.settings.alien_y_speed self.x -= self.settings.alien_x_speed self.rect.x = self.x self.rect.y = self.y def new_bullet(self): if self.bullet == None: self.bullet = Bullet(self.settings, self.screen, self, self.settings.bullet2) self.bullet_number += 1 else: if self.bullet.rect.y < self.settings.screenHeight: self.bullet.rect.y += self.settings.bullet_speed_factor self.bullet.draw_bullet() else: self.bullet = None def update_bullet(self): if self.bullet.rect.y < self.settings.screenHeight: self.bullet.rect.y += self.settings.bullet_speed_factor self.bullet.draw_bullet() else: self.bullet = None def blitme(self): """在指定的位置显示外星人""" self.screen.blit(self.image, self.rect)
def __init__(self, pos, angle): Bullet.__init__(self, pos, angle) self.image = pygame.image.load("Resources/powerUps/pierce.png") self.rect = self.image.get_rect() self.angle = angle self.rot_angle = self.angle - 90 rot_image = pygame.transform.rotate(self.image, self.rot_angle) rot_rect = self.rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect) self.image = rot_image self.place(pos) self.radius = self.rect.height/2
def __init__(self, player): pygame.sprite.Sprite.__init__(self) # 玩家编号(1/2) self.player = player # 不同玩家用不同的坦克(不同等级对应不同的图) if player == 1: self.Tanks = [ './images/myTank/tank_T1_0.png', './images/myTank/tank_T1_1.png', './images/myTank/tank_T1_2.png' ] elif player == 2: self.Tanks = [ './images/myTank/tank_T2_0.png', './images/myTank/tank_T2_1.png', './images/myTank/tank_T2_2.png' ] else: raise ValueError('myTank class -> player value error.') # 坦克等级(初始0) self.level = 0 # 载入(两个tank是为了轮子特效) self.tank = pygame.image.load(self.Tanks[self.level]).convert_alpha() self.tank_0 = self.tank.subsurface((0, 0), (48, 48)) self.tank_1 = self.tank.subsurface((48, 0), (48, 48)) self.rect = self.tank_0.get_rect() # 保护罩 self.protected_mask = pygame.image.load( './images/others/protect.png').convert_alpha() self.protected_mask1 = self.protected_mask.subsurface((0, 0), (48, 48)) self.protected_mask2 = self.protected_mask.subsurface((48, 0), (48, 48)) # 坦克方向 self.direction_x, self.direction_y = 0, -1 # 不同玩家的出生位置不同 if player == 1: self.rect.left, self.rect.top = 3 + 24 * 8, 3 + 24 * 24 elif player == 2: self.rect.left, self.rect.top = 3 + 24 * 16, 3 + 24 * 24 else: raise ValueError('myTank class -> player value error.') # 坦克速度 self.speed = 3 # 是否存活 self.being = True # 有几条命 self.life = 3 # 是否处于保护状态 self.protected = False # 子弹 self.Bullet = Bullet()
class Player(object): def __init__(self, surface): self.gun_type = 1 self.player = pygame.image.load("res/player gunner" + str(self.gun_type) + ".png") self.bullet = Bullet(surface, self.gun_type) self.surface = surface self.player_posx = 100 self.player_posy = 400 self.check_change_gun = 1 self.check = False self.fire_bullet = False self.bullet_posx = 480 def render(self): self.surface.blit(self.player,(self.player_posx, 720 - self.player_posy)) if self.check == True: self.player = pygame.image.load("res/player gunner" + str(self.gun_type) + ".png") def change_weapon(self): if pygame.key.get_pressed()[K_z]: self.gun_type = 1 if pygame.key.get_pressed()[K_x]: self.gun_type = 2 def update(self): self.change_weapon() if self.check_change_gun != self.gun_type: self.check = True self.check_change_gun = self.gun_type else: self.check = False self.fire() self.bullet_posx = self.bullet.bullet_posx def fire(self): if pygame.key.get_pressed()[K_SPACE]: self.fire_bullet = True if self.fire_bullet == True: self.bullet.render() self.bullet.move() else: self.bullet.bullet_posx = 480 if self.bullet.check_bullet() == True: self.fire_bullet = False
def keyDown(self): if key == 's' or key == 'S': SpriteManager.spawn(Bullet(self.x, self.y, PVector(0, 10), 100)) if key == ' ' or key == 'w': SpriteManager.spawn(Bullet(self.x, self.y, PVector(0, -10), 100)) if keyCode == LEFT: self.left = True if keyCode == RIGHT: self.right = True if keyCode == UP: self.up = True if keyCode == DOWN: self.down = True
def shoot(self): #Test if should be shooting if self.shooting and not self.equipped_primary_weapon.get_reloading(): weapon_bullets_per_update = 3600 / int( self.equipped_primary_weapon.get_firerate()) start_pos = self.pos if self.direction > 0: start_pos = [ self.pos[0] + self.size[0] + self.equipped_primary_weapon.get_size()[0], self.pos[1] + self.arm_height ] else: start_pos = [ self.pos[0] - self.equipped_primary_weapon.get_size()[0] - 20, self.pos[1] + self.arm_height ] #Test for which type of weapon: 0 == SMG, 1 == Assault Rifle, 2 == LMG, 3 == Shotgun, 4 == Sniper, 5 == Pistol if self.equipped_primary_weapon.get_type( ) == 0 or self.equipped_primary_weapon.get_type( ) == 1 or self.equipped_primary_weapon.get_type() == 2: if self.loop_count % weapon_bullets_per_update < 1: bullet = Bullet(start_pos, [15, 3], (0, 0, 0), [15 * self.direction, 0.001], self.equipped_primary_weapon.get_damage()) self.equipped_primary_weapon.add_bullet(bullet) self.equipped_primary_weapon.remove_current_ammo(1) elif self.equipped_primary_weapon.get_type( ) == 4 or self.equipped_primary_weapon.get_type() == 5: if not self.equipped_primary_weapon.get_shot(): bullet = Bullet(start_pos, [20, 3], (0, 0, 0), [30 * self.direction, 0.001], self.equipped_primary_weapon.get_damage()) self.equipped_primary_weapon.add_bullet(bullet) self.equipped_primary_weapon.set_shot(True) self.equipped_primary_weapon.remove_current_ammo(1) elif self.equipped_primary_weapon.get_type() == 3: if not self.equipped_primary_weapon.get_shot(): for x in range(0, 10): bullet = Bullet( [start_pos[0], start_pos[1]], [15, 3], (0, 0, 0), [15 * self.direction, x - 5], self.equipped_primary_weapon.get_damage()) self.equipped_primary_weapon.add_bullet(bullet) self.equipped_primary_weapon.set_shot(True) self.equipped_primary_weapon.remove_current_ammo(1)
def shoot(): global power if power == 1: sound_pew.play() bullet = Bullet(player.rect.centerx, player.rect.centery) bullets.add(bullet) all_sprites.add(bullet) elif power == 2: sound_pew.play() bullet1 = Bullet(player.rect.centerx - 10, player.rect.centery) bullet2 = Bullet(player.rect.centerx + 10, player.rect.centery) bullets.add(bullet1) bullets.add(bullet2) all_sprites.add(bullet1) all_sprites.add(bullet2)
def __init__(self, name, screen_x, screen_y, frames_per_second): Game.__init__(self, name, screen_x, screen_y) ship_position = Point(config.SCREEN_X/2, config.SCREEN_Y/2) self.ship = Ship(ship_position, config.SHIP_INITIAL_DIRECTION, config.SHIP_COLOR) self.bullet = Bullet(Point(0,0), config.BULLET_RADIUS, 0, config.BULLET_COLOR) self.stars = [] for i in range(config.STAR_COUNT): s = Star() self.stars.append(s) self.rocks = [] for i in range(config.ROCK_COUNT): (x,y) = random.randint(0, config.SCREEN_X), random.randint(0, config.SCREEN_Y) p = Point(x,y) r = Rock(p, random.uniform(0, 360.0), config.ROCK_COLOR, (random.uniform(0.0, config.ROCK_MAX_ROTATION_SPEED) * random.uniform(-1.0,1.0)), random.randint(0, config.ROCK_MAX_SPEED)) self.rocks.append(r)
def createBullet(self): """If it is possible (no collision with terrain or bounds) creates a new bullet and returns it. Returns none if the bullet was not created""" bulletPos = self.currPos[:] d = self.CTRLS.index(self.faceDirection) bulletPos[d > 2] += (d - (1 if d < 3 else 4)) bullet = Bullet(self.map.currentBulletId, self.id, self.map, bulletPos[0], bulletPos[1], self.faceDirection) if(bullet.checkCollision() == True): return None else: self.map.currentBulletId += 1 self.bullets.append(bullet) return bullet
def player_shoot_bullet(player): Entities.player_bullet.append( Bullet([ player.draw_rect[0], player.draw_rect[1] - Constants.player_size, Constants.bullet_size, Constants.bullet_size ], [45, 50, 10, 50], Constants.bullet_image))
def shot(self): if self.shot_cooldown <= 0: if self.last_direction < 0: self.image = self.shot_left right = False bullet = Bullet("bullet", self.x, self.y + int(0.75 * self.height), right) else: self.image = self.shot_right right = True bullet = Bullet("bullet", self.x + self.width, self.y + int(0.75 * self.height), right) self.shot_cooldown = 20 return bullet else: return False
def __init__(self, x, y, speedX, speedY, throwDistance): Bullet.__init__(self, x, y, speedX, speedY, "items-1small.png", None, Rect(110, 120, 9, 11)) self.rect = Rect(x, y, 0, 0) self.speedX = speedX self.speedY = speedY # Important if you want pinpoint accuracy self.floatX = float(self.rect.x) self.floatY = float(self.rect.y) if throwDistance > MAX_THROW_DISTANCE: throwDistance = MAX_THROW_DISTANCE self.timeToStop = throwDistance / GRENADE_SPEED self.timeToBoom = TIME_TO_BOOM
def createBullet(self, bullets, allSprites): self.fireSound.play() bullet = Bullet(self.rect.x + (self.image.get_width() / 2), self.rect.y) bullets.add(bullet) allSprites.add(bullet) self.counter = 0
def __init__(self, surface): self.gun_type = 1 self.player = pygame.image.load("res/player gunner" + str(self.gun_type) + ".png") self.bullet = Bullet(surface, self.gun_type) self.surface = surface self.player_posx = 100 self.player_posy = 400 self.check_change_gun = 1 self.check = False self.fire_bullet = False self.bullet_posx = 480
class Asteroids(Game): def __init__(self, name, screen_x, screen_y, frames_per_second): Game.__init__(self, name, screen_x, screen_y) ship_position = Point(config.SCREEN_X/2, config.SCREEN_Y/2) self.ship = Ship(ship_position, config.SHIP_INITIAL_DIRECTION, config.SHIP_COLOR) self.bullet = Bullet(Point(0,0), config.BULLET_RADIUS, 0, config.BULLET_COLOR) self.stars = [] for i in range(config.STAR_COUNT): s = Star() self.stars.append(s) self.rocks = [] for i in range(config.ROCK_COUNT): (x,y) = random.randint(0, config.SCREEN_X), random.randint(0, config.SCREEN_Y) p = Point(x,y) r = Rock(p, random.uniform(0, 360.0), config.ROCK_COLOR, (random.uniform(0.0, config.ROCK_MAX_ROTATION_SPEED) * random.uniform(-1.0,1.0)), random.randint(0, config.ROCK_MAX_SPEED)) self.rocks.append(r) def game_logic(self, keys, newkeys): for s in self.stars: s.game_logic(keys, newkeys) self.ship.game_logic(keys, newkeys) for rock in self.rocks: rock.game_logic(keys, newkeys) if rock.isActive() == True: if self.ship.intersect(rock) == True: self.ship.set_inactive() if self.bullet.intersect(rock) == True: rock.set_inactive() self.bullet.set_inactive() if pygame.K_SPACE in newkeys: if self.ship.isActive() == True: points = self.ship.getPoints() self.bullet.fire(points[0], self.ship.rotation) self.bullet.game_logic(keys,newkeys) def paint(self, surface): self.screen.fill(config.BACKGROUND_COLOR) for s in self.stars: s.paint(surface) self.ship.paint(surface) self.bullet.paint(surface) for rock in self.rocks: rock.paint(surface)
class PlayerShip(pygame.sprite.Sprite): """The player's own ship""" def __init__(self, pos): """Initializes the player ship. arguments: pos -- a list consisting of x and y coordinate of player ship """ self.image = pygame.image.load("images/player-sprite.png") self.rect = self.image.get_rect() self.rect.move_ip(*pos) # The player bullet self.bullet = Bullet([0,0],"UP", isEnemyBullet=False) def update(self,keys): """ Update the position of player ship based keys pressed arguments: keys -- A list consisting of keys preseed """ if ( keys[pygame.K_LEFT] and self.rect.x > 30 ): self.rect.move_ip(-8,0) if ( keys[pygame.K_RIGHT] and self.rect.x < 550 ): self.rect.move_ip(8,0) def maybeShoot(self, keys): """ Shoots a bullet if the player pressed the trigger arguments: keys -- A list consisting of keys preseed """ if ( keys[pygame.K_SPACE] and self.bullet.bulletFlag <= 0): self.bullet = Bullet([self.rect.x+self.rect.width/2, self.rect.y-10],"UP") audio.fire() self.bullet.run()
def deserializeBullet(bullet): retbullet = Bullet(bullet['location'], bullet['bounds'], bullet['direction'], bullet['velocity']) retbullet.id = bullet['id'] return retbullet
# UPDATE GAME AStar(survivor, total_frames, FPS) Zombie.spawn(total_frames, FPS) survivor.movement() # RENDING ACTIONS # draws either a Floor or a Wall tile for tile in Tile.list_: if tile.type == Tile.Type.FLOOR: screen.blit(floor_img, (tile.x, tile.y)) elif tile.type == Tile.Type.WALL: screen.blit(wall_img, (tile.x, tile.y)) Bullet.update(screen) Zombie.update(screen, survivor) survivor.draw(screen) display_health_bar() pygame.display.flip() clock.tick(FPS) total_frames += 1 display_end_game_screen() sleep(PAUSE_TIME)
def shoot(self): bullet = Bullet() bullet.rect.center = self.rect.center bullet.speed = 5 return bullet
for event in pygame.event.get(): if event.type == QUIT: exit() if not player_ship.isDead(): sinD = math.sin(math.radians(player_ship.direction)) cosD = math.cos(math.radians(player_ship.direction)) keys = pygame.key.get_pressed() if keys[K_w] or keys[K_UP]: player_ship.move() moved = True if keys[K_a] or keys[K_LEFT]: player_ship.turn_left() if keys[K_d] or keys[K_RIGHT]: player_ship.turn_right() if keys[K_SPACE] and player_ship.delay<=0: bullet = Bullet((x + dimy*sinD, y-dimy*cosD), (BULLET_SIZE, BULLET_SIZE), player_ship.direction, (BULLET_SPEED*sinD, -BULLET_SPEED*cosD), BULLET_DURATION) #bullet = (x + dimy*sinD, y-dimy*cosD, player_ship.direction, BULLET_DURATION) bulletList.append(bullet) player_ship.delay = SHOOT_DELAY player_ship.move_from_force_in_direction(player_ship.acceleration, player_ship.direction+180) player_ship.update() for n in wall_list: if player_ship.rect.colliderect(n) and not player_ship.isDead(): player_ship.kill(DEATH_TIME) Display.death_animation(player_ship, debris, BLACK) camera.set_camera_loc((x, y)) camera.bound_camera(map_dimensions)
def Game(): #allows the gloabal variables to be changed global lastHit global done global isMuted #This funciton will define and call a funciton to get initals and print #them to the screen def endGame(): def askForInitials(): screen.fill((0,0,0)) myfont = pygame.font.Font(None, 36) text = myfont.render("Please enter you initials", True, (180,0,16)) text2= myfont.render((""+initials+blankInitials[count:]),True, (180,0,16)) text_rect = text.get_rect() text2_rect = text2.get_rect() screen.blit(text,(screen_width/2-text_rect.width/2,screen_height/2-text_rect.height/2\ -text_rect.height-text_rect.height-text_rect.height-text_rect.height\ -text_rect.height)) screen.blit(text2,(screen_width/2-text2_rect.width/2,screen_height/2-text_rect.height/2\ -text_rect.height-text_rect.height-text_rect.height-text_rect.height)) pygame.display.flip() #Sets a flag for the while loop playAgain=False #sets variables for the intitials and blank spots that will get printed to #the screen when getting initials blankInitials="---" initials="" #Sets a flag for the loop that will allow it to be ran three times #This is needed because while loops work great with stopping pygame #code so nothing else runs(That is why a for loop didnt work) initialsEntered=False count=0 #Loops to ask for initials and will only take the lower case letters #with the if for the ascii key numbers while not(initialsEntered): screen.fill((0,0,0)) askForInitials() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key>=97 and event.key<=122: initials+=pygame.key.name(event.key).upper() count+=1 if count==3: askForInitials() initialsEntered=True break #Opens the HighScore file for reading highScore=open('HighScore.txt','r') fileLine=0 firstline="" highScores={} #Reads in the file for line in highScore: #Reads in the header line if(fileLine==0): firstline=line fileLine+=1 continue #Gets the name,level, and score of the players temp=[] #splits the info into 3 different parts then save them to #the dictionary split=line.split("\t\t") temp.append(split[1]) temp.append(split[2]) temp.append(int(split[3])) highScores[split[0]]=temp #closes the read on the highscore list highScore.close() playerStats=[] #makes a list of the current player stats so they can be comparied against #the list playerStats.append(initials) playerStats.append(str(player.level)) playerStats.append(player.pikaScore) #goes through the dictionary and sees where the current player needs to get added #then will bump the person at the spot move down one for x in range((len(highScores))): if (highScores[str(len(highScores)-x)+")"][2]<player.pikaScore): highScores[str(len(highScores)-x+1)+")"]=highScores[str(len(highScores)-x)+")"] highScores[str(len(highScores)-x)+")"]=playerStats #Opens a high score list for writing that will delete the old list #then replace it with the new names that go on it highScore=open('HighScore.txt','w') highScore.write(firstline) for x in range(1,11): highScore.write(str(x)+")\t\t"+highScores[str(x)+")"][0]+"\t\t"\ +highScores[str(x)+")"][1]+"\t\t"+str(highScores[str(x)+")"][2])+"\t\t\n") #closes the high score list highScore.close() while playAgain==False: myfont = pygame.font.Font(None, 36) #makes four lines to print to the screen text = myfont.render("Game Over", True, (180,0,16)) text1 = myfont.render(("Level: "+str(player.level)), True, (180,0,16)) text2 = myfont.render(("Score: "+str(player.pikaScore)), True, (180,0,16)) text3 = myfont.render("Press ENTER to play again", True, (180,0,16)) text_rect = text.get_rect() text1_rect = text1.get_rect() text2_rect = text2.get_rect() text3_rect = text3.get_rect() text1x = screen.get_width()/2 - text1_rect.width/2 text1y = screen.get_height()/2 - text1_rect.height textx=(text1x+text1_rect.width/2)-text_rect.width/2 texty=text1y-text_rect.height text2x=(text1x+text1_rect.width/2)-text2_rect.width/2 text2y=text1y+text1_rect.height text3x=(text1x+text1_rect.width/2)-text3_rect.width/2 text3y=text2y+text2_rect.height screen.blit(text, (textx,texty)) screen.blit(text1, (text1x,text1y)) screen.blit(text2, (text2x,text2y)) screen.blit(text3, (text3x,text3y)) pygame.display.flip() for event in pygame.event.get(): if event.type == pygame.QUIT: # If user clicked close global done done=True # Flag that shows game is over playAgain=True #Flag that they entered something to get out of loop if event.type == pygame.KEYDOWN: if event.key==pygame.K_RETURN: playAgain=True #Flag to show they want to play again if done==False: Game() #Prints instructions to the screen def instructions(): global done myfont = pygame.font.Font(None, 32) text1 = myfont.render("Pikachu vs. Zubats", True, (180,0,16)) text2 = myfont.render("Instructions", True, (180,0,16)) text3 = myfont.render("Arrow Keys: Move in Direction", True, (180,0,16)) text4 = myfont.render("Space Bar: Shoots lightning bolt", True, (180,0,16)) text5 = myfont.render("Press ENTER to continue", True, (180,0,16)) text1_rect = text1.get_rect() text2_rect = text2.get_rect() text3_rect = text3.get_rect() text4_rect = text4.get_rect() text5_rect = text5.get_rect() text4x=screen_width/2-text4_rect.width/2 text4y=screen_height/2-text4_rect.height/2 text3x=screen_width/2-text3_rect.width/2 text3y=screen_height/2-text3_rect.height/2-text4_rect.height text2x=screen_width/2-text2_rect.width/2 text2y=screen_height/2-text2_rect.height/2-text4_rect.height-text3_rect.height text5x=screen_width/2-text5_rect.width/2 text5y=screen_height/2-text5_rect.height/2+text4_rect.height+text4_rect.height text1x=screen_width/2-text1_rect.width/2 text1y=screen_height/2-text1_rect.height/2-text4_rect.height-text3_rect.height-text2_rect.height\ -text1_rect.height screen.blit(text1, (text1x,text1y)) screen.blit(text2, (text2x,text2y)) screen.blit(text3, (text3x,text3y)) screen.blit(text4, (text4x,text4y)) screen.blit(text5, (text5x,text5y)) pygame.display.flip() while True: goToGame=False for event in pygame.event.get(): if event.type == pygame.QUIT: # If user clicked close done=True # Flag that shows game is over goToGame=True if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: goToGame=True if goToGame: break # Initialize Pygame pygame.init() # Set the height and width of the screen screen_width=700 screen_height=500 screen=pygame.display.set_mode([screen_width,screen_height]) #Sets the game window title pygame.display.set_caption("Pikachu vs. Zubats") #calls the instructions which will print the instructions to the screen instructions() #creats the backgound then adds it to a background list background = Background() background.rect.width=screen_width background.rect.height=screen_height background.rect.y=-150 background.rect.x=-150 backgroundPlain = pygame.sprite.RenderPlain() backgroundPlain.add(background) #draws the background to the screen backgroundPlain.draw(screen) # This is a list of every sprite. all_sprites_list = pygame.sprite.RenderPlain() playerList= pygame.sprite.RenderPlain() # Create a pikachu player player = Pikachu() player.rect.x=(screen_width/2)-(player.rect.width/2) player.rect.y=(screen_height/2)-(player.rect.height/2) all_sprites_list.add(player) playerList.add(player) # Used to manage how fast the screen updates clock=pygame.time.Clock() #Creats a sprite list that will then be able to loop through bulletListRight= pygame.sprite.RenderPlain() bulletListLeft= pygame.sprite.RenderPlain() zubats=pygame.sprite.RenderPlain() while True: #Counts the number of zubats that were sent out in the current level numOfZubats=0 #The max number of zubats for the level maxZubatsPerLevel=random.randrange((4*player.level),(7*player.level)) #The to wait between when zubats will be sent out waitTime=random.randrange(10)/float(player.level) #the time on the clock to know when to send out the first zubat oldTime=time.clock() #Prints the level and then if repels effect wore off when the spawn time #is 0 myfont = pygame.font.Font(None, 36) text = myfont.render(("Level "+str(player.level)), True, (180,0,16)) text2 = myfont.render(("Repels' effect wore off..."), True, (180,0,16)) text_rect = text.get_rect() text_rect2=text2.get_rect() textx = screen.get_width()/2 - text_rect.width/2 texty = screen.get_height()/2 - text_rect.height/2 text2x = screen.get_width()/2 - text_rect2.width/2 text2y = screen.get_height()/2 - text_rect.height/2+text_rect.height screen.blit(text, (textx,texty)) if waitTime==0: screen.blit(text2, (text2x,text2y)) pygame.display.flip() time.sleep(2) # -------- Main Program Loop ----------- while done==False: myfont = pygame.font.Font(None, 24) text = myfont.render(("Score: "+str(player.pikaScore))\ , True, (180,0,16)) text_rect = text.get_rect() textx = screen_width-text_rect.width texty = 1 screen.blit(text, (textx,texty)) pygame.display.flip() for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done=True # Flag that we are done so we exit this loop if event.type == pygame.KEYDOWN: #The first four control the speed of the player based on direction key if event.key == pygame.K_LEFT: player.changespeed(-4,0) lastHit=0 if event.key == pygame.K_RIGHT: player.changespeed(4,0) lastHit=1 if event.key == pygame.K_UP: player.changespeed(0,-3) if event.key == pygame.K_DOWN: player.changespeed(0,3) #Checks to see if space is pressed, if it is and the number of bullets in the direct is not #already maxed out will shoot a bullet in the last direction pikachu was facing if event.key == pygame.K_SPACE: bullet=Bullet() if lastHit==1: bullet.speed=(5+(player.x_speed/2.0)) bullet.rect.x = player.rect.x+player.rect.width bullet.rect.y = player.rect.y+(player.rect.height/4)+2 if len(bulletListRight)<5: all_sprites_list.add(bullet) bulletListRight.add(bullet) else: bullet.speed=(-5+(player.x_speed/2.0)) bullet.rect.x = player.rect.x-10 bullet.rect.y = player.rect.y+(player.rect.height/2) if len(bulletListLeft)<5: all_sprites_list.add(bullet) bulletListLeft.add(bullet) #Test code to check if zubats are working, or code if you just want to make the current level #harder it will just add more zubats at a random point on the screen if event.key == pygame.K_LALT: z=Zubat() z.rect.x = random.randrange(screen_width) z.rect.y = random.randrange(screen_height) zubats.add(z) all_sprites_list.add(z) # Reset speed of pikachu when key is released if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: player.changespeed(4,0) if event.key == pygame.K_RIGHT: player.changespeed(-4,0) if event.key == pygame.K_UP: player.changespeed(0,3) if event.key == pygame.K_DOWN: player.changespeed(0,-3) #checks to see if the game is paused or not and then does #the oppisite, also it pauses the music while paused if event.key == pygame.K_p: pygame.mixer.music.pause() myfont = pygame.font.Font(None, 36) text = myfont.render(("Pause"), True, (180,0,16)) text_rect = text.get_rect() textx = screen.get_width()/2 - text_rect.width/2 texty = screen.get_height()/2 - text_rect.height/2 screen.blit(text, (textx,texty)) pygame.display.flip() while True: unpause=False for event in pygame.event.get(): if event.type == pygame.QUIT: # If user clicked close done=True # Flag that shows game is over unpause=True if event.type == pygame.KEYUP: if event.key == pygame.K_p: unpause=True if unpause: pygame.mixer.music.unpause() break #Checks to see if the music is muted or unmuted then does the oppiset if event.key == pygame.K_m: if isMuted: pygame.mixer.music.play(-1,.5) isMuted=False else: pygame.mixer.music.stop() isMuted=True #Spawns new zubats if the number of zubats is under the level max if(numOfZubats<maxZubatsPerLevel): currentTime=time.clock()-oldTime #Checks to see if the wait time was passed if it was will spawn a zubat on the edge of the screen if(currentTime>waitTime): #sets the old time to the current time on the clock oldTime=time.clock() z=Zubat() #decides what side of the screen to spawn from temp=random.randrange(2) if(temp==0): z.rect.x=0-z.rect.width z.rect.y = random.randrange(screen_height) else: z.rect.x=screen_width z.rect.y = random.randrange(screen_height) zubats.add(z) all_sprites_list.add(z) numOfZubats+=1 #Checks the position of Pikachu, when Pikachu goes #off the screen he will loop around to the opposite end of the screen for player in playerList: if(player.rect.x <0-player.rect.width): player.rect.x=screen_width if(player.rect.x >screen_width): player.rect.x=0-player.rect.width if(player.rect.y < 0-player.rect.height): player.rect.y = screen_height if(player.rect.y > screen_height): player.rect.y=0-player.rect.height #Loops through zubat to move them and check if they hit pikachu or get hit by a lightning bolt for zubat in zubats: #checks the x postion of zubat and pikachu and moves zubat towards pikachu #also sets the speed which is used to flip the zubat picture opsite direction if(zubat.rect.x+(zubat.rect.width/2)>player.rect.x+(player.rect.width/2)): zubat.rect.x-=2 zubat.speed=-1 elif(zubat.rect.x+(zubat.rect.width/2)<player.rect.x+(player.rect.width/2)): zubat.rect.x+=2 zubat.speed=1 #checks the y postion of zubat and pikachu and moves zubat towards pikachu if(zubat.rect.y+(zubat.rect.height/2)>player.rect.y+(player.rect.height/2)): zubat.rect.y-=1 elif(zubat.rect.y+(zubat.rect.height/2)<player.rect.y+(player.rect.height/2)): zubat.rect.y+=1 #Checks to see if zubat kills(hit) pikachu if(pygame.sprite.collide_circle(player,zubat)): #empyt the sprites list so nothing is on the screen all_sprites_list.empty() endGame() done=True #These two loops checks to see if a zubat is hit by a bullet going either direction for bullet in bulletListRight: if pygame.sprite.collide_rect(bullet,zubat): bulletListRight.remove(bullet) zubats.remove(zubat) all_sprites_list.remove(bullet) all_sprites_list.remove(zubat) score=random.randrange(75,125) player.pikaScore+=score for bullet in bulletListLeft: if pygame.sprite.collide_rect(bullet,zubat): bulletListLeft.remove(bullet) zubats.remove(zubat) all_sprites_list.remove(bullet) all_sprites_list.remove(zubat) score=random.randrange(75,125) player.pikaScore+=score #Calls the update to move them and check to see if the picture needs flipping zubat.selectPicture() #These two for loops move the bullets o for bullet in bulletListRight: bullet.rect.x += bullet.speed if bullet.rect.x > screen_width: bulletListRight.remove(bullet) for bullet in bulletListLeft: bullet.rect.x += bullet.speed if bullet.rect.x < 0-(bullet.rect.width): bulletListLeft.remove(bullet) # Clear the screen screen.fill((0,0,0)) player.selectPicture() backgroundPlain.draw(screen) # Draw all the spites all_sprites_list.draw(screen) # Limit to 20 frames per second clock.tick(20) # Updates Screen. pygame.display.flip() if(len(zubats)==0 and numOfZubats==maxZubatsPerLevel): break if(done==True): break else: player.level+=1 pygame.quit()
def updateEvents(self): #movement if self.event1 == True: #stop from leaving window #left edge if self.rect.left > 0: self.rect.x += self.xspeed elif self.xspeed < 0: self.stopX() self.rect.left = 0 #right edge if self.rect.right < WINDOWWIDTH: self.rect.x += self.xspeed elif self.xspeed > 0: self.stopX() self.rect.right = WINDOWWIDTH #top edge if self.rect.top > 0: self.rect.y += self.yspeed elif self.yspeed < 0: self.stopY() self.rect.top = 0 #bottom edge if self.rect.bottom < WINDOWHEIGHT: self.rect.y += self.yspeed elif self.yspeed > 0: self.stopY() self.rect.bottom = WINDOWHEIGHT #shooting (lvl 3) if self.event2 == True: #shoot a bullet if self.timer == 0: self.timer += 1 bullet = Bullet(BLACK, 4, 8) bullet.convertToPic(BULLET_DGREY, 1) bullet.load(self, self.bullets) bullet.aim(90, 1) bullet.fire(18) #sprayer (lvl 2) if self.event3 == True: if self.timer == 0: self.timer += 1 flame = FlameV2(YELLOW, 6, 6, 24, 24) flame.load(self, self.bullets, 'N') flame.aim(90, 30) flame.fire(5) flame.wiggle = True #--1 flame = FlameV2(YELLOW, 6, 6, 24, 24) flame.load(self, self.bullets, 'N') flame.aim(100, 30) flame.fire(5) #--2 flame = FlameV2(YELLOW, 6, 6, 24, 24) flame.load(self, self.bullets, 'N') flame.aim(80, 30) flame.fire(5) #--3 flame = FlameV2(YELLOW, 6, 6, 24, 24) flame.load(self, self.bullets, 'N') flame.aim(95, 15) flame.fire(5) flame.wiggle = True #--4 flame = FlameV2(YELLOW, 6, 6, 24, 24) flame.load(self, self.bullets, 'N') flame.aim(85, 15) flame.fire(5) flame.wiggle = True #--5 #missile (lvl 2) if self.event4 == True: if self.timer == 0: self.timer += 1 missile = MissileV3(windowSurface, MISSLE_BASIC, -90) missile.setUpdateGroup( self.bullets ) self.bullets.add( missile ) missile.setCenter(self.rect.center) missile.setDir( random.randint(87,93) ) missile.setSpeed( random.randint(300,500)/100 ) missile.setTrailStrength(1) #sprayer (lvl 3) if self.event5 == True: if self.timer == 0: self.timer += 1 #shoot 5 different bullets side = random.randint(8,10) bullet = Bullet(DDBLUE, side,side) bullet.load(self, self.bullets) bullet.aim(90, 5) bullet.yaccel = 0.35 bullet.special_01() bullet.fire(random.randint(10,14)) #--1 side = random.randint(8,10) bullet = Bullet(DDBLUE, side,side) bullet.load(self, self.bullets) bullet.aim(87, 4) bullet.yaccel = 0.35 bullet.special_01() bullet.fire(random.randint(10,14)) #--2 side = random.randint(8,10) bullet = Bullet(DDBLUE, side,side) bullet.load(self, self.bullets) bullet.aim(83, 3) bullet.yaccel = 0.35 bullet.special_01() bullet.fire(random.randint(10,14)) #--3 side = random.randint(8,10) bullet = Bullet(DDBLUE, side,side) bullet.load(self, self.bullets) bullet.aim(93, 4) bullet.yaccel = 0.35 bullet.special_01() bullet.fire(random.randint(10,14)) #--4 side = random.randint(8,10) bullet = Bullet(DDBLUE, side,side) bullet.load(self, self.bullets) bullet.aim(97, 3) bullet.yaccel = 0.35 bullet.special_01() bullet.fire(random.randint(10,14)) #--5 #update target group for current minion if self.currMinion == None and self.baddies != None: self.currMinion.setTargetGroup(self.baddies)
def shoot(self, bullets, baddies, fps): # fyi... # Assuming fps=60 for comments mentioning # how long the alarm is set for. #shooter if self.selected == 0: #locked if self.unlocked[0] == 0: print("Warning: shooter is not unlocked yet") return -1 #lvl 1 elif self.unlocked[0] == 1: #allow a shot every 1/4 sec self.alarm = int(fps/4) #shoot a bullet if self.timer == 0: self.timer += 1 bullet = Bullet(DGREY, 4, 8) bullet.convertToPic(BULLET_LGREY, 1) bullet.load(self, bullets) bullet.aim(90, 5) bullet.fire(6) #lvl 2 elif self.unlocked[0] == 2: #allow a shot every 1/fps sec self.alarm = 1 #shoot a bullet if self.timer == 0: self.timer += 1 bullet = Bullet(DDGREY, 4, 8) bullet.convertToPic(BULLET_GREY, 1) bullet.load(self, bullets) bullet.aim(90, 10) bullet.fire(10) #lvl 3 elif self.unlocked[0] == 3: #update bullet group for self self.bullets = bullets #allow a shot every 1/30 sec self.alarm = int(fps/30) #allow holding down to keep shooting self.event2 = True else: print("Error: player is trying to shoot with an incorrect upgrade selection") return -2 #missile elif self.selected == 1: #locked if self.unlocked[1] == 0: print("Warning: missile is not unlocked yet") return -1 #lvl 1 elif self.unlocked[1] == 1: #allow a shot every 1 sec self.alarm = int(fps) #shoot a missile if self.timer == 0: self.timer += 1 missile = MissileV3(windowSurface, MISSLE_BASIC, -90) missile.setUpdateGroup( bullets ) bullets.add( missile ) missile.setCenter(self.rect.center) missile.setDir( random.randint(87,93) ) missile.setSpeed( random.randint(300,500)/100 ) missile.setTrailStrength(1) #lvl 2 elif self.unlocked[1] == 2: #update bullet group for self self.bullets = bullets #allow a shot every 1/2 sec self.alarm = int(fps/2) #allow holding down to keep launching self.event4 = True #lvl 3 elif self.unlocked[1] == 3: #allow a small missile every 1 sec self.alarm = int(fps*1) #25% chance for a large missile # ... #shoot 3 missiles if self.timer == 0: self.timer += 1 #seeking bounds bounds = [0,WINDOWWIDTH,self.rect.y,0] special = random.randint(1,4) if special == 1: # 1 big seek missile missile = MissileV3(windowSurface, MISSLE_HEAVY, -90) missile.setUpdateGroup( bullets ) bullets.add( missile ) missile.setCenter(self.rect.center) missile.setDir( 90 ) missile.setSpeed( random.randint(200,400)/100 ) missile.seek(baddies, 2, bounds) missile.setTrailStrength(2) # 2 small seek missiles missile = MissileV3(windowSurface, MISSLE_BASIC, -90) missile.setUpdateGroup( bullets ) bullets.add( missile ) missile.setCenter(self.rect.center) missile.setDir( random.randint(82,88) ) missile.setSpeed( random.randint(400,600)/100 ) missile.seek(baddies, 5, bounds) missile.setTrailStrength(0) missile = MissileV3(windowSurface, MISSLE_BASIC, -90) missile.setUpdateGroup( bullets ) bullets.add( missile ) missile.setCenter(self.rect.center) missile.setDir( random.randint(92,98) ) missile.setSpeed( random.randint(400,600)/100 ) missile.seek(baddies, 5, bounds) missile.setTrailStrength(0) else: print("Error: player is trying to shoot with an incorrect upgrade selection") return -2 #sprayer elif self.selected == 2: #locked if self.unlocked[2] == 0: print("Warning: sprayer is not unlocked yet") return -1 #lvl 1 elif self.unlocked[2] == 1: #allow a shot every 1 sec self.alarm = int(fps) #shoot 3 bullets, 4 fragments if self.timer == 0: self.timer += 1 bullet = Bullet(DDGREY, 7, 7) bullet.load(self, bullets) bullet.aim(90, 4) bullet.fire(16) #--1 bullet = Bullet(DDGREY, 7, 7) bullet.load(self, bullets) bullet.aim(95, 6) bullet.fire(15) #--2 bullet = Bullet(DDGREY, 7, 7) bullet.load(self, bullets) bullet.aim(85, 6) bullet.fire(15) #--3 #lvl 2 elif self.unlocked[2] == 2: #update bullet group for self self.bullets = bullets #allow a shot every 1/10 sec self.alarm = int(fps/10) #allow holding down to keep shooting self.event5 = True #lvl 3 elif self.unlocked[2] == 3: #update bullet group for self self.bullets = bullets #allow a shot every 1/15 sec self.alarm = int(fps/15) #allow holding down to keep shooting self.event3 = True else: print("Error: player is trying to shoot with an incorrect upgrade selection") return -2 #minions elif self.selected == 3: #locked if self.unlocked[3] == 0: print("Warning: minions are not unlocked yet") return -1 #lvl 1 elif self.unlocked[3] == 1: #allow a shot every 0.5 sec self.alarm = int(fps/2) #create a random suicide minion if self.timer == 0: self.timer += 1 suiciders = [MINION_1,MINION_2,MINION_3] minion = Minion(windowSurface, random.choice(suiciders), -90) minion.init() #place minion randomly in front of self # N,E,S,W bounds = [self.rect.centery-80,self.rect.centerx+50,self.rect.y-10,self.rect.centerx-50] cx = random.randint(bounds[3],bounds[1]) cy = random.randint(bounds[0],bounds[2]) minion.setCenter( (cx,cy) ) #set type, update group, target group minion.type = 1 minion.setUpdateGroup(bullets) minion.setTargetGroup(baddies) #load minion into update group bullets.add(minion) #set current minion self.currMinion = minion #lvl 2 elif self.unlocked[3] == 2: #allow a shot every 1/6 sec self.alarm = int(fps/6) #create a shooter minion if self.timer == 0: self.timer += 1 #only if fewer than 2 shooter-minions are alive if len(self.pop2) < 2: # bounds: N,E,S,W bounds = [self.rect.centery-35,self.rect.centerx+50,self.rect.y+15,self.rect.centerx-50] cx = random.randint(bounds[3],bounds[1]) cy = random.randint(bounds[0],bounds[2]) #pick a side this minion will be on (right/left) if cx >= WINDOWWIDTH/2: pic = MINION_4 #right side = 1 else: pic = MINION_5 #left side = 2 #create a shooter minion minion = Minion(windowSurface, pic, -90) minion.init() minion.side = side #place minion randomly in front of self minion.setCenter( (cx,cy) ) #set type, alarm, update group, target group minion.type = 2 minion.alarm = 60*2 minion.setUpdateGroup(bullets) minion.setTargetGroup(baddies) #load minion into update group, pop2 bullets.add(minion) self.pop2.append(minion) #set current minion self.currMinion = minion #lvl 3 elif self.unlocked[3] == 3: #allow a shot every 0.25 sec self.alarm = int(fps/4) #create an army minion if self.timer == 0: self.timer += 1 #only if fewer than 8 army-minions are alive if len(self.pop3) < 8: #create a random army minion armies = { 1 : ARMY_1, #flames 2 : ARMY_2, #missiles 3 : ARMY_3 } #lasers choice = random.randint(1,3) minion = Minion(windowSurface, armies[choice], -90) minion.init() # bounds: N,E,S,W bounds = [self.rect.centery-35,self.rect.centerx+50,self.rect.y+15,self.rect.centerx-50] cx = random.randint(bounds[3],bounds[1]) cy = random.randint(bounds[0],bounds[2]) #place minion randomly in front of self minion.setCenter( (cx,cy) ) #set type, health, subtype, alarm, update group, target group, dir minion.type = 3 minion.health = 40 if choice == 1: minion.alarm = 60/6 minion.subtype = "red" elif choice == 2: minion.alarm = 60*2 minion.subtype = "blue" elif choice == 3: minion.alarm = 60/3 minion.subtype = "green" minion.setUpdateGroup(bullets) minion.setTargetGroup(baddies) minion.setDir(90) #load minion into update group, pop3 bullets.add(minion) self.pop3.append(minion) #set current minion self.currMinion = minion else: print("Error: player is trying to shoot with an incorrect upgrade selection") return -2 #bombs (NOTE*** attractor and reflector do not attract/reflect enemies) elif self.selected == 4: #locked if self.unlocked[4] == 0: print("Warning: bombs are not unlocked yet") return -1 #lvl 1 elif self.unlocked[4] == 1: #allow a shot every 1/2 sec self.alarm = int(fps/2) #throws 1 bomb if self.timer == 0: self.timer += 1 bomb = Bomb(windowSurface, BOMB_SMALL) bomb.initVars() bomb.setCenter(self.rect.center) bomb.setUpdateGroup(bullets) bomb.setDensity(15) bomb.setSmoke(5) bomb.setAmt(10) bullets.add(bomb) bomb.dir = random.randint(60, 120) bomb.speed = random.randint(115,190)/10 bomb.accel = -random.randint(5,7)/10 #lvl 2 elif self.unlocked[4] == 2: #allow a shot every 2 sec self.alarm = int(fps*2) #throws 1 reflector if self.timer == 0: self.timer += 1 bomb = Bomb(windowSurface, BOMB_REFLECT) bomb.initVars() bomb.setCenter(self.rect.center) bomb.setUpdateGroup(bullets) bullets.add(bomb) bomb.dir = 90 bomb.speed = 2 bomb.setReflect(0.8) #lvl 3 elif self.unlocked[4] == 3: #allow a shot every 4 sec self.alarm = int(fps*4) #throws 1 attractor if self.timer == 0: self.timer += 1 #seeking bounds bounds = [0,WINDOWWIDTH,self.rect.y,0] #attractor (also launches missiles) bomb = Bomb(windowSurface, BOMB_ATTRACT) bomb.initVars() bomb.setCenter(self.rect.center) bomb.setUpdateGroup(bullets) bullets.add(bomb) bomb.dir = 90 bomb.speed = 2 bomb.setAttract(0.7, baddies, bounds) else: print("Error: player is trying to shoot with an incorrect upgrade selection") return -2 #error else: print("Error: player is trying to shoot with an incorrect weapon selection") return -2 #if all goes well, return 0 return 0
class PlayerBike(DirectObject): def __init__(self, cTrav): #create speed vars self.max_vel = 35 self.accel = 2 self.current_vel = 0 self.cTrav = cTrav self.weapon = 0 #vars for jumping self.tempHeading = 0 self.temp_vel = 0 self.count = 0 self.first_time = False self.jump = False self.dz = 0 #set HP self.hp = 10 #invincible check self.invin = False self.invinCount = 0 #Shotgun check self.shotgun = False self.p_up_timer = 0 #healing powerup self.health_up = False #load all sound files self.singleShot = base.loader.loadSfx('M4A1.mp3') #create empty list for bullets and a task for updating the positions self.bullet = Bullet(cTrav) self.spreadshot = weapon1(cTrav) self.explode = weapon2(cTrav) self.wallshot = weapon3(cTrav) taskMgr.add(self.bullet.update, "bulletTask") taskMgr.add(self.spreadshot.update, "bulletTask") taskMgr.add(self.updatePowerup, "powerupTask") #load the bike actor and parent it to a physics node self.bike = Actor("moto2_actor.egg", {"move":"moto2_moveAnim.egg", "turnL":"moto2_blahblah.egg"}) #self.bike.setScale(.5) #self.bike.setH(180) self.bike.reparentTo(render) self.dummy = Actor("temp_bullet.egg") self.dummy.reparentTo(render) #setup a move task for the bike taskMgr.add(self.move, "moveTask") self.prevTime = 0 self.isMoving = False #setup a shoot task for the bike taskMgr.add(self.shoot, "shootTask") self.shotClock = 25 # for shooting anim self.isShooting = False #setup a moving dictionary self.moveMap = {"left":0, "right":0, "forward":0} #setup a shoot check self.shootCheck = 0 #setup a wall collision check self.wallCheck = False #pusher collision spheres #front collisionPusher = CollisionHandlerPusher() collisionPusher.setInPattern("p_bike-%in") cPushSphere = CollisionSphere((0,3.5,2),2) cNode1 = CollisionNode("p_bike_push") cNode1.addSolid(cPushSphere) cNode1.setIntoCollideMask(0x10) cNode1.setFromCollideMask(0x1) self.cNodePath1 = self.bike.attachNewNode(cNode1) #self.cNodePath1.show() collisionPusher.addCollider(self.cNodePath1, self.bike) self.cTrav.addCollider(self.cNodePath1, collisionPusher) #middle cPushSphere = CollisionSphere((0,0,2),2) cNode2 = CollisionNode("p_bike_push") cNode2.addSolid(cPushSphere) cNode2.setIntoCollideMask(0x10) cNode2.setFromCollideMask(0x1) self.cNodePath2 = self.bike.attachNewNode(cNode2) #self.cNodePath2.show() collisionPusher.addCollider(self.cNodePath2, self.bike) self.cTrav.addCollider(self.cNodePath2, collisionPusher) #back cPushSphere = CollisionSphere((0,-2.5,2),2) cNode3 = CollisionNode("p_bike_push") cNode3.addSolid(cPushSphere) cNode3.setIntoCollideMask(0x10) cNode3.setFromCollideMask(0x1) self.cNodePath3 = self.bike.attachNewNode(cNode3) #self.cNodePath3.show() collisionPusher.addCollider(self.cNodePath3, self.bike) self.cTrav.addCollider(self.cNodePath3, collisionPusher) #collision rays for faux-gravity #front wheel lifter = CollisionHandlerFloor() lifter.setMaxVelocity(9.8) cRay1 = CollisionRay(0, 3, 3, 0, 0, -1) cRayNode1 = CollisionNode('playerRay') cRayNode1.addSolid(cRay1) cRayNode1.setIntoCollideMask(BitMask32.allOff()) cRayNode1.setFromCollideMask(2) cRayNodePath1 = self.bike.attachNewNode(cRayNode1) #cRayNodePath1.show() self.cTrav.addCollider(cRayNodePath1, lifter) lifter.addCollider(cRayNodePath1, self.bike) #setup and parent spotlights to the player self.spotlight = Spotlight("headlight") self.spotlight.setColor((1, 1, 1, 1)) self.spotlight.setAttenuation(Point3(0,0,.001)) lens = PerspectiveLens() #can change size of cone lens.setFov(20) self.spotlight.setLens(lens) self.spotlight.setExponent(100) lightNode = self.bike.attachNewNode(self.spotlight) render.setLight(lightNode) def setDirection(self, key, value): #set the direction as on or off self.moveMap[key] = value def setShoot(self, value): self.shootCheck = value #print("set shoot =", self.shootCheck) def shoot(self, task): #check if space bar is pressed if self.shootCheck: #Check which weapon is being used #standard weapon if self.weapon == 0: #check if able to shoot if self.shotClock >= 25: #print("Shooting a bullet!") self.singleShot.play() self.bullet.createBullet(self.bike) self.shotClock = 0 else: self.shotClock += 1 #Weapon 2 - Spreadshot/Shotgun elif self.weapon == 1: if self.shotClock >= 40: #print("Shooting a bullet!") self.singleShot.play() self.spreadshot.createBullet(self.bike) self.shotClock = 0 else: self.shotClock += 1 else: self.shotClock += 1 return Task.cont def updatePowerup(self, task): #check powerup timers if self.invin == True: self.invinCount += 1 #print self.invinCount if self.invinCount == 400: self.invin = False self.invinCount = 0 if self.shotgun == True: self.weapon = 1 self.p_up_timer += 1 #print self.p_up_timer if self.p_up_timer == 500: self.shotgun = False self.weapon = 0 if self.health_up == True: self.hp += 2 if self.hp > 10: self.hp = 10 self.health_up = False return Task.cont def move(self, task): elapsed = task.time - self.prevTime self.dummy.setPos(self.bike.getX(), self.bike.getY(), 0.0) #keep track of all the bike's previous Pos and Hpr prevX = self.bike.getX() prevY = self.bike.getY() prevZ = self.bike.getZ() prevH = self.bike.getH() prevP = self.bike.getP() prevR = self.bike.getR() #check key map #check if at jump height if prevZ >= 2.00: #set jump check self.jump = True #check for when temp_vel needs to be increased instead of decreased if self.first_time == False: self.temp_vel -= 9.8 if self.temp_vel <= 0 and self.first_time == False: self.first_time = True self.temp_vel += 9.8 elif self.first_time == True: self.temp_vel += 9.8 #make sure temp_vel doesn't increase too much if self.temp_vel > self.current_vel: self.temp_vel = self.current_vel #calculate dist for dy and dx normally, then do trig for dz dist = (self.current_vel + 11) * elapsed angle = deg2Rad(self.bike.getH()) dy = dist * -math.cos(angle) dx = dist * math.sin(angle) self.dz = math.sqrt((dy*dy)+(dx*dx)) #debug prints """print('new') print('dy', dy) print('dx', dx) print('dz', dz) print('angle', angle) print('bike heading', self.bike.getH()) print('bike x', self.bike.getX()) print('bike y', self.bike.getY()) print('temp_vel', self.temp_vel)""" #use a count to determine when to decrease or increase the bike's Z if self.count < 30: self.bike.setPos(self.bike.getX() - dx, self.bike.getY() - dy, self.bike.getZ() + self.dz) else: self.bike.setPos(self.bike.getX() - dx, self.bike.getY() - dy, self.bike.getZ() - self.dz) self.count += 1 else: #reset counters used in jumping self.first_time = False self.count = 0 #check if turning if self.moveMap['left']: self.bike.setH(self.bike.getH() + elapsed * 150) if self.moveMap['right']: self.bike.setH(self.bike.getH() - elapsed * 150) #check keymap for forward motion #accelerate if self.moveMap['forward']: #print(prevZ) self.current_vel += self.accel self.temp_vel = self.current_vel if(self.current_vel > self.max_vel): self.current_vel = self.max_vel dist = self.current_vel * elapsed angle = deg2Rad(self.bike.getH()) dx = dist * math.sin(angle) dy = dist * -math.cos(angle) if self.jump == True: self.bike.setPos(self.bike.getX() - dx, self.bike.getY() - dy, self.bike.getZ() - self.dz) if self.bike.getZ() <= 0: self.jump = False self.bike.setZ(0) else: self.bike.setPos(self.bike.getX() - dx, self.bike.getY() - dy, self.bike.getZ()) else: #decelerate self.current_vel -= 20 * self.accel * elapsed self.temp_vel = self.current_vel if(self.current_vel < 0): self.current_vel = 0 dist = self.current_vel * elapsed angle = deg2Rad(self.bike.getH()) dx = dist * math.sin(angle) dy = dist * -math.cos(angle) if self.jump == True: self.bike.setPos(self.bike.getX() - dx, self.bike.getY() - dy, self.bike.getZ() - self.dz) if self.bike.getZ() <= 0: self.jump = False self.bike.setZ(0) else: self.bike.setPos(self.bike.getX() - dx, self.bike.getY() - dy, self.bike.getZ()) #attempt to change pitch if self.bike.getZ() != prevZ: ang = math.atan2(self.bike.getY(), self.bike.getZ()) self.bike.setP(ang) if self.moveMap['left'] or self.moveMap['right'] or self.moveMap['forward']: #print('heading', self.bike.getH()) if self.isMoving == False: self.isMoving = True self.bike.loop("move") else: if self.isMoving: self.isMoving = False self.bike.stop() #self.bike.pose("walk", 4) self.prevTime = task.time #print(self.current_vel) return Task.cont
def __init__(self, cTrav): #create speed vars self.max_vel = 35 self.accel = 2 self.current_vel = 0 self.cTrav = cTrav self.weapon = 0 #vars for jumping self.tempHeading = 0 self.temp_vel = 0 self.count = 0 self.first_time = False self.jump = False self.dz = 0 #set HP self.hp = 10 #invincible check self.invin = False self.invinCount = 0 #Shotgun check self.shotgun = False self.p_up_timer = 0 #healing powerup self.health_up = False #load all sound files self.singleShot = base.loader.loadSfx('M4A1.mp3') #create empty list for bullets and a task for updating the positions self.bullet = Bullet(cTrav) self.spreadshot = weapon1(cTrav) self.explode = weapon2(cTrav) self.wallshot = weapon3(cTrav) taskMgr.add(self.bullet.update, "bulletTask") taskMgr.add(self.spreadshot.update, "bulletTask") taskMgr.add(self.updatePowerup, "powerupTask") #load the bike actor and parent it to a physics node self.bike = Actor("moto2_actor.egg", {"move":"moto2_moveAnim.egg", "turnL":"moto2_blahblah.egg"}) #self.bike.setScale(.5) #self.bike.setH(180) self.bike.reparentTo(render) self.dummy = Actor("temp_bullet.egg") self.dummy.reparentTo(render) #setup a move task for the bike taskMgr.add(self.move, "moveTask") self.prevTime = 0 self.isMoving = False #setup a shoot task for the bike taskMgr.add(self.shoot, "shootTask") self.shotClock = 25 # for shooting anim self.isShooting = False #setup a moving dictionary self.moveMap = {"left":0, "right":0, "forward":0} #setup a shoot check self.shootCheck = 0 #setup a wall collision check self.wallCheck = False #pusher collision spheres #front collisionPusher = CollisionHandlerPusher() collisionPusher.setInPattern("p_bike-%in") cPushSphere = CollisionSphere((0,3.5,2),2) cNode1 = CollisionNode("p_bike_push") cNode1.addSolid(cPushSphere) cNode1.setIntoCollideMask(0x10) cNode1.setFromCollideMask(0x1) self.cNodePath1 = self.bike.attachNewNode(cNode1) #self.cNodePath1.show() collisionPusher.addCollider(self.cNodePath1, self.bike) self.cTrav.addCollider(self.cNodePath1, collisionPusher) #middle cPushSphere = CollisionSphere((0,0,2),2) cNode2 = CollisionNode("p_bike_push") cNode2.addSolid(cPushSphere) cNode2.setIntoCollideMask(0x10) cNode2.setFromCollideMask(0x1) self.cNodePath2 = self.bike.attachNewNode(cNode2) #self.cNodePath2.show() collisionPusher.addCollider(self.cNodePath2, self.bike) self.cTrav.addCollider(self.cNodePath2, collisionPusher) #back cPushSphere = CollisionSphere((0,-2.5,2),2) cNode3 = CollisionNode("p_bike_push") cNode3.addSolid(cPushSphere) cNode3.setIntoCollideMask(0x10) cNode3.setFromCollideMask(0x1) self.cNodePath3 = self.bike.attachNewNode(cNode3) #self.cNodePath3.show() collisionPusher.addCollider(self.cNodePath3, self.bike) self.cTrav.addCollider(self.cNodePath3, collisionPusher) #collision rays for faux-gravity #front wheel lifter = CollisionHandlerFloor() lifter.setMaxVelocity(9.8) cRay1 = CollisionRay(0, 3, 3, 0, 0, -1) cRayNode1 = CollisionNode('playerRay') cRayNode1.addSolid(cRay1) cRayNode1.setIntoCollideMask(BitMask32.allOff()) cRayNode1.setFromCollideMask(2) cRayNodePath1 = self.bike.attachNewNode(cRayNode1) #cRayNodePath1.show() self.cTrav.addCollider(cRayNodePath1, lifter) lifter.addCollider(cRayNodePath1, self.bike) #setup and parent spotlights to the player self.spotlight = Spotlight("headlight") self.spotlight.setColor((1, 1, 1, 1)) self.spotlight.setAttenuation(Point3(0,0,.001)) lens = PerspectiveLens() #can change size of cone lens.setFov(20) self.spotlight.setLens(lens) self.spotlight.setExponent(100) lightNode = self.bike.attachNewNode(self.spotlight) render.setLight(lightNode)
def fireBullet(self): self.newBullet = Bullet("Bullets.gif",self.upperLeft.x + (self.get_width() / 2), self.upperLeft.y + (self.get_height() / 2), 30, 30, 3, 3, self.crosshair) self.newBullet.set_animation_frame(6) self.gun.addBullet(self.newBullet) self.attackFlag = moveDirection.ATTACK self.delay = 1
class Character(SpriteClass): def __init__(self, filename, x, y, width, height, columns, rows, xVelocity = 1, yVelocity = 1): SpriteClass.__init__(self, filename,x, y, width, height, columns, rows) self.characterModel = filename self.keyLeft = pygame.K_a self.keyRight = pygame.K_d self.keyUp = pygame.K_w self.keyDown = pygame.K_s self.keySpace = pygame.K_SPACE self.width = self.get_width() self.height = self.get_height() self.velocity = Point2D(xVelocity, yVelocity) self.keyboard = pygame.key.get_pressed() self.animationSwitchUpDown = False self.animationSwitchLeftRight = False self.isAlive = True self.playerDirection = moveDirection.NULL self.attackFlag = moveDirection.NULL self.gun = Gun(True) self.newBullet = None self.leftMouseClick = (1,0,0) self.delay = 0 self.firingRate = 10 self.health = 100 self.score = 0 ### #variables for timer ### self.timer = 0 #timer to reset the path self.timingFlag = False #flag to set to make the path reset after the timer self.delay = 1000 #1 second self.setUpCrossHair() def damage(self, amount = 20): if self.health > 0: self.health -= amount def setUpSprite(self): self.set_image_color_key(255, 0, 255) self.set_animation_delay(500) self.play(True) def moveUp(self): self.upperLeft.y -= self.velocity.y self.updateLowerRight() def moveDown(self): self.upperLeft.y += self.velocity.y self.updateLowerRight() def moveLeft(self): self.upperLeft.x -= self.velocity.x self.updateLowerRight() def moveRight(self): self.upperLeft.x += self.velocity.x self.updateLowerRight() def handleUpActions(self): self.set_animation_range(12, 16) self.moveUp() if(self.animationSwitchUpDown == False): self.set_animation_frame(12) self.animationSwitchUpDown = True def handleDownActions(self): self.set_animation_range(0, 4) self.moveDown() if(self.animationSwitchUpDown == False): self.set_animation_frame(0) self.animationSwitchUpDown = True def handleLeftActions(self): self.set_animation_range(4, 8) self.moveLeft() if(self.animationSwitchLeftRight == False): self.set_animation_frame(4) self.animationSwitchLeftRight = True def handleRightActions(self): self.set_animation_range(8, 12) self.moveRight() if(self.animationSwitchLeftRight == False): self.set_animation_frame(8) self.animationSwitchLeftRight = True def handleInput(self): self.keyboard = pygame.key.get_pressed() if(self.keyboard[self.keyLeft]): self.handleLeftActions() self.playerDirection = moveDirection.LEFT elif(self.keyboard[self.keyRight]): self.handleRightActions() self.playerDirection = moveDirection.RIGHT if(not (self.keyboard[self.keyLeft] or self.keyboard[self.keyRight])): self.animationSwitchLeftRight = False if(self.keyboard[self.keyUp]): self.handleUpActions() self.playerDirection = moveDirection.UP elif(self.keyboard[self.keyDown]): self.handleDownActions() self.playerDirection = moveDirection.DOWN if(not (self.keyboard[self.keyUp] or self.keyboard[self.keyDown])): self.animationSwitchUpDown = False if(self.keyboard[self.keyLeft] == False) and (self.keyboard[self.keyRight] == False) and (self.keyboard[self.keyUp] == False) and (self.keyboard[self.keyDown] == False): self.playerDirection = moveDirection.NULL def setUpCrossHair(self): pygame.mouse.set_visible(False) self.crosshair = MouseCrosshair(Point2D(50,50), Point2D(30,30), "crosshair.bmp", 60, 30, 2, 1) self.crosshair.set_image_color_key(255, 255, 255) self.crosshair.set_animation_delay(200) self.crosshair.play(True) def handleAttack(self): if self.delay >= self.firingRate: self.delay = 0 if(pygame.mouse.get_pressed() == self.leftMouseClick): if self.delay == 0: if(self.attackFlag != moveDirection.ATTACK): self.fireBullet() else: self.attackFlag = moveDirection.NULL if self.delay != 0: self.delay += 1 def fireBullet(self): self.newBullet = Bullet("Bullets.gif",self.upperLeft.x + (self.get_width() / 2), self.upperLeft.y + (self.get_height() / 2), 30, 30, 3, 3, self.crosshair) self.newBullet.set_animation_frame(6) self.gun.addBullet(self.newBullet) self.attackFlag = moveDirection.ATTACK self.delay = 1 def checkScreenBounds(self): if(self.upperLeft.y <= 0): self.upperLeft.y = 1 if(self.upperLeft.y + self.height >= screenHeight - 115): self.upperLeft.y = screenHeight - self.height - 115 if(self.upperLeft.x <= 0): self.upperLeft.x = 1 if(self.upperLeft.x + self.width >= screenWidth): self.upperLeft.x = screenWidth - self.width - 1 self.updateLowerRight() def updateLowerRight(self): self.lowerRight.x = self.upperLeft.x + self.width self.lowerRight.y = self.upperLeft.y + self.height def update(self, screen, enemyList): if self.health > 0: self.handleInput() self.handleAttack() self.checkScreenBounds() self.gun.update(screen, enemyList) for enemy in enemyList: if(enemy.health == 0): self.score += 1000 self.crosshair.update(screen)