def __init__(self,bulletlist): Bullet.__init__(self,bulletlist) self.x=1 self.xran = random.uniform(1,6) self.y=self.plot(self.x) self.bspeed=.6 self.xspeed=.1
def shoot(self, shotVec=None): if self.ammunition > 0: self.shootSound.play() b = Bullet(self.playerID, self.color) pos = self.model.find("**/BulletStart").getPos(render) hpr = self.model.getHpr(render) hpr.setX(hpr.getX() + 90.0) b.shoot(pos, shotVec) self.ammunition -= 1
def spawn_bullet(self): x, y = self.position deg = self.rotation bp = load_pic('bullet.png') if deg == 0: x += self.width/2 + bp.width else: x -= self.width/2 + bp.width b = Bullet(bp, x, y, deg, batch=graphics_batch) snd_bullet.play() b.color = self.color bullets.append(b)
def __init__(self, bulletlist, **kw): self.kw = kw Bullet.__init__(self, bulletlist) self.inc = 0.2 self.c = 0 self.width = 30 self.speed = 10 # print "kwargs are ",kw # print "kwargs are ",self.kw self.mid = self.kw["mid"]
def shotBullet(self, player): if self.seeing_player and self.shot >= 40: distance = player.rect.x - self.rect.x bullet = Bullet(self.rect.center[0], self.rect.center[1] - 10, 5, ["sprites\\enemy_bullet.png"]) if distance > 0: bullet.fire(0) else: bullet.fire(math.pi) self.shot = 0 return bullet else: return None
def shoot(self): """Chooses a random bottom enemy to shoot the bullet is added to the self.bullets group """ # pick a random living enemy, then make the bottom living enemy of that column shoot r = random.randint(0, len(self) - 1) ##print ("Random = ", r) ##print ("Enemies = ", len(self)) col = Group.sprites(self)[r].col shooter = self.bottom_sprite(col) new_bullet = Bullet(window_size, bullet_filename, bullet_speed, shooter.rect.center, SOUTH) new_bullet.add(self.bullets)
class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) #call Sprite initializer self.image= playership[0] self.rect = self.image.get_rect() self.state=0 self.speed=10 def get_pos(self): return self.rect def move(self, x,y): self.rect.topleft=(x,y) def move_one(self,direction): if direction == 1: self.rect.move_ip(self.speed,0) if not self.in_range(self.rect): #if it goes out of the range, move it back self.rect.move_ip((-1)*self.speed,0) elif direction == 0: self.rect.move_ip((-1)*self.speed,0) if not self.in_range(self.rect): self.rect.move_ip(self.speed,0) def in_range(self,rect): if gamewindow.contains(rect): return True return False def set_pos(self, tempx,tempy): self.rect.move_ip(tempx,tempy) def set_hit(self): self.state=1 def shoot(self,shotslist,locx,locy): self.boom=Bullet(shotslist) self.boom.set_pos(locx,locy) #self.boom.set_speed(globalvars.BUL) shotslist.add(self.boom) def update(self): #yay for update... if self.state > 0: self.image=playership[self.state/explosion_speed] self.state+=1 if self.state >= len(playership)*explosion_speed: self.state=0 self.image=playership[0]
def dataReceived(self, data): if not '\n' in data: self.buf += data return full = (self.buf + data).split("\n") self.buf = full[-1] for line in full[:-1]: json_data = json.loads(line) if json_data["message_type"] == "hello": global game_map print "Hello message" units = [Unit.from_dict(u) for u in json_data["units"]] bullets = [Bullet.from_dict(b) for b in json_data["bullets"]] hero = Hero.from_dict(json_data["hero"]) commander = Commander.from_dict(json_data["commander"]) game_map = GameMap(json_data["rows"], json_data["cols"], json_data["map"], hero, commander, units, bullets) elif json_data["message_type"] == "update": # Drop any removed units/bullets, then update values for remaining if len(game_map.units) > len(json_data["units"]): game_map.units = game_map.units[:len(json_data["units"])] for i in xrange(len(json_data["units"]) - len(game_map.units)): game_map.units.append(Unit(1, 1999, 1999, 0, 0)) for u_old, u_new in zip(game_map.units, json_data["units"]): u_old.update_from_dict(u_new) if len(game_map.bullets) > len(json_data["bullets"]): game_map.bullets = game_map.bullets[:len(json_data["bullets"])] for i in xrange(len(json_data["bullets"]) - len(game_map.bullets)): game_map.bullets.append(Bullet(0, 999, 999, 0, 0)) for b_old, b_new in zip(game_map.bullets, json_data["bullets"]): b_old.update_from_dict(b_new) game_map.hero.update_from_dict(json_data["hero"]) game_map.commander.update_from_dict(json_data["commander"])
def play(): from menu import Menu menu = Menu(screen) #show menu before starting game. menu.showMenu() from player import Player from bullet import Bullet from enemies import Enemies player = Player() player.set_screen(screen) to_update = player.create() #draw player to screen immediately pygame.display.update(to_update) bullet = Bullet() bullet.set_screen(screen) enemies = Enemies() enemies.set_screen(screen) while player.is_alive(): to_update = [] pygame.event.pump() key = pygame.key.get_pressed() #key events that only need to be pressed once for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: menu.showMenu() if event.key == pygame.K_SPACE: player.fire(bullet, True) if key[pygame.K_ESCAPE]: sys.exit() if key[pygame.K_RIGHT]: to_update += player.move_right() if key[pygame.K_LEFT]: to_update += player.move_left() if key[pygame.K_SPACE]: player.fire(bullet, False) frametime.start() to_update += bullet.move(enemies, player) to_update += enemies.move(bullet) pygame.display.update(to_update) #find how long it took to render this frame so we can adjust speeds frametime.end() #player died player.game_over() enemies.game_over() bullet.game_over() pygame.display.flip()
def __init__(self, x=None, kind=None, is_red=None): pygame.sprite.Sprite.__init__(self) # 用于给刚生成的坦克播放出生特效 self.born = True self.times = 90 # 坦克的种类编号 if kind is None: self.kind = random.randint(0, 3) else: self.kind = kind # 所有坦克 self.tanks1 = ['./images/enemyTank/enemy_1_0.png', './images/enemyTank/enemy_1_1.png', './images/enemyTank/enemy_1_2.png', './images/enemyTank/enemy_1_3.png'] self.tanks2 = ['./images/enemyTank/enemy_2_0.png', './images/enemyTank/enemy_2_1.png', './images/enemyTank/enemy_2_2.png', './images/enemyTank/enemy_2_3.png'] self.tanks3 = ['./images/enemyTank/enemy_3_0.png', './images/enemyTank/enemy_3_1.png', './images/enemyTank/enemy_3_2.png', './images/enemyTank/enemy_3_3.png'] self.tanks4 = ['./images/enemyTank/enemy_4_0.png', './images/enemyTank/enemy_4_1.png', './images/enemyTank/enemy_4_2.png', './images/enemyTank/enemy_4_3.png'] self.tanks = [self.tanks1, self.tanks2, self.tanks3, self.tanks4] # 是否携带食物(红色的坦克携带食物) if is_red is None: self.is_red = random.choice((True, False, False, False, False)) else: self.is_red = is_red # 同一种类的坦克具有不同的颜色, 红色的坦克比同类坦克多一点血量 if self.is_red: self.color = 3 else: self.color = random.randint(0, 2) # 血量 self.blood = self.color # 载入(两个tank是为了轮子特效) self.tank = pygame.image.load(self.tanks[self.kind][self.color]).convert_alpha() self.tank_0 = self.tank.subsurface((0, 48), (48, 48)) self.tank_1 = self.tank.subsurface((48, 48), (48, 48)) self.rect = self.tank_0.get_rect() # 坦克位置 if x is None: self.x = random.randint(0, 2) else: self.x = x self.rect.left, self.rect.top = 3 + self.x * 12 * 24, 3 # 坦克是否可以行动 self.can_move = True # 坦克速度 self.speed = max(3 - self.kind, 1) # 方向 self.direction_x, self.direction_y = 0, 1 # 是否存活 self.being = True # 子弹 self.bullet = Bullet()
def shoot(self): for i in range(4): bullet = Bullet(IMG_PATH_BULLET, self.getRect().centerx, self.getRect().centery, 1) bullet.x -= bullet.w/2 bullet.y -= bullet.h/2 self.bullets.append(bullet) for bullet in self.bullets: if self.bullets.index(bullet) == 0: bullet.speedX = 0 bullet.speedY = -self.speed elif self.bullets.index(bullet) == 1: bullet.speedX = self.speed bullet.speedY = 0 elif self.bullets.index(bullet) == 2: bullet.speedX = 0 bullet.speedY = self.speed else: bullet.speedX = -self.speed bullet.speedY = 0
def fire_button_pressed(self): if self.bullet: # if there is already a bullet existing (which means it's flying around or exploding somewhere) # don't fire. return self.app.sound['bullet_start'].play() # create a bullet, calculate the start position and fire it. tower_angle = radians(self.tank.tank_tower_scatter.rotation) tower_position = self.tank.pos bullet_position = (tower_position[0] + 48 + cos(tower_angle) * 130, tower_position[1] + 70 + sin(tower_angle) * 130) self.bullet = Bullet(angle=tower_angle) self.bullet.center = bullet_position self.add_widget(self.bullet) self.bullet.fire()
def __init__(self): Game.__init__(self, config.TITLE, config.SCREEN_X, config.SCREEN_Y) self.title = config.TITLE self.screen_x = config.SCREEN_X self.screen_y = config.SCREEN_Y self.level = 1 self.asteroid_count = 0 self.ship = Ship() self.rocks = [] self.stars = [] self.bullet = Bullet() self.bullet2 = Bullet() self.bullet3 = Bullet() self.nuke = Nuke() self.score = 0 pygame.init() self.name = '' pygame.mixer.init(44100, -16, 2, 512) self.star_trek = pygame.mixer.Sound("Star Trek Theme Song.wav") self.star_trek.play(-1) self.ship_explosion_sfx = pygame.mixer.Sound("explosion.ogg") self.astroid_explosion_sfx = pygame.mixer.Sound("explosion.ogg") for i in range(config.ASTEROID_COUNT): self.rocks.append(Rock()) self.asteroid_count += 1 for i in range(config.STAR_COUNT): self.stars.append(Stars()) for i in self.rocks: if i.active == False: self.asteroid_count -= 1 self.high_count = 10 self.high_score = [] try: f = open("score.txt", 'r') for score in f: score.rstrip("\n") self.high_score.append(score) f.close() print self.high_score except: self.highscore = 0 self.rock_dead = []
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()
def reset(self, position, rotation, pull): Game.__init__(self, config.TITLE, config.SCREEN_X, config.SCREEN_Y) self.ship = Ship() self.ship.position = position self.ship.rotation = rotation self.ship.pull = pull self.rocks = [] self.stars = [] self.asteroid_count = 0 self.bullet = Bullet() self.bullet2 = Bullet() self.bullet3 = Bullet() self.nuke = Nuke() pygame.init() pygame.mixer.init(44100, -16, 2, 512) self.star_trek = pygame.mixer.Sound("Star Trek Theme Song.wav") self.star_trek.play(-1) self.ship_explosion_sfx = pygame.mixer.Sound("explosion.ogg") self.astroid_explosion_sfx = pygame.mixer.Sound("explosion.ogg") for i in range(config.ASTEROID_COUNT + (self.level + 1)): self.rocks.append(Rock()) self.asteroid_count += 1 for i in range(config.STAR_COUNT): self.stars.append(Stars()) for i in self.rocks: if i.active == False: self.asteroid_count -= 1 self.high_count = 10 self.high_score = [] try: f = open("score.txt", 'r') for score in f: score.rstrip() self.high_score.append(score) f.close() except: self.highscore = 0 self.rock_dead = []
def fire(self, all_sprites_list, bullet_list): """Fires a shot, takes in all_sprites_list to get access to the group Firing is limited by the self.rate of fire(compulsory time in milliseconds between each shot). """ if self.dead: pass else: # Restrain the rate of fire if (pygame.time.get_ticks()-self.last_shot) > (self.rate_of_fire): if self.ammo: if self.weaponup: #------------------------------------------- for i in range(-1, 2): bullet = Bullet(self.powerbullets, self.dir, 20) bullet.rect.centerx = self.rect.centerx bullet.rect.centery = self.rect.centery # Calculate vectors: bullet.xspeed = math.cos(math.radians(self.dir+(i*20))) * BULLETSPEED bullet.yspeed = math.sin(math.radians(self.dir+(i*20))) * (-BULLETSPEED) # Add the bullets to the lists all_sprites_list.add(bullet) bullet_list.add(bullet) # Decrease the ammo count self.ammo = max(0, self.ammo-1) else: bullet = Bullet(self.bullets, self.dir, 10) bullet.rect.centerx = self.rect.centerx bullet.rect.centery = self.rect.centery # Calculate vectors: bullet.xspeed = math.cos(math.radians(self.dir)) * BULLETSPEED bullet.yspeed = math.sin(math.radians(self.dir)) * (-BULLETSPEED) # Add the bullets to the lists all_sprites_list.add(bullet) bullet_list.add(bullet) # Decrease the ammo count self.ammo = max(0, self.ammo-1) self.last_shot = pygame.time.get_ticks()
def fire_bullet(ai_settings,screen,ship,bullets): #创建一颗子弹,并将其加入到编组bullets中 if(len(bullets)<ai_settings.bullets_allowed): new_bullet= Bullet(ai_settings,screen,ship) bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): # 创建一颗子弹,并加入到编组bullets中 if len(bullets) < ai_settings.bullet_num: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): '''Выпускает пулю, если максимум еще не достигнут.''' # Создание новой пули и включение ее в группу bullets. if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def fire_bullet(aiSettings, screen, ship, bullets): new_bullet = Bullet(aiSettings, screen, ship) bullets.add(new_bullet) new_bullet.sound.play()
def fire_bullet(ai_settings, screen, ship, bullets): """如果还没有到达极限,就发射一颗子弹""" if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def shoot(self,shotslist,locx,locy): self.boom=Bullet(shotslist) self.boom.set_pos(locx,locy) #self.boom.set_speed(globalvars.BUL) shotslist.add(self.boom)
from bullet import Bullet cli = Bullet( prompt = "\nPlease choose a fruit: ", choices = ["apple", "banana", "orange", "watermelon", "strawberry"], indent = 0, align = 5, margin = 2, shift = 0, bullet = "", pad_right = 5, return_index = True ) result = cli.launch() print("You chose:", result)
def fire_bullet(ai_settings, screen, ship, bullets): if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def fire_bullet(settings, screen, shooter, bullets): if len(bullets) < settings.bullets_allowed: new_bullet = Bullet(settings, screen, shooter) # создание пули bullets.add(new_bullet)
def fireBullets(bullets, screen, settings, ship): if len(bullets) < settings.bullets_allowed: new_bullet = Bullet(screen, settings, ship) bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): """如果还没有达到限制,就发射一颗子弹""" # 创建一颗子弹,并将其加入到编组bullets中 if len(bullets) < ai_settings.bullet_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def main(): random.seed(time.time()) # Initialise colorama init() # Clear screen print(chr(27) + '[2j') print('\033c') print('\x1bc') # Get terminal size (ncols, nlines) = shutil.get_terminal_size() # Initialise screen screen = Window(0, 1, ncols, nlines - 1, f"{config.bkgd} ") # Initialise keyboard kb = KBHit() # Create and draw the paddle paddle = Paddle(((ncols - 1) - config.paddle["dim"][0]) // 2, nlines - 4, screen) last_update = 0 start = time.time() score = 0 lives = 3 curr_level = 1 # List to store shooters shooters = [None, None] while curr_level <= 3: # Create and draw bricks boss = None if curr_level == 1: bricks, powerups = levels.level_one(screen) elif curr_level == 2: bricks, powerups = levels.level_two(screen) elif curr_level == 3: bricks, powerups = levels.level_three(screen) boss = Boss(ncols // 2, 5, screen) else: sys.exit() if lives == 0: break while lives: # Reset paddle location paddle.x = ((ncols - 1) - config.paddle["dim"][0]) // 2 paddle.powerup = None # Create and draw the ball balls = [ Ball(random.randrange(paddle.x, paddle.x + paddle.width), nlines - 5, list(config.ball["speed"]), 1, screen) ] # List to store bullets bullets = [] shoot_paddle = [0] # List to store bombs bombs = [] tick = 0 while len(balls): if (time.time() - last_update > config.tick_interval): tick += 1 for i in range(ncols): print(f"{Cursor.POS(1+i, 1)}{Back.BLACK} ", end='') statusline = f"{Cursor.POS(1, 1)}Level: {curr_level} " statusline += f"Score: {score} " statusline += f"Time: {int(time.time() - start)} " statusline += f"Lives: {lives} " statusline += f"Shoot Paddle: {int(shoot_paddle[0] * config.tick_interval)} " if boss: statusline += "Boss Health: [" for i in range(0, boss.health, 10): statusline += "•" for i in range(0, 100 - boss.health, 10): statusline += " " statusline += "]" print(statusline, end='') last_update = time.time() change_level = False direction = 0 if kb.kbhit(): c = kb.getch() if ord(c) == 27: sys.exit(0) if c == 'a': direction = -1 elif c == 'd': direction = 1 elif c == ' ': # Activate balls for ball in balls: ball.paused = False elif c == '1' or c == '2' or c == '3': curr_level = int(c) if curr_level != 3 else 4 change_level = True break # Create new bullets if needed shoot_paddle[0] = max(0, shoot_paddle[0] - 1) if shoot_paddle[0] and shoot_paddle[0] % config.bullet[ "rate"] == 0: bullets.append( Bullet(max(paddle.x, 0), paddle.y, config.bullet["speed"], screen)) bullets.append( Bullet( min(paddle.x + paddle.width, screen.get_screen_size()[1] - 1), paddle.y, config.bullet["speed"], screen)) # Create bomb if needed if boss and tick % config.bomb["rate"] == 0: bombs.append( Bomb(boss.x + 5, boss.y + 3, config.bomb["speed"], screen)) # Create shooters if needed if shoot_paddle[0] and not shooters[0]: shooters[0] = Object(paddle.x, paddle.y - 1, 1, 1, config.paddle["color"], screen) if shoot_paddle[0] and not shooters[1]: shooters[1] = Object(paddle.x + paddle.width - 1, paddle.y - 1, 1, 1, config.paddle["color"], screen) # Create brick layer on boss level if health is 50 if boss and boss.health == 80 and not boss.done[0]: bricks.append([]) brick_count = screen.get_screen_size()[1] // \ (config.brick["dim"][0] + 5) for i in range(brick_count): bricks[1].append( Brick(i * (config.brick["dim"][0] + 5), 9, 1, screen)) boss.done[0] = True # Create brick layer on boss level if health is 20 if boss and boss.health == 20 and not boss.done[1]: brick_count = screen.get_screen_size()[1] // \ (config.brick["dim"][0] + 5) bricks.append([]) for i in range(brick_count): bricks[2].append( Brick(i * (config.brick["dim"][0] + 5), 13, 1, screen)) boss.done[1] = True # Clear screen screen.clear() # Move the paddle paddle.move(direction, balls) # Move the powerups to_delete = [] for powerup in powerups: object = None if powerup.type == "paddle": object = paddle elif powerup.type == "ball": object = balls else: object = shoot_paddle if not powerup.move(paddle, object, tick): to_delete.append(powerup) powerups = [ powerup for powerup in powerups if powerup not in to_delete ] # Move the ball to_delete = [] for ball in balls: delete, d_score = ball.move(bricks, paddle, boss) if not delete: to_delete.append(ball) score += d_score balls = [ball for ball in balls if ball not in to_delete] # Delete shooters if powerup is over if shoot_paddle[0] == 0: shooters = [None, None] # Move the bullets to_delete = [] for bullet in bullets: delete, d_score = bullet.move(bricks) if not delete: to_delete.append(bullet) score += d_score bullets = [ bullet for bullet in bullets if bullet not in to_delete ] # Move the bombs to_delete = [] lose_life = False for bomb in bombs: delete, lose_life = bomb.move(paddle) if not delete: to_delete.append(bomb) if lose_life: break if lose_life: break bombs = [bomb for bomb in bombs if bomb not in to_delete] # Move the boss if boss: boss.move(paddle.x + paddle.width // 2) # Move the shooter if shooters[0]: shooters[0].x = paddle.x if shooters[1]: shooters[1].x = paddle.x + paddle.width - 1 # Update bricks for layer in bricks: for brick in layer: brick.rainbow(tick) # Don't move bricks on boss level if curr_level < 3: brick.move(tick) if brick.y + brick.height > paddle.y: sys.exit() brick.update() # Update paddle paddle.update() # Update shooters for shooter in shooters: if shooter: shooter.update() # Update powerups for powerup in powerups: powerup.update() # Update ball for ball in balls: ball.update() # Update bullets for bullet in bullets: bullet.update() # Update bombs for bomb in bombs: bomb.update() # Boss update if boss: boss.update() screen.draw() # Check if all breackable bricks are broken on non boss levels if curr_level < 3: change_level = True for layer in bricks: for brick in layer: if brick._strength != 4: change_level = False break if not change_level: break else: if boss.health <= 0: change_level = True if change_level: curr_level += 1 break if change_level: break lives -= 1
def fire_bullet(ai_settings, stats, screen, ship, bullets): if len(bullets ) < ai_settings.bullets_allowed and stats.game_active == True: new_bullet = Bullet(ai_settings, screen, ship) ai_settings.laser.play() bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): """ Fire a bullet if limit not reached yet """ if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def _fire_bullet(self): if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet)
def fire_bullets(ai_settings, screen, ship, bullets): """ Fire a bullet if limit is not reached yet. """ # Create new bullets and add it to the bullets group if len(bullets) <= ai_settings.bullet_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): #Create new bullet and add to bullet group if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def _create_30_cal (game, data) : p30_cal = Bullet (default='images/30_cal.png') p30_cal.set_pos (_get_coords (data)) p30_cal.set_name (".30 cal") return p30_cal
def __init__(self,x=0,y=0,width=5,height=5, **images) : Bullet.__init__ (self,x,y,width,height,**images) self._name = "Explosive Bullet"
def fire_bullet(ai_settings, screen, ship, bullets): if len(bullets) < ai_settings.bullet_allowed: new_bullet = Bullet(ai_settings, screen, ship) #创建新的子弹 bullets.add(new_bullet) #将子弹添加到编组内
def fire_bullet(ai_settings, stats, screen, ship, bullets, music1): if len(bullets) < ai_settings.bullet_allowed and stats.game_active: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) music1.play()
class Asteroids(Game): def __init__(self): Game.__init__(self, config.TITLE, config.SCREEN_X, config.SCREEN_Y) self.title = config.TITLE self.screen_x = config.SCREEN_X self.screen_y = config.SCREEN_Y self.level = 1 self.asteroid_count = 0 self.ship = Ship() self.rocks = [] self.stars = [] self.bullet = Bullet() self.bullet2 = Bullet() self.bullet3 = Bullet() self.nuke = Nuke() self.score = 0 pygame.init() self.name = '' pygame.mixer.init(44100, -16, 2, 512) self.star_trek = pygame.mixer.Sound("Star Trek Theme Song.wav") self.star_trek.play(-1) self.ship_explosion_sfx = pygame.mixer.Sound("explosion.ogg") self.astroid_explosion_sfx = pygame.mixer.Sound("explosion.ogg") for i in range(config.ASTEROID_COUNT): self.rocks.append(Rock()) self.asteroid_count += 1 for i in range(config.STAR_COUNT): self.stars.append(Stars()) for i in self.rocks: if i.active == False: self.asteroid_count -= 1 self.high_count = 10 self.high_score = [] try: f = open("score.txt", 'r') for score in f: score.rstrip("\n") self.high_score.append(score) f.close() print self.high_score except: self.highscore = 0 self.rock_dead = [] def reset(self, position, rotation, pull): Game.__init__(self, config.TITLE, config.SCREEN_X, config.SCREEN_Y) self.ship = Ship() self.ship.position = position self.ship.rotation = rotation self.ship.pull = pull self.rocks = [] self.stars = [] self.asteroid_count = 0 self.bullet = Bullet() self.bullet2 = Bullet() self.bullet3 = Bullet() self.nuke = Nuke() pygame.init() pygame.mixer.init(44100, -16, 2, 512) self.star_trek = pygame.mixer.Sound("Star Trek Theme Song.wav") self.star_trek.play(-1) self.ship_explosion_sfx = pygame.mixer.Sound("explosion.ogg") self.astroid_explosion_sfx = pygame.mixer.Sound("explosion.ogg") for i in range(config.ASTEROID_COUNT + (self.level + 1)): self.rocks.append(Rock()) self.asteroid_count += 1 for i in range(config.STAR_COUNT): self.stars.append(Stars()) for i in self.rocks: if i.active == False: self.asteroid_count -= 1 self.high_count = 10 self.high_score = [] try: f = open("score.txt", 'r') for score in f: score.rstrip() self.high_score.append(score) f.close() except: self.highscore = 0 self.rock_dead = [] def game_logic(self, keys, newkeys, surface): self.ship.game_logic(keys, newkeys,self.bullet, self.nuke) self.bullet.game_logic(keys, newkeys) self.nuke.game_logic(keys, newkeys) for rock in self.rocks: if rock.active == True: rock.game_logic(keys, newkeys) if self.bullet.collision(rock) and self.bullet.active: self.astroid_explosion_sfx.play() self.rock_dead.append(rock) rock.active = False self.asteroid_count -= 1 self.score = self.score + 100 if self.nuke.collision(rock) and self.nuke.active: self.astroid_explosion_sfx.play() self.rock_dead.append(rock) rock.active = False self.score = self.score + 100 self.asteroid_count -= 1 if self.ship.collision(rock) and self.ship.active == True: self.ship_explosion_sfx.play() self.rock_dead.append(rock) self.score = self.score -100 if self.ship.shield_health >0: self.ship.shield_health -= 25 rock.active = False self.asteroid_count -= 1 self.ship.count -= 1 if self.ship.count == 0: self.ship.active = False for star in self.stars: star.game_logic() if self.game_over() == config.GAME_WIN: pygame.mixer.quit() self.level += 1 if self.level >= 5: self.nuke_count = 2 self.reset(self.ship.position, self.ship.rotation, self.ship.pull) if (self.game_over() != config.GAME_PLAYING): self.name = inputbox.ask(surface, "Three Letter Initial") self.name = self.name[0:3] name_score = self.name, self.score self.high_score.append(str(name_score)) print self.high_score self.high_score.sort(key=lambda s: eval(s)[1], reverse=True) if len(self.high_score) > self.high_count: self.high_score.pop() def entry_box(self): self.name = inputbox.ask(surface, "Your name") def save(self): f = open("score.txt", 'w') for score in self.high_score: score = score.rstrip() f.write(str(score)+"\n") f.close() def game_over(self): if not self.ship.active: return config.GAME_LOSE rocks_dead = True for rock in self.rocks: if rock.active: rocks_dead = False if rocks_dead: return config.GAME_WIN else: return config.GAME_PLAYING def paint(self, surface): surface.fill(config.BACKGROUND_COLOR) for star in self.stars: star.paint(surface) self.ship.paint(surface) self.ship.draw_shield(surface) self.bullet.paint(surface) self.nuke.paint(surface) for rock in self.rocks: rock.paint(surface) F = pygame.font.Font(None, 36) text = F.render("Score:" + str(self.score), True, (255, 255, 255)) F1 = pygame.font.Font(None, 36) text1 = F1.render("Shield Health:" + str(self.ship.shield_health), True, (255, 255, 255)) F2 = pygame.font.Font(None, 36) text2 = F2.render("Nukes:" + str(self.nuke.nuke_count), True, (255, 255, 255)) F3 = pygame.font.Font(None, 36) text3 = F3.render("Level:" + str(self.level), True, (255, 255, 255)) F4 = pygame.font.Font(None, 36) text4 = F4.render("Asteroids Left:" + str(self.asteroid_count), True, (255, 255, 255)) F5 = pygame.font.Font(None, 36) surface.blit(text3, (0, 0)) surface.blit(text, (0, 25)) surface.blit(text1, (0, 50)) surface.blit(text2, (0, 75)) surface.blit(text4, (0, 100)) if self.game_over() != config.GAME_PLAYING: xPos = 250 yPos = 50 high = F5.render('High Scores', True, (255, 255, 255)) surface.blit(high, (xPos, 10)) for line in self.high_score: name1, score1 = eval(str(line)) text5 = F5.render(name1, True, (255, 255, 255)) text6 = F5.render(str(score1), True, (255, 255, 255)) surface.blit(text5, (xPos, yPos)) surface.blit(text6, (xPos+100, yPos)) yPos += 50
class myTank(pygame.sprite.Sprite): 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() # 射击 def shoot(self): self.bullet.being = True self.bullet.turn(self.direction_x, self.direction_y) if self.direction_x == 0 and self.direction_y == -1: self.bullet.rect.left = self.rect.left + 20 self.bullet.rect.bottom = self.rect.top - 1 elif self.direction_x == 0 and self.direction_y == 1: self.bullet.rect.left = self.rect.left + 20 self.bullet.rect.top = self.rect.bottom + 1 elif self.direction_x == -1 and self.direction_y == 0: self.bullet.rect.right = self.rect.left - 1 self.bullet.rect.top = self.rect.top + 20 elif self.direction_x == 1 and self.direction_y == 0: self.bullet.rect.left = self.rect.right + 1 self.bullet.rect.top = self.rect.top + 20 else: raise ValueError('myTank class -> direction value error.') if self.level == 0: self.bullet.speed = 8 self.bullet.stronger = False elif self.level == 1: self.bullet.speed = 12 self.bullet.stronger = False elif self.level == 2: self.bullet.speed = 12 self.bullet.stronger = True elif self.level == 3: self.bullet.speed = 16 self.bullet.stronger = True else: raise ValueError('myTank class -> level value error.') # 等级提升 def up_level(self): if self.level < 3: self.level += 1 try: self.tank = pygame.image.load(self.tanks[self.level]).convert_alpha() except: self.tank = pygame.image.load(self.tanks[-1]).convert_alpha() # 等级降低 def down_level(self): if self.level > 0: self.level -= 1 self.tank = pygame.image.load(self.tanks[self.level]).convert_alpha() # 向上 def move_up(self, tankGroup, brickGroup, ironGroup, myhome): self.direction_x, self.direction_y = 0, -1 # 先移动后判断 self.rect = self.rect.move(self.speed*self.direction_x, self.speed*self.direction_y) self.tank_0 = self.tank.subsurface((0, 0), (48, 48)) self.tank_1 = self.tank.subsurface((48, 0), (48, 48)) # 是否可以移动 is_move = True # 地图顶端 if self.rect.top < 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞石头/钢墙 if pygame.sprite.spritecollide(self, brickGroup, False, None) or \ pygame.sprite.spritecollide(self, ironGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞其他坦克 if pygame.sprite.spritecollide(self, tankGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 大本营 if pygame.sprite.collide_rect(self, myhome): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False return is_move # 向下 def move_down(self, tankGroup, brickGroup, ironGroup, myhome): self.direction_x, self.direction_y = 0, 1 # 先移动后判断 self.rect = self.rect.move(self.speed*self.direction_x, self.speed*self.direction_y) self.tank_0 = self.tank.subsurface((0, 48), (48, 48)) self.tank_1 = self.tank.subsurface((48, 48), (48, 48)) # 是否可以移动 is_move = True # 地图底端 if self.rect.bottom > 630 - 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞石头/钢墙 if pygame.sprite.spritecollide(self, brickGroup, False, None) or \ pygame.sprite.spritecollide(self, ironGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞其他坦克 if pygame.sprite.spritecollide(self, tankGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 大本营 if pygame.sprite.collide_rect(self, myhome): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False return is_move # 向左 def move_left(self, tankGroup, brickGroup, ironGroup, myhome): self.direction_x, self.direction_y = -1, 0 # 先移动后判断 self.rect = self.rect.move(self.speed*self.direction_x, self.speed*self.direction_y) self.tank_0 = self.tank.subsurface((0, 96), (48, 48)) self.tank_1 = self.tank.subsurface((48, 96), (48, 48)) # 是否可以移动 is_move = True # 地图左端 if self.rect.left < 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞石头/钢墙 if pygame.sprite.spritecollide(self, brickGroup, False, None) or \ pygame.sprite.spritecollide(self, ironGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞其他坦克 if pygame.sprite.spritecollide(self, tankGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 大本营 if pygame.sprite.collide_rect(self, myhome): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False return is_move # 向右 def move_right(self, tankGroup, brickGroup, ironGroup, myhome): self.direction_x, self.direction_y = 1, 0 # 先移动后判断 self.rect = self.rect.move(self.speed*self.direction_x, self.speed*self.direction_y) self.tank_0 = self.tank.subsurface((0, 144), (48, 48)) self.tank_1 = self.tank.subsurface((48, 144), (48, 48)) # 是否可以移动 is_move = True # 地图右端 if self.rect.right > 630 - 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞石头/钢墙 if pygame.sprite.spritecollide(self, brickGroup, False, None) or \ pygame.sprite.spritecollide(self, ironGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 撞其他坦克 if pygame.sprite.spritecollide(self, tankGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False # 大本营 if pygame.sprite.collide_rect(self, myhome): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) is_move = False return is_move # 死后重置 def reset(self): self.level = 0 self.protected = False 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.direction_x, self.direction_y = 0, -1 if self.player == 1: self.rect.left, self.rect.top = 3 + 24 * 8, 3 + 24 * 24 elif self.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
def _fire_bullet(self): '''create a new bullet and add it to the bullets group''' if len(self.bullets) < self.settings.bullets_allowed: #if the amount of bullets in the group is less than 3: new_bullet = Bullet(self) #create an instance of a bullet self.bullets.add(new_bullet) #add the bullet to the group of bullets
class enemyTank(pygame.sprite.Sprite): def __init__(self, x=None, kind=None, is_red=None): pygame.sprite.Sprite.__init__(self) # 用于给刚生成的坦克播放出生特效 self.born = True self.times = 90 # 坦克的种类编号 if kind is None: self.kind = random.randint(0, 3) else: self.kind = kind # 所有坦克 self.tanks1 = ['./images/enemyTank/enemy_1_0.png', './images/enemyTank/enemy_1_1.png', './images/enemyTank/enemy_1_2.png', './images/enemyTank/enemy_1_3.png'] self.tanks2 = ['./images/enemyTank/enemy_2_0.png', './images/enemyTank/enemy_2_1.png', './images/enemyTank/enemy_2_2.png', './images/enemyTank/enemy_2_3.png'] self.tanks3 = ['./images/enemyTank/enemy_3_0.png', './images/enemyTank/enemy_3_1.png', './images/enemyTank/enemy_3_2.png', './images/enemyTank/enemy_3_3.png'] self.tanks4 = ['./images/enemyTank/enemy_4_0.png', './images/enemyTank/enemy_4_1.png', './images/enemyTank/enemy_4_2.png', './images/enemyTank/enemy_4_3.png'] self.tanks = [self.tanks1, self.tanks2, self.tanks3, self.tanks4] # 是否携带食物(红色的坦克携带食物) if is_red is None: self.is_red = random.choice((True, False, False, False, False)) else: self.is_red = is_red # 同一种类的坦克具有不同的颜色, 红色的坦克比同类坦克多一点血量 if self.is_red: self.color = 3 else: self.color = random.randint(0, 2) # 血量 self.blood = self.color # 载入(两个tank是为了轮子特效) self.tank = pygame.image.load(self.tanks[self.kind][self.color]).convert_alpha() self.tank_0 = self.tank.subsurface((0, 48), (48, 48)) self.tank_1 = self.tank.subsurface((48, 48), (48, 48)) self.rect = self.tank_0.get_rect() # 坦克位置 if x is None: self.x = random.randint(0, 2) else: self.x = x self.rect.left, self.rect.top = 3 + self.x * 12 * 24, 3 # 坦克是否可以行动 self.can_move = True # 坦克速度 self.speed = max(3 - self.kind, 1) # 方向 self.direction_x, self.direction_y = 0, 1 # 是否存活 self.being = True # 子弹 self.bullet = Bullet() # 射击 def shoot(self): self.bullet.being = True self.bullet.turn(self.direction_x, self.direction_y) if self.direction_x == 0 and self.direction_y == -1: self.bullet.rect.left = self.rect.left + 20 self.bullet.rect.bottom = self.rect.top - 1 elif self.direction_x == 0 and self.direction_y == 1: self.bullet.rect.left = self.rect.left + 20 self.bullet.rect.top = self.rect.bottom + 1 elif self.direction_x == -1 and self.direction_y == 0: self.bullet.rect.right = self.rect.left - 1 self.bullet.rect.top = self.rect.top + 20 elif self.direction_x == 1 and self.direction_y == 0: self.bullet.rect.left = self.rect.right + 1 self.bullet.rect.top = self.rect.top + 20 else: raise ValueError('enemyTank class -> direction value error.') # 随机移动 def move(self, tankGroup, brickGroup, ironGroup, myhome): self.rect = self.rect.move(self.speed*self.direction_x, self.speed*self.direction_y) is_move = True if self.direction_x == 0 and self.direction_y == -1: self.tank_0 = self.tank.subsurface((0, 0), (48, 48)) self.tank_1 = self.tank.subsurface((48, 0), (48, 48)) if self.rect.top < 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) self.direction_x, self.direction_y = random.choice(([0, 1], [0, -1], [1, 0], [-1, 0])) is_move = False elif self.direction_x == 0 and self.direction_y == 1: self.tank_0 = self.tank.subsurface((0, 48), (48, 48)) self.tank_1 = self.tank.subsurface((48, 48), (48, 48)) if self.rect.bottom > 630 - 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) self.direction_x, self.direction_y = random.choice(([0, 1], [0, -1], [1, 0], [-1, 0])) is_move = False elif self.direction_x == -1 and self.direction_y == 0: self.tank_0 = self.tank.subsurface((0, 96), (48, 48)) self.tank_1 = self.tank.subsurface((48, 96), (48, 48)) if self.rect.left < 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) self.direction_x, self.direction_y = random.choice(([0, 1], [0, -1], [1, 0], [-1, 0])) is_move = False elif self.direction_x == 1 and self.direction_y == 0: self.tank_0 = self.tank.subsurface((0, 144), (48, 48)) self.tank_1 = self.tank.subsurface((48, 144), (48, 48)) if self.rect.right > 630 - 3: self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) self.direction_x, self.direction_y = random.choice(([0, 1], [0, -1], [1, 0], [-1, 0])) is_move = False else: raise ValueError('enemyTank class -> direction value error.') if pygame.sprite.spritecollide(self, brickGroup, False, None) \ or pygame.sprite.spritecollide(self, ironGroup, False, None) \ or pygame.sprite.spritecollide(self, tankGroup, False, None): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) self.direction_x, self.direction_y = random.choice(([0, 1], [0, -1], [1, 0], [-1, 0])) is_move = False if pygame.sprite.collide_rect(self, myhome): self.rect = self.rect.move(self.speed*-self.direction_x, self.speed*-self.direction_y) self.direction_x, self.direction_y = random.choice(([0, 1], [0, -1], [1, 0], [-1, 0])) is_move = False return is_move # 重新载入坦克 def reload(self): self.tank = pygame.image.load(self.tanks[self.kind][self.color]).convert_alpha() self.tank_0 = self.tank.subsurface((0, 48), (48, 48)) self.tank_1 = self.tank.subsurface((48, 48), (48, 48))
def updateControls(self, game, key): self.timeUntilNextShot = max(0, self.timeUntilNextShot-1) self.timeUntilNextShot2 = max(0, self.timeUntilNextShot2-1) #print self.timeUntilNextShot if not self.po: return #shooting for gun in range(self.numGuns): left, right, up, down = 0, 0, 0, 0 if self.id == 0: #player 1 if gun == 0: if key[K_w]: up = 1. if key[K_s]: down = 1. if key[K_a]: left = 1. if key[K_d]: right = 1. elif gun == 1: if key[K_t]: up = 1. if key[K_g]: down = 1. if key[K_f]: left = 1. if key[K_h]: right = 1. elif self.id == 1: #player 2 if gun == 0: if key[K_UP]: up = 1. if key[K_DOWN]: down = 1. if key[K_LEFT]: left = 1. if key[K_RIGHT]: right = 1. elif gun == 1: if key[K_i]: up = 1. if key[K_k]: down = 1. if key[K_j]: left = 1. if key[K_l]: right = 1. elif self.id == 2 and gun == 0: pass #if key[K_i]: up = 1. #if key[K_k]: down = 1. #if key[K_j]: left = 1. #if key[K_l]: right = 1. elif self.id == 3 and gun == 0: pass #if key[K_t]: up = 1. #if key[K_g]: down = 1. #if key[K_f]: left = 1. #if key[K_h]: right = 1. if left and right: left, right = 0, 0 if up and down: up, down = 0, 0 numHeld = float(left+right+up+down) if numHeld < 1: continue if numHeld > 1: s = numHeld**0.5 left /= s right /= s up /= s down /= s dx, dy = right - left, down - up if gun == 0 and self.timeUntilNextShot > 0 \ or gun == 1 and self.timeUntilNextShot2 > 0: continue if gun == 0: self.timeUntilNextShot += self.TIME_BETWEEN_SHOTS elif gun == 1: if self.favoriteFruit == "shotgun": #ugly special case self.timeUntilNextShot2 += 20 else: self.timeUntilNextShot2 += self.TIME_BETWEEN_SHOTS if self.favoriteFruit == "shotgun" and gun != 1: for degree in range(-10, 10, 3): a = math.radians(degree) b = Bullet() b.po.pos = copy.copy(self.po.pos) b.po.v = copy.copy(self.po.v) + (V3(dx, dy).rotate(a)) \ * b.BULLET_SPEED b.owner = self.id b.bulletType = self.favoriteFruit game.bullets.append(b) vDiff = -0.3*(b.po.m * b.BULLET_SPEED) / self.po.m self.po.v += V3(dx, dy) * vDiff else: b = Bullet() b.po.pos = copy.copy(self.po.pos) b.po.v = copy.copy(self.po.v) + V3(dx, dy) * b.BULLET_SPEED b.owner = self.id b.bulletType = self.favoriteFruit if gun == 1: #gun 1 is like jetpack... #b.isVisisble = False b.ttl = 1 r = 4.0 b.BULLET_SPEED *= -r b.po.m /= r game.bullets.append(b) #p = mv const. #p1 = p2 => m1 v1 = m2 v2 => v1 = (m2 v2) / m1 #where 1 is the player, 2 is the bullet vDiff = -(b.po.m * b.BULLET_SPEED) / self.po.m self.po.v += V3(dx, dy) * vDiff
def checkKeydownEvents(event, setting, screen, stats, sb, playBtn, quitBtn, sel, ship1, ship2, aliens, bullets, eBullets, pauseBtnState2): """Response to kepresses""" global back #Movement of the ship1 if event.key == pg.K_RIGHT: ship1.movingRight = True elif event.key == pg.K_LEFT: ship1.movingLeft = True elif event.key == pg.K_UP: ship1.movingUp = True elif event.key == pg.K_DOWN: ship1.movingDown = True elif event.key == pg.K_RALT: #sounds.attack.play() #ship1.shoot = True if not stats.paused: if len(bullets) < 10: sounds.attack.play() newBullet = Bullet(setting, screen, ship1, ship1.trajectory) bullets.add(newBullet) ship1.chargeGaugeStartTime = pg.time.get_ticks() ship1.shoot = True elif event.key == pg.K_RSHIFT: #Change the style of trajectory of bullet if (ship1.trajectory < 5): ship1.trajectory += 1 else: ship1.trajectory = 0 #Movement of the ship2 elif event.key == pg.K_d: ship2.movingRight = True elif event.key == pg.K_a: ship2.movingLeft = True elif event.key == pg.K_s: ship2.movingDown = True elif event.key == pg.K_w: ship2.movingUp = True elif event.key == pg.K_LALT: #sounds.attack.play() #ship2.shoot = True if not stats.paused: if len(bullets) < 10: sounds.attack.play() newBullet = Bullet(setting, screen, ship2, ship2.trajectory) bullets.add(newBullet) ship2.chargeGaugeStartTime = pg.time.get_ticks() ship2.shoot = True elif event.key == pg.K_LSHIFT: #Change the style of trajectory of bullet if (ship2.trajectory < 5): ship2.trajectory += 1 else: ship2.trajectory = 0 #Check for pause key elif event.key == pg.K_p: sounds.paused.play() pause(stats) elif event.key == pg.K_F12: # Reset Game sounds.button_click_sound.play() resetGame() elif event.key == pg.K_ESCAPE: #Quit game sounds.button_click_sound.play() pg.time.delay(300) sys.exit()
def fire(self, id): bi = Bullet(self.x, self.y, self.d * 2.5, 2) bi.collision_list.append(id) globals.bullets.append(bi) globals.shake_duration = 0.75
def launch (self, velocity) : b1 = Bullet (default='images/buckshot.png') b1.rect.x = self.rect.x b1.rect.y = self.rect.y b2 = Bullet (default='images/buckshot.png') b2.rect.x = self.rect.x b2.rect.y = self.rect.y b3 = Bullet (default='images/buckshot.png') b3.rect.x = self.rect.x b3.rect.y = self.rect.y entities_list = self.get_pass_through_entities () entities_list.extend ([self, b1, b2, b3]) b1.set_pass_through_entities (entities_list) b1.set_friendly_entities (entities_list) b2.set_pass_through_entities (entities_list) b2.set_friendly_entities (entities_list) b3.set_pass_through_entities (entities_list) b3.set_friendly_entities (entities_list) self._delegate.spawn_entity (b1) b1.launch ( (velocity[0], -2) ) self._delegate.spawn_entity (b2) b2.launch ( (velocity[0], 0) ) self._delegate.spawn_entity (b3) b3.launch ( (velocity[0], 2) ) self._delegate.despawn_entity (self)
def _fire_bullet(self): """新しい弾を生成し bullets グループに追加する""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): """Fire a bullet if 3-limit has not reached yet.""" # Create a new bullet and add it to the bullets group. if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def fire_bullet(ai_settings, screen, ship, bullets): """ Fire bullet if limit not reached.""" #Create new bullet and add to bullets group. if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def __init__(self, x, y): Bullet.__init__(self, x, y)
def _fire_bullet(self): """Create a new bullet and add it to the bullets group.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet)
def fight(team,otherteam, screen): """ Simulates a round of combat where team attacks otherteam, drawing it on the screen """ global sim_fight for i in team.members: try: for b in range(i.attack_cap): l = len (otherteam.members) target = otherteam.members[rollDie(l,1)-1] for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONUP and event.button == 1 and pygame.mouse.get_focused()): if (pygame.Rect(625,25,150,50).collidepoint(event.pos)): sim_fight = False if sim_fight == True: if i.ranged == True: bullet = Bullet(i) if i.rect.x > target.rect.x: bullet.rect.x = i.rect.x - 25 elif i.rect.x < target.rect.x: bullet.rect.x = i.rect.x + 85 bullet.rect.y = i.rect.y bullet_list.add(bullet) while True: team.drawGroup(screen) otherteam.drawGroup(screen) bullet_list.update(target) bullet_list.draw(screen) pygame.display.update() fpsTime.tick(FPS) if bullet.rect.colliderect(target.rect): bullet.erase(screen) team.drawGroup(screen) otherteam.drawGroup(screen) damage = i.attack(target) draw_damage(damage,target,screen) pygame.display.update() pygame.time.delay(500) bullet_list.remove(bullet) if not target.active: #Erase the Target If Dead pygame.draw.rect(screen,BLACK,target.rect) team.drawGroup(screen) otherteam.drawGroup(screen) pygame.display.update() break elif i.ranged == False: orgx = i.rect.x orgy = i.rect.y i.update(screen, target) damage = i.attack(target) draw_damage(damage,target,screen) # Draw the unit draw_unit(screen, i) pygame.display.update() pygame.time.delay(500) if not target.active: screen.blit(bg,(target.rect.x,target.rect.y), (target.rect.x,target.rect.y,80,80)) screen.blit(bg,(i.rect.x, i.rect.y), (i.rect.x, i.rect.y,80,80)) pygame.display.update() i.rect.x = orgx i.rect.y = orgy team.drawGroup(screen) otherteam.drawGroup(screen) pygame.display.update() pygame.time.delay(500) else: damage = i.attack(target) except (IndexError): pass
def _fire_bullet(self): """Создание нового снаряда и включение его в группу bullets.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet)
def shoot(): """Creates a new friendly bullet at the player's location if too many don't exist already """ if len(good_bullets) < max_player_bullets: new_bullet = Bullet(window_size, bullet_filename, bullet_speed, player.rect.center, NORTH) new_bullet.add(good_bullets)
bullet_sprites = pygame.sprite.RenderUpdates() # 创建sprite容器 树 AddEnemy = pygame.USEREVENT + 1 #添加子弹的时间 pygame.time.set_timer(AddEnemy, 1000) #画圆 pygame.draw.rect(screen, [255, 0, 0], [250, 150, 300, 200], 0) pygame.display.flip() while True: clock.tick(60) screen.fill((48, 144, 144)) #背景色 screen.blit(airplane.image, airplane.rect) for event in pygame.event.get(): if event.type == pygame.QUIT: exit() elif event.type == AddEnemy: bullet_sprites.add(Bullet(screen, airplane)) elif event.type == pygame.K_BACKSPACE: loadgameover(count_num) # 获取键盘状态 pressed_keys = pygame.key.get_pressed() #调用方法更新 airplane.update(pressed_keys) #场景动画更新 bullet_sprites.update() bullet_updates = bullet_sprites.draw(screen) pygame.display.update(bullet_updates) #子弹和病毒组的碰撞 # hit_list = pygame.sprite.groupcollide(bullet_sprites, viral_sprites, True, False) # if hit_list: # bullet_sprites[0].kill()
class DeflectouchWidget(Widget): app = ObjectProperty(None) version = StringProperty(VERSION) level = NumericProperty(1) lives = NumericProperty(3) bullet = None setting_popup = None stockbar = None deflector_list = [] obstacle_list = [] goal_list = [] max_stock = 0 level_build_index = 0 ''' #################################### ## ## GUI Functions ## #################################### ''' def fire_button_pressed(self): if self.bullet: # if there is already a bullet existing (which means it's flying around or exploding somewhere) # don't fire. return self.app.sound['bullet_start'].play() # create a bullet, calculate the start position and fire it. tower_angle = radians(self.tank.tank_tower_scatter.rotation) tower_position = self.tank.pos bullet_position = (tower_position[0] + 48 + cos(tower_angle) * 130, tower_position[1] + 70 + sin(tower_angle) * 130) self.bullet = Bullet(angle=tower_angle) self.bullet.center = bullet_position self.add_widget(self.bullet) self.bullet.fire() def reset_button_pressed(self): self.app.sound['reset'].play() self.reset_level() def level_button_pressed(self): self.app.sound['switch'].play() # create a popup with all the levels grid_layout = GridLayout(cols=8,rows=5,spacing=10, padding=10) enable_next_row = True row_not_complete = False for row in range(5): for collumn in range(8): button = Button(text=str(row*8 + (collumn + 1)),bold=True,font_size=30) if enable_next_row == True: # if this row is already enabled: button.bind(on_press=self.load_level) if self.app.config.get('GamePlay', 'Levels')[row*8 + collumn] == '1': # if level was already done, green button button.background_color = (0, 1, 0, 1) else: # if level not yet done but enabled though, red button button.background_color = (1, 0, 0, 0.5) # and do NOT enable the next row then: row_not_complete = True else: # if not yet enabled: button.background_color = (0.1, 0.05, 0.05, 1) grid_layout.add_widget(button) if row_not_complete == True: enable_next_row = False popup = Popup(title='Level List (if you finished a row, the next row will get enabled!)', content=grid_layout, size_hint=(0.5, 0.5)) popup.open() def settings_button_pressed(self): self.app.sound['switch'].play() # the first time the setting dialog is called, initialize its content. if self.setting_popup is None: self.setting_popup = Popup(attach_to=self, title='DeflecTouch Settings', size_hint=(0.3, 0.5)) self.setting_dialog = SettingDialog(root=self) self.setting_popup.content = self.setting_dialog self.setting_dialog.music_slider.value = boundary(self.app.config.getint('General', 'Music'), 0, 100) self.setting_dialog.sound_slider.value = boundary(self.app.config.getint('General', 'Sound'), 0, 100) self.setting_dialog.speed_slider.value = boundary(self.app.config.getint('GamePlay', 'BulletSpeed'), 1, 10) self.setting_popup.open() def display_help_screen(self): # display the help screen on a Popup image = Image(source='graphics/help_screen.png') help_screen = Popup(title='Quick Guide through DEFLECTOUCH', attach_to=self, size_hint=(0.98, 0.98), content=image) image.bind(on_touch_down=help_screen.dismiss) help_screen.open() ''' #################################### ## ## Game Play Functions ## #################################### ''' def bullet_exploding(self): self.app.sound['explosion'].play() # create an animation on the old bullets position: # bug: gif isn't transparent #old_pos = self.bullet.center #self.bullet.anim_delay = 0.1 #self.bullet.size = 96, 96 #self.bullet.center = old_pos #self.bullet.source = 'graphics/explosion.gif' #Clock.schedule_once(self.bullet_exploded, 1) self.remove_widget(self.bullet) self.bullet = None # or should i write del self.bullet instead? self.lives -= 1 if self.lives == 0: self.reset_level() def level_accomplished(self): self.app.sound['accomplished'].play() # store score in config: (i have to convert the string to a list to do specific char writing) levels_before = list(self.app.config.get('GamePlay', 'Levels')) levels_before[self.level - 1] = '1' self.app.config.set('GamePlay', 'Levels', "".join(levels_before)) self.app.config.write() # show up a little image with animation: size*2 and out_bounce and the wait 1 sec image = Image(source='graphics/accomplished.png', size_hint=(None, None), size=(200, 200)) image.center=self.center animation = Animation(size=(350, 416), duration=1, t='out_bounce') animation &= Animation(center=self.center, duration=1, t='out_bounce') animation += Animation(size=(350, 416), duration=1) # little hack to sleep for 1 sec self.add_widget(image) animation.start(image) animation.bind(on_complete=self.accomplished_animation_complete) def accomplished_animation_complete(self, animation, widget): self.remove_widget(widget) # open the level dialog? #self.level_button_pressed() # no. just open the next level. if self.level != 40: if self.level % 8 == 0: # if it was the last level of one row, another row has been unlocked! Popup(title='New levels unlocked!', content=Label(text='Next 8 levels unlocked!', font_size=18), size_hint=(0.3, 0.15)).open() self.reset_level() self.load_level(self.level + 1) def reset_level(self): # first kill the bullet if self.bullet != None: self.bullet.unbind(pos=self.bullet.callback_pos) self.bullet.animation.unbind(on_complete=self.bullet.on_collision_with_edge) self.bullet.animation.stop(self.bullet) self.remove_widget(self.bullet) self.bullet = None # then delete all the deflectors. self.background.delete_all_deflectors() # now the user can begin once again with 3 lives: self.lives = 3 def load_level(self, level): BRICK_WIDTH = self.height / 17.73 LEVEL_OFFSET = [self.center_x - (LEVEL_WIDTH/2) * BRICK_WIDTH, self.height / 12.5] # i have to check if the function is called by a level button in the level popup OR with an int as argument: if not isinstance(level, int): level = int(level.text) # and if the function was called by a button, play a sound self.app.sound['select'].play() # try to load the level image try: level_image = kivy.core.image.Image.load('levels/level%02d.png' % level, keep_data=True) except Exception, e: error_text = 'Unable to load Level %d!\n\nReason: %s' % (level, e) Popup(title='Level loading error:', content=Label(text=error_text, font_size=18), size_hint=(0.3, 0.2)).open() return # First of all, delete the old level: self.reset_level() for obstacle in self.obstacle_list: self.background.remove_widget(obstacle) self.obstacle_list = [] for goal in self.goal_list: self.background.remove_widget(goal) self.goal_list = [] if self.stockbar != None: self.remove_widget(self.stockbar) self.max_stock = 0 # set level inital state self.lives = 3 self.level = level for y in range(LEVEL_HEIGHT, 0, -1): for x in range(LEVEL_WIDTH): color = level_image.read_pixel(x, y) if len(color) > 3: # if there was transparency stored in the image, cut it. color.pop() if color == [0, 0, 0]: # create obstacle brick on white pixels image = Image(source=('graphics/brick%d.png' % randint(1, 4)), x = LEVEL_OFFSET[0] + x * BRICK_WIDTH, y = LEVEL_OFFSET[1] + (y-1) * BRICK_WIDTH, size = (BRICK_WIDTH, BRICK_WIDTH), allow_stretch = True) self.obstacle_list.append(image) # the actual widget adding is done in build_level() #self.background.add_widget(image) elif color == [0, 0, 1]: # create a goal brick on blue pixels image = Image(source=('graphics/goal%d.png' % randint(1, 4)), x = LEVEL_OFFSET[0] + x * BRICK_WIDTH, y = LEVEL_OFFSET[1] + (y-1) * BRICK_WIDTH, size = (BRICK_WIDTH, BRICK_WIDTH), allow_stretch = True) self.goal_list.append(image) # the actual widget adding is done in build_level() #self.background.add_widget(image) # but in the lowermost row there is also stored the value for the maximum stock for x in range(LEVEL_WIDTH): color = level_image.read_pixel(x, 0) if len(color) > 3: # if there was transparency stored in the image, cut it. color.pop() if color == [1, 0, 0]: self.max_stock += 1 # now i set up the stockbar widget: self.max_stock = self.max_stock * self.width/1.4/LEVEL_WIDTH self.stockbar = Stockbar(max_stock=self.max_stock, x=self.center_x-self.max_stock/2, center_y=self.height/16 + 20) self.add_widget(self.stockbar) # now start to build up the level: self.level_build_index = 0 if len(self.obstacle_list) != 0: Clock.schedule_interval(self.build_level, 0.01)
def fire_bullet(ai_settings, screen, ship, bullets): '''如果还没有达到限制,就发射一颗子弹''' # 创建新子弹, 并将其键入到编组bullets中 if len(bullets) < ai_settings.bullets_allowed: new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet)
def play(window, options): window_rect = window.get_rect() options["Textures"].load_texture_pack(options["Textures"].pack) player = Shooter(window=window, texture=options["Textures"]) player.set_position(WINDOW_SIZE[0]/2, WINDOW_SIZE[1]*0.90) player.options = options player_group = pygame.sprite.Group() player_group.add(player) target_group = generate_targets(player, WINDOW_SIZE, Levels) bullet_group = pygame.sprite.Group() clock = pygame.time.Clock() FPS = player.options["Difficulty"] timeouts = { "Target Movement":[FPS*0.65,FPS*0.65], "Powerup":[FPS*15, FPS*15] } init_sounds() if options["Sounds"]: Sounds["main"].play(loops=-1) #Start background music logging.info("Game Started.") PLAYING_GAME = True while PLAYING_GAME: window.fill((0,0,0)) fired = False for event in pygame.event.get(): if event.type == pygame.QUIT: logging.critical("Exiting Game...") PLAYING_GAME = False return "QUIT" if event.type == pygame.KEYDOWN and event.key in [pygame.K_SPACE, pygame.K_w, pygame.K_UP] and not fired: if player.options["Sounds"]: Sounds["shot"].play() temp = Bullet(player, player.options["Textures"], player.powerup == "BIGGER") bullet_group.add(temp) if player.powerup == "DOUBLE": temp = Bullet(player, player.options["Textures"], player.powerup == "BIGGER") temp.rect.y += 20 bullet_group.add(temp) fired = True keys = pygame.key.get_pressed() if keys[pygame.K_RIGHT] or keys[pygame.K_d]: if player.powerup == "SPEED": player.move(player.speed * 1.5) else: player.move(player.speed) if keys[pygame.K_LEFT] or keys[pygame.K_a]: if player.powerup == "SPEED": player.move(-player.speed*1.5) else: player.move(-player.speed) if keys[pygame.K_KP4] and keys[pygame.K_KP5] and keys[pygame.K_KP6] and player.OP: temp = Bullet(player, player.options["Textures"], False) bullet_group.add(temp) if keys[pygame.K_r] and [pygame.K_9] and [pygame.K_k] and player.OP: eggs.r9k(window) if keys[pygame.K_KP4] and keys[pygame.K_KP2] and keys[pygame.K_KP0] and keys[pygame.K_o] and keys[pygame.K_p] and not player.OP: if player.options["Sounds"]: Sounds["main"].stop() Sounds["OP"].play(loops=-1) player.OP = True player.change_colour((255,96,0)) logging.warn("OP mode engaged.") if keys[pygame.K_KP_MINUS] and player.OP: if player.options["Sounds"]: Sounds["OP"].stop() Sounds["main"].play(loops=-1) player.OP = False player.reset_image() logging.warn("OP mode disabled.") for sprite in bullet_group: sprite.update() if sprite.rect.y < 0 or (sprite.rect.y > player.rect.y and sprite.type == "TARGET"): bullet_group.remove(sprite) for bullet in bullet_group: hit_list = pygame.sprite.spritecollide(bullet, target_group, False) for target in hit_list: if bullet.type != "TARGET": target.lives -= 1 if target.lives <= 0: target_group.remove(target) player.score += 1 bullet_group.remove(bullet) if target.lives <= 0 and target.type == "POWERUP": player.powerup = POWERUPS[randint(0,len(POWERUPS)-1)] logging.info("Powerup set to {}".format(player.powerup)) hit_list = pygame.sprite.spritecollide(bullet, player_group, False) for player in hit_list: if bullet.type == "TARGET": bullet_group.remove(bullet) logging.info("You were hit by a target's bullet!") if not player.OP: player.lives -= 1 if player.lives <= 0: return "LIVES" if timeouts["Target Movement"][0] <=0: drop_targets = False for target in target_group: target.move() if target.rect.x <= 30 or target.rect.x >=WINDOW_SIZE[0] - target.width/2 - 30: drop_targets = True if target.rect.y >= player.rect.y + target.height/2: PLAYING_GAME = False return "PLAYER COLLISION" if drop_targets: logging.debug("The targets are moving down a level!") for target in target_group: target.drop() timeouts["Target Movement"][0] = timeouts["Target Movement"][1] if timeouts["Powerup"][0] <= 0: timeouts["Powerup"][0] = timeouts["Powerup"][1] if player.powerup == "SCORE": player.score += 10 player.powerup = "" elif player.powerup == "LIVES": player.lives += 1 player.powerup = "" for target in target_group: if target.type == "SHOOTER": if randint(0,600) > 1: continue temp = Bullet(target, player.options["Textures"], False) temp.type="TARGET" temp.image = pygame.transform.scale(player.options["Textures"].get_texture("TARGET_BULLET"), (temp.width, temp.height)) x,y = temp.rect.x, temp.rect.y temp.rect = temp.image.get_rect() temp.set_position(x,y) temp.speed = -1 #So it shoots down! bullet_group.add(temp) if len(target_group) == 0: #If all current players are gone. player.level += 1 Sounds["main"].set_volume(0.5) target_group = generate_targets(player, WINDOW_SIZE, Levels) target_group.draw(window) bullet_group.empty() pygame.display.update() sleep(0.75) Sounds["main"].set_volume(1.0) update_score(window, player.score) update_level(window, player.level) update_lives(window, player.lives) target_group.draw(window) bullet_group.draw(window) player_group.draw(window) for key, value in timeouts.items(): value[0] -= 1 pygame.display.update() clock.tick(FPS)
class Board(QFrame): BoardWidth = 1200 BoardHeight = 850 def __init__(self, parent): super().__init__(parent) self.initBoard() def initBoard(self): '''initiates board''' self.q = Queue() self.qB = Queue() # setting timer for players self.timer = QBasicTimer() self.timer.start(20, self) # setting timer for birds self.timerBirds = QBasicTimer() self.timerBirds.start(BIRD_SPEED, self) self.timerBirdsID = self.timerBirds.timerId() # setting timer for birds bullets self.timerBird_bullet = QBasicTimer() self.timerBird_bullet.start(BIRD_BULLET_SPEED, self) self.timerBird_bulletID = self.timerBird_bullet.timerId() self.timerCounter = 0 self.timerCounterBullets = 0 # counter for levels self.lvl = 1 self.nextLvl = False # setting label for showing number of levels self.lvlLabel = QLabel(self) pic = QPixmap('level.png') pic = pic.scaled(125, 65) self.lvlLabel.setPixmap(pic) self.lvlLabel.move(450, 20) self.lvlNumberLabel = QLabel(self) self.changeLvlNumber() self.lvlNumberLabel.move(600, 22) self.lvlNumberLabel2 = QLabel(self) pic = QPixmap('blue-watercolor-number-1B.png') pic = pic.scaled(25, 60) self.lvlNumberLabel2.setPixmap(pic) self.lvlNumberLabel2.move(630, 22) self.lvlNumberLabel2.hide() # setting label for showing who's winner self.winnerLabel = QLabel(self) pic = QPixmap('winner.png') pic = pic.scaled(700, 60) self.winnerLabel.setPixmap(pic) self.winnerLabel.move(190, 530) self.winnerLabel.hide() self.winnerNumLabel = QLabel(self) pic = QPixmap('blue-watercolor-number-0B.png') pic = pic.scaled(25, 60) self.winnerNumLabel.setPixmap(pic) self.winnerNumLabel.move(925, 530) self.winnerNumLabel.hide() self.noWinnerLabel = QLabel(self) pic = QPixmap('nowinner.png') pic = pic.scaled(500, 60) self.noWinnerLabel.setPixmap(pic) self.noWinnerLabel.move(340, 530) self.noWinnerLabel.hide() # setting curent value for birds speed and bullets speed self.curBirdSpeed = 30 self.curBirdBulletSpeed = 10 self.bigBird = Bird(self, -55, 80, 70, 70) self.bigBirdUp = True self.bigBirdHit = False #self.bigBirdStarted = False self.bigBirdFlying = False self.bigBird.setGeometry(10, 100, 70, 70) self.bigBird.hide() # initializing 3x10 birds, their directions, counter for number of hitted ones, bullets they have and number of ones they fired self.birds = [Bird(self, 0, 0, 50, 50) for i in range(NUM_BIRDS)] self.BirdsGoingLeft = True self.BirdsGoingRight = False self.wingsUp = [True for i in range(NUM_BIRDS)] self.bird_hit = [False for i in range(NUM_BIRDS)] self.dead_count = 0 self.bird_bullets = [ Bullet(self, 0, 0, 'Poop-512.png') for i in range(NUM_BIRDS) ] self.bird_bullets_fired = [False for i in range(NUM_BIRDS)] self.ColumnDown = [False for i in range(10)] self.leftBirdsWall = 9 self.rightBirdsWall = 0 self.rowDown = 2 self.rowGone = False self.setUpGame() # initializing 2 players, their bullets, flags for firing bullets, hitting birds, touching another label, being dead and checking which key is pressed self.player1 = Player(self, 1100, 750, 1110, 'planeW.gif') self.player2 = Player(self, 50, 750, 0, 'planeG.gif') self.bullet1 = Bullet(self, 1120, 740, 'bullet.png') self.bullet1.hide() self.bullet2 = Bullet(self, 70, 740, 'bullet.png') self.bullet2.hide() self.isFired1 = False self.isFired2 = False self.labelsTouching1 = False self.labelsTouching2 = False self.hitBird1 = False self.hitBird2 = False self.noWinner = False self.isDead = 0 self.isDead1 = False self.isDead2 = False self.gameOver = False self.keys_pressed = set() self.startProcess() self.setFocusPolicy(Qt.StrongFocus) def closeProcess(self): print("close T") self.q.put("CLOSE") def startProcess(self): self.p = Process(target=calculateBigBird, args=[self.q]) # self.pBirds = Process(target=calculateBirds, args=[self.q]) self.p.start() # self.pBirds.start() # method for setting up game -> place birds on board in formation def setUpGame(self): j = 0 i = 0 for z in range(NUM_BIRDS): self.birds[z].setX(1100 - i * 65) self.birds[z].setY(150 + j * 55) self.birds[z].setGeo() self.bird_bullets[z].set_bullets(1125 - i * 80, 205 + j * 80) self.bird_bullets[z].hide() i += 1 if (i != 0 and i % 10 == 0): j += 1 i = 0 # method for updating game def game_update(self): self.checkNeighbors() self.timerCounter += 1 self.timerCounterBullets += 1 if (self.timerCounter % 14 == 0) and self.bigBirdFlying and self.bigBirdHit is False: self.timerCounter = 0 self.flyBigBird() if (self.timerCounterBullets % 75 == 0): self.update_bullets() self.timerCounterBullets = 0 # -> checks which player has fired bullet and calls responding method if self.isFired1: self.isFired1 = self.fireBullet(self.bullet1, self.bullet1.y - BULLET_SPEED, True) else: self.bullet1.hide() self.hitBird1 = False if self.isFired2: self.isFired2 = self.fireBullet(self.bullet2, self.bullet2.y - BULLET_SPEED, True) else: self.bullet2.hide() self.hitBird2 = False # -> checks if bird has been hitted and sets her at responding position if self.hitBird1: self.bullet1.y = 0 self.bullet1.x = 0 self.bullet1.hide() if self.hitBird2: self.bullet2.y = 0 self.bullet2.x = 0 self.bullet2.hide() # -> checks flags to know if it needs to stop game and display winner if self.isDead1 is True and self.isDead2 is True: self.gameOver = True if (self.player1.num_lifes > 0 and self.player2.num_lifes > 0): self.noWinner = True self.endGame() # -> checks which key is being pressed and calls responding method to move player in wanted direction if Qt.Key_Left in self.keys_pressed: self.MovePlayer(self.player1, self.player1.x - 20, 'planeWLeft.gif') if Qt.Key_Right in self.keys_pressed: self.MovePlayer(self.player1, self.player1.x + 20, 'planeWRight.gif') if Qt.Key_A in self.keys_pressed: self.MovePlayer(self.player2, self.player2.x - 20, 'planeGLeft.gif') if Qt.Key_D in self.keys_pressed: self.MovePlayer(self.player2, self.player2.x + 20, 'planeGRight.gif') # -> checks if player is alive and sets position for bullet to be fired if Qt.Key_Up in self.keys_pressed and self.isFired1 is False and self.isDead1 is False: self.bullet1.y = self.player1.y - 15 self.bullet1.x = self.player1.x + 20 self.bullet1.move(self.bullet1.x, self.bullet1.y) self.bullet1.show() self.isFired1 = True if Qt.Key_W in self.keys_pressed and self.isFired2 is False and self.isDead2 is False: self.bullet2.y = self.player2.y - 15 self.bullet2.x = self.player2.x + 20 self.bullet2.move(self.bullet2.x, self.bullet2.y) self.bullet2.show() self.isFired2 = True # -> checks if there's need to update game to new level, if bird's bullet has hit the player, which player has hit the bird for i in range(NUM_BIRDS): if (self.dead_count == 30 and (self.isDead1 is False or self.isDead2 is False)): self.nextLvl = True self.lvl += 1 self.curBirdSpeed += 2 if (self.lvl % 3 == 0): self.curBirdBulletSpeed += 2 self.bigBird.move(-55, 80) self.bigBird.hide() # self.bigBirdStarted = False self.bigBirdFlying = False self.changeLvlNumber() if self.isDead1 is False: self.player1.num_lifes = 3 for i in range(self.player1.num_lifes): self.player1.lifes[i].show() if self.isDead2 is False: self.player2.num_lifes = 3 for i in range(self.player2.num_lifes): self.player2.lifes[i].show() self.setUpGame() self.BirdsGoingLeft = True self.BirdsGoingRight = False self.wingsUp = [True for i in range(NUM_BIRDS)] self.bird_hit = [False for i in range(NUM_BIRDS)] self.dead_count = 0 self.bird_bullets_fired = [False for i in range(NUM_BIRDS)] self.ColumnDown = [False for i in range(10)] self.leftBirdsWall = 9 self.rightBirdsWall = 0 if self.isDead1 is False: self.player1.x = 1100 self.player1.y = 750 self.player1.move(self.player1.x, self.player1.y) if self.isDead2 is False: self.player2.x = 50 self.player2.y = 750 self.player2.move(self.player2.x, self.player2.y) if self.bird_bullets_fired[i] and self.bird_hit[i] is False: if self.areLabelsTouching( self.bird_bullets[i], self.player1) is False and self.areLabelsTouching( self.bird_bullets[i], self.player2) is False: self.bird_bullets_fired[i] = self.fireBullet( self.bird_bullets[i], self.bird_bullets[i].y + self.curBirdBulletSpeed, False) elif self.areLabelsTouching(self.bird_bullets[i], self.player2): self.player2.move(50, 750) self.player2.x = 50 self.player2.num_lifes -= 1 self.player2.lifes[self.player2.num_lifes].hide() self.bird_bullets_fired[i] = False self.bird_bullets[i].hide() if self.player2.num_lifes == 0: self.isDead2 = True self.isDead = 2 self.player2.setParent(None) elif self.areLabelsTouching(self.bird_bullets[i], self.player1): self.player1.move(1100, 750) self.player1.x = 1100 self.player1.num_lifes -= 1 self.player1.lifes[self.player1.num_lifes].hide() self.bird_bullets_fired[i] = False self.bird_bullets[i].hide() if self.player1.num_lifes == 0: self.isDead1 = True self.isDead = 1 self.player1.setParent(None) if self.gameOver: self.birds[i].hide() self.bird_bullets[i].hide() if (self.bird_hit[i]): self.birds[i].hide() self.bird_bullets[i].hide() else: value = self.detectCollision(self.birds[i], self.bullet1, self.bullet2) if (value == 1): self.dead_count += 1 print(self.dead_count) self.hitBird1 = True self.bird_hit[i] = True if (value == 2): self.dead_count += 1 print(self.dead_count) self.hitBird2 = True self.bird_hit[i] = True if self.bigBirdFlying: value = self.detectCollision(self.bigBird, self.bullet1, self.bullet2) if (value == 1 and self.player1.num_lifes < 3): self.bigBirdHit = True self.bigBird.hide() if self.player1.num_lifes < 3: self.player1.num_lifes += 1 self.player1.lifes[self.player1.num_lifes - 1].show() if (value == 2 and self.player2.num_lifes < 3): self.bigBirdHit = True self.bigBird.hide() if self.player2.num_lifes < 3: self.player2.num_lifes += 1 self.player2.lifes[self.player2.num_lifes].show() # method for checking if there's been collision between two labels def areLabelsTouching(self, label1, label2): self.label1 = label1 self.label2 = label2 if self.label2.x <= self.label1.x <= self.label2.x + self.label2.dimX and self.label1.y + self.label1.dimY >= \ self.label2.y: return True elif self.label2.x <= self.label1.x + self.label1.dimX <= self.label2.x + self.label2.dimX and self.label1.y + \ self.label1.dimY >= self.label2.y: return True else: return False def startBigBird(self): chance = random.randint(1, 100) #chance = 10 if (chance < 10): #self.bigBirdStarted = True self.bigBird.move(-55, 80) self.bigBirdFlying = True #!!!!!!!!! def flyBigBird(self): if self.bigBird.x < 1200: self.q.put(self.bigBird.x) pos = self.q.get() self.bigBird.move(pos, self.bigBird.y) #self.bigBird.move(self.bigBird.x + BIGBIRD_SPEED, self.bigBird.y) if self.bigBirdHit is False: self.FlightPicture(self.bigBird, self.bigBirdUp, False) else: self.bigBird.hide() if self.bigBirdUp: self.bigBirdUp = False else: self.bigBirdUp = True else: self.bigBirdFlying = False self.bigBird.hide() def checkNeighbors(self): for i in range(self.rightBirdsWall, self.leftBirdsWall): if (self.bird_hit[i] is False or self.bird_hit[i + 10] is False or self.bird_hit[i + 20] is False): break else: self.rightBirdsWall = i + 1 for j in range(self.leftBirdsWall, self.rightBirdsWall, -1): if (self.bird_hit[j] is False or self.bird_hit[j + 10] is False or self.bird_hit[j + 20] is False): break else: self.leftBirdsWall = j - 1 # method for birds movement formation def update_birds(self): if (self.bigBirdFlying is False): self.startBigBird() #if self.rowGone: # self.rowDown -= 1 # self.rowGone = False if (self.BirdsGoingLeft): newX1 = self.birds[self.leftBirdsWall].x - 30 newX2 = self.birds[self.leftBirdsWall + 10].x - 30 newX3 = self.birds[self.leftBirdsWall + 20].x - 30 newY = self.birds[self.leftBirdsWall].y - 30 #idx = 10 * self.rowDown #bottomY = self.birds[self.leftBirdsWall].y + 30 #if(self.birds[bottomY] > 720): # self.isDead1 = True # self.isDead2 = True if self.gameOver is False: if (newX1 > 0 and newX2 > 0 and newX3 > 0): for i in range(NUM_BIRDS): if self.bird_hit[i] is False: #self.qB.put(self.birds[i].x) #self.qB.put("SPEED") #self.qB.put(self.curBirdSpeed) #move = self.qB.get() #self.birds[i].move(move, self.birds[i].y) self.birds[i].move( self.birds[i].x - self.curBirdSpeed, self.birds[i].y) self.FlightPicture(self.birds[i], self.wingsUp[i], True) if (self.wingsUp[i]): self.wingsUp[i] = False else: self.wingsUp[i] = True else: self.birds[i].hide() else: for i in range(NUM_BIRDS): if self.bird_hit[i] is False: self.birds[i].move( self.birds[i].x, self.birds[i].y + self.curBirdSpeed) self.FlightPicture(self.birds[i], self.wingsUp[i], False) if (self.wingsUp[i]): self.wingsUp[i] = False else: self.wingsUp[i] = True self.BirdsGoingLeft = False self.BirdsGoingRight = True else: self.birds[i].hide() else: for i in range(NUM_BIRDS): self.birds[i].hide() elif (self.BirdsGoingRight): newX1 = self.birds[self.rightBirdsWall].x + 30 newX2 = self.birds[self.rightBirdsWall + 10].x + 30 newX3 = self.birds[self.rightBirdsWall + 20].x + 30 newY = self.birds[0].y + 30 idx = 10 * self.rowDown #bottomY = self.birds[idx].y + 30 #if(self.birds[bottomY] > 720): # self.isDead1 = True # self.isDead2 = True if self.gameOver is False: if (newX1 < 1100 and newX2 < 1100 and newX3 < 1100): for i in range(NUM_BIRDS): if self.bird_hit[i] is False: self.birds[i].move( self.birds[i].x + self.curBirdSpeed, self.birds[i].y) self.FlightPicture(self.birds[i], self.wingsUp[i], False) if (self.wingsUp[i]): self.wingsUp[i] = False else: self.wingsUp[i] = True else: self.birds[i].hide() else: for i in range(NUM_BIRDS): if self.bird_hit[i] is False: self.birds[i].move( self.birds[i].x, self.birds[i].y + self.curBirdSpeed) self.FlightPicture(self.birds[i], self.wingsUp[i], True) if (self.wingsUp[i]): self.wingsUp[i] = False else: self.wingsUp[i] = True self.BirdsGoingLeft = True self.BirdsGoingRight = False else: self.birds[i].hide() else: for i in range(NUM_BIRDS): self.birds[i].hide() # method for changing picture of a bird to mimic winds movement def FlightPicture(self, bird, wUp, left): if (wUp): picture = QPixmap("13g.gif") else: picture = QPixmap("18g.gif") if (left): picture = picture.transformed(QTransform().scale(-1, 1)) picture = picture.scaled(50, 50) bird.setPixmap(picture) # method for birds randomly firing bullets def update_bullets(self): for i in range(NUM_BIRDS): choice = False number = random.randint(1, 200) if (number < 10): choice = True if (choice and self.bird_bullets_fired[i] is False): self.bird_bullets[i].x = self.birds[i].x + 50 self.bird_bullets[i].y = self.birds[i].y + 55 self.bird_bullets[i].move(self.bird_bullets[i].x, self.bird_bullets[i].y) self.bird_bullets[i].show() self.bird_bullets_fired[i] = True # method for detecting key being pressed and adding that event to array of pressed keys def keyPressEvent(self, event): self.keys_pressed.add(event.key()) # method for detecting released pressed key and removing that event from array of pressed keys def keyReleaseEvent(self, event): self.keys_pressed.remove(event.key()) key = event.key() if key == Qt.Key_Left: self.changePicture(self.player1, 'planeW.gif') if key == Qt.Key_Right: self.changePicture(self.player1, 'planeW.gif') if key == Qt.Key_A: self.changePicture(self.player2, 'planeG.gif') if key == Qt.Key_D: self.changePicture(self.player2, 'planeG.gif') # method for moving players within the range of board when keys are pressed def MovePlayer(self, player, newX, newPicture): if newX < Board.BoardWidth - 60 and newX > 10: self.player = player self.changePicture(self.player, newPicture) self.player.x = newX self.player.move(newX, self.player.y) self.show() # method for changing picture of a player to mimic movement in requested direction def changePicture(self, label, newPicture): picture = QPixmap(newPicture) picture = picture.scaled(40, 60) label.setPixmap(picture) # method for ending game and showing result def endGame(self): self.end = EndGame(self) if (self.noWinner is False): if self.isDead == 2: pic = QPixmap('blue-watercolor-number-2B.png') else: pic = QPixmap('blue-watercolor-number-1B.png') pic = pic.scaled(25, 60) self.winnerNumLabel.setPixmap(pic) self.winnerLabel.show() self.winnerNumLabel.show() else: self.noWinnerLabel.show() self.end.show() self.lvlLabel.hide() self.lvlNumberLabel.hide() self.lvlNumberLabel2.hide() self.player1.hide() self.player2.hide() for i in range(self.player1.num_lifes): self.player1.lifes[i].hide() for i in range(self.player2.num_lifes): self.player2.lifes[i].hide() # method for changing number of level def changeLvlNumber(self): if (self.lvl > 9 and self.lvl < 100): strLvl = str(self.lvl) pic1 = QPixmap('blue-watercolor-number-' + strLvl[0] + 'B.png') pic2 = QPixmap('blue-watercolor-number-' + strLvl[1] + 'B.png') pic1 = pic1.scaled(25, 60) pic2 = pic2.scaled(25, 60) self.lvlNumberLabel.setPixmap(pic1) self.lvlNumberLabel2.setPixmap(pic2) self.lvlNumberLabel.show() self.lvlNumberLabel2.show() else: pic = QPixmap('blue-watercolor-number-' + str(self.lvl) + 'B.png') pic = pic.scaled(25, 60) self.lvlNumberLabel.setPixmap(pic) self.lvlNumberLabel.show() # method for player firing bullets def fireBullet(self, bullet, newY, player): self.bullet = bullet if (player): if newY < 10: self.bullet.hide() return False else: self.bullet.move(self.bullet.x, newY) self.bullet.y = newY self.bullet.show() return True elif (newY > 840): self.bullet.hide() return False else: self.bullet.move(self.bullet.x, newY) self.bullet.y = newY self.bullet.show() return True # method for detecting which player has hit the bird def detectCollision(self, label1, label2, label3): self.label1 = label1 self.label2 = label2 detX1_start = self.label1.x detX1_stop = self.label1.x + self.label1.dimX detY1_start = self.label1.y detY1_stop = self.label1.y + self.label1.dimY detX2_start = self.label2.x detX2_stop = self.label2.x + self.label2.dimX detY2_start = self.label2.y detY2_stop = self.label2.y + self.label2.dimY if (detX2_start > detX1_start and detX2_start < detX1_stop): if (detY2_start > detY1_start and detY2_start < detY1_stop): return 1 elif (detY2_stop > detY1_start and detY2_stop < detY1_stop): return 1 elif (detX2_stop > detX1_start and detX2_stop < detX1_stop): if (detY2_start > detY1_start and detY2_start < detY1_stop): return 1 elif (detY2_stop > detY1_start and detY2_stop < detY1_stop): return 1 self.label2 = label3 detX1_start = self.label1.x detX1_stop = self.label1.x + self.label1.dimX detY1_start = self.label1.y detY1_stop = self.label1.y + self.label1.dimY detX2_start = self.label2.x detX2_stop = self.label2.x + self.label2.dimX detY2_start = self.label2.y detY2_stop = self.label2.y + self.label2.dimY if (detX2_start > detX1_start and detX2_start < detX1_stop): if (detY2_start > detY1_start and detY2_start < detY1_stop): return 2 elif (detY2_stop > detY1_start and detY2_stop < detY1_stop): return 2 elif (detX2_stop > detX1_start and detX2_stop < detX1_stop): if (detY2_start > detY1_start and detY2_start < detY1_stop): return 2 elif (detY2_stop > detY1_start and detY2_stop < detY1_stop): return 2 return -1 # method for initiazing game update according to timer event def timerEvent(self, event): if self.gameOver is False: self.game_update() if (self.timerBirdsID == event.timerId()): self.update_birds() #if(self.timerBird_bulletID == event.timerId()): # self.update_bullets() self.update()
def main(): pygame.init() ak47_sound = pygame.mixer.Sound('sounds/ak47-1.ogg') ak_reload3 = pygame.mixer.Sound('sounds/ak47_boltpull.ogg') empty_pistolsound = pygame.mixer.Sound('sounds/clipempty_pistol.ogg') LetItGo = pygame.mixer.Sound('sounds/LetItGo.ogg') moosound = pygame.mixer.Sound('sounds/moosound.ogg') starsound = pygame.mixer.Sound('sounds/Ding.ogg') bg_p1won = pygame.image.load('images/winner.png') bg_p2won = pygame.image.load('images/loserkeenanwon.png') bg_p3won = pygame.image.load('images/loserkeenan2.0.png') bg = pygame.image.load('images/WesternBackgroundTest2.png') size = width, height = 1000, 500 screen = pygame.display.set_mode(size) #Creates all sprite group. all_sprites_list = pygame.sprite.Group() # Bullet for Player 1 bullet_list = pygame.sprite.Group() # Bullet for Player 2 bullet_list2 = pygame.sprite.Group() # Bullet for Player 3 bullet_list3 = pygame.sprite.Group() # Cow sprite list cow_sprite_list = pygame.sprite.Group() # Horseshoe sprite list horseshoe_sprite_list = pygame.sprite.Group() # Skull sprite list skull_sprite_list = pygame.sprite.Group() # Ammofloat sprite list ammofloat_sprite_list = pygame.sprite.Group() # Star sprite list star_sprite_list = pygame.sprite.Group() # Tnt sprite list tnt_sprite_list = pygame.sprite.Group() # Dynamite sprite list dynamite_sprite_list = pygame.sprite.Group() # Floating objects moving top floating_objects_list_top = pygame.sprite.Group() # Floating objects moving bottom floating_objects_list_bottom = pygame.sprite.Group() 'Boolean to determine whether they hit a star. If they hit a star, bullet speed increases.' hit = False hitp2 = False hitp3 = False 'Boolean to determine if someone has won the game.' p1won = False p2won = False p3won = False 'Boolean that checks whether or not the game is over and to display a winning condition' gameOver = False LetItGo.play() 'Loads all the floating objects on the top that are moving.' load_HorseShoe_top(floating_objects_list_top, horseshoe_sprite_list, all_sprites_list) load_AmmoObject_top(floating_objects_list_top, ammofloat_sprite_list, all_sprites_list) load_CowObject_top(floating_objects_list_top, cow_sprite_list, all_sprites_list) load_star_top(floating_objects_list_top, star_sprite_list, all_sprites_list) load_dynamite_top(floating_objects_list_top, dynamite_sprite_list, all_sprites_list) load_skull_top(floating_objects_list_top, skull_sprite_list, all_sprites_list) 'Loads all the floating objects on the bottom that are moving.' load_ammo_object_bottom(floating_objects_list_bottom, ammofloat_sprite_list, all_sprites_list) load_skull_bottom(floating_objects_list_bottom, skull_sprite_list, all_sprites_list) load_tnt_bottom(floating_objects_list_bottom, tnt_sprite_list, all_sprites_list) load_cow_bottom(floating_objects_list_bottom, cow_sprite_list, all_sprites_list) load_star_bottom(floating_objects_list_bottom, star_sprite_list, all_sprites_list) load_horseshoe_bottom(floating_objects_list_bottom, horseshoe_sprite_list, all_sprites_list) 'Puts all the floating objects on the top into a single list.' load_floating_objects_top(floating_objects_list_top, all_sprites_list) 'Puts all the floating objects on the bottom into a single list.' load_floating_objects_bottom(floating_objects_list_bottom, all_sprites_list) starlist = [] starlist2 = [] starlist3 = [] 'Creates an ammo sprite group for player 1. This determines the amount of bullet the player starts with.' ammolist = [] ammo_list = pygame.sprite.Group() for i in range(6): oh = Ammo() oh.rect.x = 30 + i*15 oh.rect.y = 450 ammolist.append(oh) ammo_list.add(oh) all_sprites_list.add(oh) 'Creates an ammo sprite group for player 2. This determines the amount of bullet the player starts with.' ammolist2 = [] ammo_list2 = pygame.sprite.Group() for i in range(6): ammo2 = Ammo() ammo2.rect.x = 350 + i*15 ammo2.rect.y = 450 ammolist2.append(ammo2) ammo_list2.add(ammo2) all_sprites_list.add(ammo2) 'Creates an ammo sprite group for player 3. This determines the amount of bullet the player starts with.' ammolist3 = [] ammo_list3 = pygame.sprite.Group() for i in range(6): ammo3 = Ammo() ammo3.rect.x = 730 + i*15 ammo3.rect.y = 450 ammolist3.append(ammo3) ammo_list3.add(ammo3) all_sprites_list.add(ammo3) 'Instantiate the players.' player = Player() player2 = Player2() player3 = Player3() 'Add the players to the all sprites group.' all_sprites_list.add(player) all_sprites_list.add(player2) all_sprites_list.add(player3) 'Set default location of players.' locationplayer1(player) locationplayer2(player2) locationplayer3(player3) 'This updates the score for each player after hitting a sprite.' p1score = 0 p2score = 0 p3score = 0 'This counter helps determine the movement of the computer' counterp2 = 0 counterp3 = 0 'Sets up the default scoresheet when the game starts' gamefont = pygame.font.FontType('Furmanite Bold.ttf', 30) scoretext = gamefont.render('SquirtYay: ' + str(p1score), 2, [255,0,0]) scoretext2 = gamefont.render('Keenan: ' + str(p2score), 2, [255, 255, 255]) scoretext3 = gamefont.render('Keenan 2.0: '+ str(p3score), 2, [37, 171, 27]) boxsize = scoretext.get_rect() boxsize2 = scoretext2.get_rect() boxsize3 = scoretext3.get_rect() scoreXpos = (450-boxsize[2])/2 scoreXpos2 = (550-boxsize2[2]/2) scoreXpos3 = (800-boxsize3[2]/2) 'Determines the time for when player 2 will shoot a bullet.' time_elapsed_since_last_action = 0 'Determines the time for when player 3 will shoot a bullet.' time_elapsed_since_last_action2 = 0 'Creates an object to help track time.' clock = pygame.time.Clock() while True: # <--- main game loop 'Blit the background onto the screen.' screen.blit(bg, (0,0)) 'This updates the score board every time an object is shot at.' scoretext = gamefont.render('SquirtYay: ' + str(p1score), 2, [255,0,0]) scoretext2 = gamefont.render('Keenan: '+str(p2score), 2, [255, 255, 255]) scoretext3 = gamefont.render('Keenan 2.0: '+str(p3score), 2, [37,171,27]) screen.blit(scoretext, [scoreXpos, 20]) screen.blit(scoretext2, [scoreXpos2, 20]) screen.blit(scoretext3, [scoreXpos3, 20]) 'Increase the time while game is on.' dt = clock.tick() time_elapsed_since_last_action += dt time_elapsed_since_last_action2 += dt 'If the game is over display the winning background.' while gameOver == True: if p1won == True: screen.blit(bg_p1won, (0,0)) if p2won == True: screen.blit(bg_p2won, (0,0)) if p3won == True: screen.blit(bg_p3won, (0,0)) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() for event in pygame.event.get(): if event.type == QUIT: # QUIT event to exit the game pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN and len(ammolist) > 0 and gameOver == False: 'Fire a bullet if the user clicks the mouse button' bullet = Bullet() ak47_sound.play() 'Removes ammunition from the list and screen every time the player shoots' if len(ammolist) > 0: newList = ammolist.pop() all_sprites_list.remove(newList) 'Set the bullet so it is where the player is' bullet.rect.x = player.rect.x+65 bullet.rect.y = player.rect.y+10 'Adds the bullet to the lists' all_sprites_list.add(bullet) bullet_list.add(bullet) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_r: for i in range(6): all_sprites_list.remove(ammolist) ammolist.clear() for i in range(6): oh = Ammo() oh.rect.x = 30 + i*15 oh.rect.y = 450 ammolist.append(oh) ammo_list.add(oh) all_sprites_list.add(oh) ak_reload3.play() elif event.type == pygame.MOUSEBUTTONDOWN and len(ammolist) == 0: empty_pistolsound.play() 'This checks for the winning conditions. If someone has won, it will set the game over and whoever won to true. Ending the game.' if p1score >= 70: gameOver = True p1won = True if p2score >= 70: gameOver = True p2won = True if p3score >= 70: gameOver = True p3won = True 'PLAYER 2 ACTIONS' 'Wait until begin shooting.' if time_elapsed_since_last_action > 950: #player 2's Bullet bullet2 = Bullet() ak47_sound.play() bullet2.rect.x = player2.rect.x + 61 bullet2.rect.y = player2.rect.y + 10 'Each time the player shoots an ammo and it is greater than 0. Remove one from the display list.' if len(ammolist2) > 0: newList2 = ammolist2.pop() all_sprites_list.remove(newList2) 'This counter is incremented every time the player shoots to determine when the player will move. ' counterp2 += 1 ' If the player no longer has ammo. Automatically reload the list. ' if len(ammolist2) == 0: empty_pistolsound.play() ak_reload3.play() for i in range(6): ammo2 = Ammo() ammo2.rect.x = 350 + i*15 ammo2.rect.y = 450 ammolist2.append(ammo2) ammo_list2.add(ammo2) all_sprites_list.add(ammo2) all_sprites_list.add(bullet2) bullet_list2.add(bullet2) time_elapsed_since_last_action = 0 #automoveplayer2 automoveplayer2(player2, counterp2) 'Player 3 ACTIONS' if time_elapsed_since_last_action2 > 1200: #player 2's Bullet bullet3 = Bullet() ak47_sound.play() bullet3.rect.x = player3.rect.x + 60 bullet3.rect.y = player3.rect.y + 10 # Removes AMMO from list if len(ammolist3) > 0: newList3 = ammolist3.pop() all_sprites_list.remove(newList3) #counter to move player counterp3 += 1 #print(counterp3) if len(ammolist3) == 0: empty_pistolsound.play() ak_reload3.play() for i in range(6): ammo3 = Ammo() ammo3.rect.x = 730 + i*15 ammo3.rect.y = 450 ammolist3.append(ammo3) ammo_list3.add(ammo3) all_sprites_list.add(ammo3) all_sprites_list.add(bullet3) bullet_list3.add(bullet3) time_elapsed_since_last_action2 = 0 'automoveplayer3' automoveplayer3(player3, counterp3) 'Player 1 sprite collision' for bullet in bullet_list: cow_hit_list = pygame.sprite.spritecollide(bullet, cow_sprite_list, True) horseshoe_hit_list = pygame.sprite.spritecollide(bullet, horseshoe_sprite_list, True) ammo_hit_list = pygame.sprite.spritecollide(bullet, ammofloat_sprite_list, True) skull_hit_list = pygame.sprite.spritecollide(bullet, skull_sprite_list, True) tnt_hit_list = pygame.sprite.spritecollide(bullet, tnt_sprite_list, True) star_hit_list = pygame.sprite.spritecollide(bullet, star_sprite_list, True) dynamite_hit_list = pygame.sprite.spritecollide(bullet, dynamite_sprite_list, True) if hit == False: bullet.bulletspeed(3) else: bullet.bulletspeed(7) 'If the player hits an ammo, it will automatically reload their bullets.' for ammofloat in ammo_hit_list: bullet_list.remove(bullet) all_sprites_list.remove(bullet) ak_reload3.play() for i in range(6): all_sprites_list.remove(ammolist) ammolist.clear() for i in range(6): oh = Ammo() oh.rect.x = 50 + i*15 oh.rect.y = 450 ammolist.append(oh) ammo_list.add(oh) all_sprites_list.add(oh) for horseshoe in horseshoe_hit_list: bullet_list.remove(bullet) all_sprites_list.remove(bullet) p1score += 3 for cow in cow_hit_list: bullet_list.remove(bullet) all_sprites_list.remove(bullet) p1score += 3 moosound.play() ' If the player hits a skull, it will remove the bullets of the other players forcing them to reload.' for skull in skull_hit_list: bullet_list.remove(bullet) all_sprites_list.remove(bullet) for i in range(6): all_sprites_list.remove(ammolist2) ammolist2.clear() for i in range(6): all_sprites_list.remove(ammolist3) ammolist3.clear() for tnt in tnt_hit_list: bullet_list.remove(bullet) all_sprites_list.remove(bullet) p1score += 5 for star in star_hit_list: starsound.play() hit = True bullet_list.remove(bullet) all_sprites_list.remove(bullet) star_obj = Star() star_obj.rect.x = 245 star_obj.rect.y = 440 starlist.append(star_obj) star_sprite_list.add(starlist) all_sprites_list.add(starlist) for dynamite in dynamite_hit_list: bullet_list.remove(bullet) all_sprites_list.remove(bullet) p1score += 5 'Player 2 sprite collision' for bullet2 in bullet_list2: cow_hit_list = pygame.sprite.spritecollide(bullet2, cow_sprite_list, True) horseshoe_hit_list = pygame.sprite.spritecollide(bullet2, horseshoe_sprite_list, True) ammo_hit_list = pygame.sprite.spritecollide(bullet2, ammofloat_sprite_list, True) skull_hit_list = pygame.sprite.spritecollide(bullet2, skull_sprite_list, True) tnt_hit_list = pygame.sprite.spritecollide(bullet2, tnt_sprite_list, True) star_hit_list = pygame.sprite.spritecollide(bullet2, star_sprite_list, True) dynamite_hit_list = pygame.sprite.spritecollide(bullet2, dynamite_sprite_list, True) if hitp2 == False: bullet2.bulletspeed(3) else: bullet2.bulletspeed(7) ' If the player hits an ammo, it will automatically reload their bullets.' for ammofloat in ammo_hit_list: bullet_list2.remove(bullet2) all_sprites_list.remove(bullet2) ak_reload3.play() for i in range(6): all_sprites_list.remove(ammolist2) ammolist2.clear() for i in range(6): ammo2 = Ammo() ammo2.rect.x = 350 + i*15 ammo2.rect.y = 450 ammolist2.append(ammo2) ammo_list2.add(ammo2) all_sprites_list.add(ammo2) for horseshoe in horseshoe_hit_list: bullet_list2.remove(bullet2) all_sprites_list.remove(bullet2) p2score += 3 for cow in cow_hit_list: bullet_list2.remove(bullet2) all_sprites_list.remove(bullet2) p2score += 3 moosound.play() ' If the player hits a skull, it will remove the bullets of the other players forcing them to reload.' for skull in skull_hit_list: bullet_list.remove(bullet2) all_sprites_list.remove(bullet2) for i in range(6): all_sprites_list.remove(ammolist) ammolist.clear() for i in range(6): all_sprites_list.remove(ammolist3) ammolist3.clear() for tnt in tnt_hit_list: bullet_list.remove(bullet2) all_sprites_list.remove(bullet2) p2score += 5 for star in star_hit_list: starsound.play() hitp2 = True bullet_list.remove(bullet2) all_sprites_list.remove(bullet2) star_obj = Star() star_obj.rect.x = 600 star_obj.rect.y = 440 starlist2.append(star_obj) star_sprite_list.add(starlist2) all_sprites_list.add(starlist2) for dynamite in dynamite_hit_list: bullet_list.remove(bullet2) all_sprites_list.remove(bullet2) p2score += 5 'Player 3 sprite collision' for bullet3 in bullet_list3: cow_hit_list = pygame.sprite.spritecollide(bullet3, cow_sprite_list, True) horseshoe_hit_list = pygame.sprite.spritecollide(bullet3, horseshoe_sprite_list, True) ammo_hit_list = pygame.sprite.spritecollide(bullet3, ammofloat_sprite_list, True) skull_hit_list = pygame.sprite.spritecollide(bullet3, skull_sprite_list, True) tnt_hit_list = pygame.sprite.spritecollide(bullet3, tnt_sprite_list, True) star_hit_list = pygame.sprite.spritecollide(bullet3, star_sprite_list, True) dynamite_hit_list = pygame.sprite.spritecollide(bullet3, dynamite_sprite_list, True) if hitp3 == False: bullet3.bulletspeed(6) else: bullet3.bulletspeed(10) ' If the player hits an ammo, it will automatically reload their bullets.' for ammofloat in ammo_hit_list: bullet_list3.remove(bullet3) all_sprites_list.remove(bullet3) ak_reload3.play() for i in range(6): all_sprites_list.remove(ammolist3) ammolist3.clear() for i in range(6): ammo3 = Ammo() ammo3.rect.x = 715 + i*15 ammo3.rect.y = 450 ammolist3.append(ammo3) ammo_list3.add(ammo3) all_sprites_list.add(ammo3) for horseshoe in horseshoe_hit_list: bullet_list3.remove(bullet3) all_sprites_list.remove(bullet3) p3score += 3 for cow in cow_hit_list: bullet_list3.remove(bullet3) all_sprites_list.remove(bullet3) p3score += 3 moosound.play() 'If the player hits a skull, it will remove the bullets of ' 'the other players forcing them to reload.' for skull in skull_hit_list: bullet_list.remove(bullet2) all_sprites_list.remove(bullet2) for i in range(6): all_sprites_list.remove(ammolist) ammolist.clear() for i in range(6): all_sprites_list.remove(ammolist2) ammolist2.clear() for tnt in tnt_hit_list: bullet_list.remove(bullet3) all_sprites_list.remove(bullet3) p3score += 5 for star in star_hit_list: starsound.play() hitp3 = True bullet_list.remove(bullet3) all_sprites_list.remove(bullet3) star_obj = Star() star_obj.rect.x = 940 star_obj.rect.y = 440 starlist3.append(star_obj) star_sprite_list.add(starlist3) all_sprites_list.add(starlist3) for dynamite in dynamite_hit_list: bullet_list.remove(bullet3) all_sprites_list.remove(bullet3) p3score += 5 if len(floating_objects_list_bottom) < 3: for i in floating_objects_list_bottom: i.kill() 'Load all the floating objects moving left after list is 0' load_ammo_object_bottom(floating_objects_list_bottom, ammofloat_sprite_list, all_sprites_list) load_skull_bottom(floating_objects_list_bottom, skull_sprite_list, all_sprites_list) load_tnt_bottom(floating_objects_list_bottom, tnt_sprite_list, all_sprites_list) load_cow_bottom(floating_objects_list_bottom, cow_sprite_list, all_sprites_list) load_star_bottom(floating_objects_list_bottom, star_sprite_list, all_sprites_list) load_horseshoe_bottom(floating_objects_list_bottom, horseshoe_sprite_list, all_sprites_list) load_floating_objects_bottom(floating_objects_list_bottom, all_sprites_list) if len(floating_objects_list_top) < 3: for i in floating_objects_list_top: i.kill() 'Load all the floating objects moving right after list is 0.' load_HorseShoe_top(floating_objects_list_top, horseshoe_sprite_list, all_sprites_list) load_AmmoObject_top(floating_objects_list_top, ammofloat_sprite_list, all_sprites_list) load_CowObject_top(floating_objects_list_top, cow_sprite_list, all_sprites_list) load_star_top(floating_objects_list_top, star_sprite_list, all_sprites_list) load_dynamite_top(floating_objects_list_top, dynamite_sprite_list, all_sprites_list) load_skull_top(floating_objects_list_top, skull_sprite_list, all_sprites_list) load_floating_objects_top(floating_objects_list_top, all_sprites_list) move_floating_objects_top(floating_objects_list_top) move_floating_objects_bottom(floating_objects_list_bottom) ' Call the update() method on all the sprites' all_sprites_list.update() all_sprites_list.draw(screen) pygame.display.flip()
def initBoard(self): '''initiates board''' self.q = Queue() self.qB = Queue() # setting timer for players self.timer = QBasicTimer() self.timer.start(20, self) # setting timer for birds self.timerBirds = QBasicTimer() self.timerBirds.start(BIRD_SPEED, self) self.timerBirdsID = self.timerBirds.timerId() # setting timer for birds bullets self.timerBird_bullet = QBasicTimer() self.timerBird_bullet.start(BIRD_BULLET_SPEED, self) self.timerBird_bulletID = self.timerBird_bullet.timerId() self.timerCounter = 0 self.timerCounterBullets = 0 # counter for levels self.lvl = 1 self.nextLvl = False # setting label for showing number of levels self.lvlLabel = QLabel(self) pic = QPixmap('level.png') pic = pic.scaled(125, 65) self.lvlLabel.setPixmap(pic) self.lvlLabel.move(450, 20) self.lvlNumberLabel = QLabel(self) self.changeLvlNumber() self.lvlNumberLabel.move(600, 22) self.lvlNumberLabel2 = QLabel(self) pic = QPixmap('blue-watercolor-number-1B.png') pic = pic.scaled(25, 60) self.lvlNumberLabel2.setPixmap(pic) self.lvlNumberLabel2.move(630, 22) self.lvlNumberLabel2.hide() # setting label for showing who's winner self.winnerLabel = QLabel(self) pic = QPixmap('winner.png') pic = pic.scaled(700, 60) self.winnerLabel.setPixmap(pic) self.winnerLabel.move(190, 530) self.winnerLabel.hide() self.winnerNumLabel = QLabel(self) pic = QPixmap('blue-watercolor-number-0B.png') pic = pic.scaled(25, 60) self.winnerNumLabel.setPixmap(pic) self.winnerNumLabel.move(925, 530) self.winnerNumLabel.hide() self.noWinnerLabel = QLabel(self) pic = QPixmap('nowinner.png') pic = pic.scaled(500, 60) self.noWinnerLabel.setPixmap(pic) self.noWinnerLabel.move(340, 530) self.noWinnerLabel.hide() # setting curent value for birds speed and bullets speed self.curBirdSpeed = 30 self.curBirdBulletSpeed = 10 self.bigBird = Bird(self, -55, 80, 70, 70) self.bigBirdUp = True self.bigBirdHit = False #self.bigBirdStarted = False self.bigBirdFlying = False self.bigBird.setGeometry(10, 100, 70, 70) self.bigBird.hide() # initializing 3x10 birds, their directions, counter for number of hitted ones, bullets they have and number of ones they fired self.birds = [Bird(self, 0, 0, 50, 50) for i in range(NUM_BIRDS)] self.BirdsGoingLeft = True self.BirdsGoingRight = False self.wingsUp = [True for i in range(NUM_BIRDS)] self.bird_hit = [False for i in range(NUM_BIRDS)] self.dead_count = 0 self.bird_bullets = [ Bullet(self, 0, 0, 'Poop-512.png') for i in range(NUM_BIRDS) ] self.bird_bullets_fired = [False for i in range(NUM_BIRDS)] self.ColumnDown = [False for i in range(10)] self.leftBirdsWall = 9 self.rightBirdsWall = 0 self.rowDown = 2 self.rowGone = False self.setUpGame() # initializing 2 players, their bullets, flags for firing bullets, hitting birds, touching another label, being dead and checking which key is pressed self.player1 = Player(self, 1100, 750, 1110, 'planeW.gif') self.player2 = Player(self, 50, 750, 0, 'planeG.gif') self.bullet1 = Bullet(self, 1120, 740, 'bullet.png') self.bullet1.hide() self.bullet2 = Bullet(self, 70, 740, 'bullet.png') self.bullet2.hide() self.isFired1 = False self.isFired2 = False self.labelsTouching1 = False self.labelsTouching2 = False self.hitBird1 = False self.hitBird2 = False self.noWinner = False self.isDead = 0 self.isDead1 = False self.isDead2 = False self.gameOver = False self.keys_pressed = set() self.startProcess() self.setFocusPolicy(Qt.StrongFocus)