示例#1
0
	def __init__(self, center, gs=None):
		pygame.sprite.Sprite.__init__(self)

		self.gs = gs
		self.image = pygame.image.load("imgs/tank1.png")
		self.orig_image = pygame.image.load("imgs/tank1.png")
		# tank is a tad smaller than gun bc collision detecting
		self.image = pygame.transform.scale(self.image, (40, 40))
		self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
		self.rect = self.image.get_rect()
		self.rect.center = center
		self.fire_x = 0
		self.fire_y = 0
		self.fire_timer = 0
		self.tofire = False
		self.mx = 0
		self.my = 0
		self.life = True

		#attach gun, has to be a different part in order
		# to move around seemlessly (as opposed to a weird
		# rotating square)
		self.gun = Gun(self.rect.center, self.gs)
		self.hold = False
		self.key = 0
示例#2
0
 def test_readIDFileReturnsFalseFromPoorlyFormattedFile(self):
     file = open('gunid', 'r+')
     file.truncate()
     file.write("not a good file")
     file.close()
     gun = Gun()
     self.assertFalse(gun.readIDFile())
示例#3
0
    def __init__(self,
                 motor_range,
                 steppers,
                 friendly_mode=True,
                 trigger_pin=None,
                 micro_pins=None,
                 micro_pos=None,
                 show_video=False):
        global has_motors

        self.friendly_mode = friendly_mode
        self.micro_pins = micro_pins
        self.micro_pos = micro_pos
        self.motor_range = motor_range

        self.stepper_x = steppers[0]
        self.stepper_y = steppers[1]

        self.override_motion = False

        atexit.register(self.__turn_off_motors)

        if has_motors:
            self.gun = Gun(trigger_pin, self.stepper_x, self.stepper_y,
                           friendly_mode)
        else:
            self.gun = dummy.Gun(self.stepper_x, self.stepper_y, friendly_mode)
        self.motion_sensor = MotionSensor(self.__on_motion,
                                          self.__on_no_motion,
                                          show_video=show_video)
示例#4
0
    def __init__( self, robotName, skinImgs, screen, initPos, initDir ):
        """
            'robotName' - String com um máximo de 15 caracteres que indica o nome do robot.            
            'skinImgs' - Lista com as imagens para o corpo, arma e radar do robot. [ bodyImg, gunImg, radarImg ]
            screen - objecto do tipo 'pygame.display' onde o robot irá ficar.
            'initPos' - Tupla com o x e y iniciais
            'initDir' - Direcção inicial do robot
        """
        self._name = robotName
        # Imagem base que não vai ser alterada
        self._baseBodyImg = skinImgs[ 0 ]
        self.screen = screen
        
        # Imagem que vai sofrer as alterações para depois se dezenhada na Surface.
        self._bodyImg = None
        # Vai conter sempre o rectangulo actual da imagem
        self._bodyRect = self._baseBodyImg.get_rect()

        Gun.__init__( self, skinImgs[ 1 ] )
        Radar.__init__( self, skinImgs[ 2 ] )
        
        # Inicializa a posição do robot com a sua posição inicial
        x, y = initPos
        self.update( x, y, initDir, initDir, initDir )
        
        self.angle = 0
示例#5
0
文件: enemy.py 项目: bdevorem/tanks
	def __init__(self, gs=None, center=None, angle=None, target=None, interval = None):
		"""
		Enemy class: sort of a hybrid between the user
		tank and the pellets. It is a tank, and the gun
		follows the user at all time. But it changes directions
		when it hits another enemy or a wall
		"""
		pygame.sprite.Sprite.__init__(self)
		self.gs = gs

		self.angle = angle
		self.target = target		
		self.center = center

		self.image = pygame.image.load("imgs/tank3.png")
		self.orig_image = pygame.image.load("imgs/tank3.png")
		self.image = pygame.transform.scale(self.image, (40, 40))
		self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
		self.rect = self.image.get_rect()
		self.rect.center = self.center
		self.dx = math.cos(self.angle)*2
		self.dy = math.sin(self.angle)*-2
		self.exploded = False
		self.tofire = False
		self.gun = Gun(self.rect.center, self.gs)

		#random interval at which to fire at user
		self.fire_interval = interval
		self.fire_timer = 0
示例#6
0
    def init(self):
        self.bgColor = (11, 102, 35)
        Player.init()
        self.player = Player(self.width / 2, self.height / 2)
        self.playerGroup = pygame.sprite.Group(self.player)

        Gun.init()
        self.guns = pygame.sprite.Group()
        for i in range(3):
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            self.guns.add(Gun(x, y))

        objectGenerator.init()
        self.objectSet = pygame.sprite.Group()
        self.objectCoor = [(0,0)]
        self.test = objectGenerator(0, 0)
        while len(self.objectCoor) < 8:
            x = random.randint(0, self.width)
            y = random.randint(0, self.height)
            if not self.isTouching(x, y):
                self.objectCoor.append((x,y))
                self.objectSet.add(objectGenerator(x, y))

        self.bullets = pygame.sprite.Group()

        self.roads = set()
        number = random.randint(1, 2)
        for i in range(number):
            self.roads.add(self.selectRoads())
示例#7
0
    def test_attack_by_gun(self):
        # setup
        knight = self.create_knight(Gun())  # parameterized creation method

        # exercise
        pain = knight.attack_power()

        # verify
        self.assertEqual(pain, Gun().attack_power())
示例#8
0
 def test_validateReturnsTrueWhenInputIsProperlyFormatted(self):
     file = open('gunid', 'r+')
     file.truncate()
     file.write(
         "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n"
     )
     file.close()
     gun = Gun()
     self.assertTrue(gun.readIDFile())
示例#9
0
 def test_validateReturnsFalseWhenPlayerIsNotRegistered(self):
     file = open('gunid', 'r+')
     file.truncate()
     file.write(
         "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=None\n"
     )
     file.close()
     gun = Gun()
     self.assertFalse(gun.readIDFile())
示例#10
0
def fve_gun(exp, nom, plt):
    from fit import Opt
    from gun import magic
    from gun import Gun
    
    fig = plt.figure('fve_gun',figsize=fig_y_size(9))    
    p2f = magic.newton2dyne*magic.area/1e11
    opt = Opt(
        nom.eos,
        {'gun':nom.gun,'stick':nom.stick},
        {'gun':exp.vt,'stick':exp.stick_data})
    cs,costs = opt.fit(max_iter=5)
    print('costs={0}'.format(costs))
    opt_gun = Gun(opt.eos)
    nom.gun.eos = nom.eos # Restore nominal eos after optimization
    t2vs = [Gun(eos).fit_t2v() for eos in [opt.eos.new_c(c) for c in cs]]
    e = [exp.v - t2v(exp.t) for t2v in t2vs[1:]]

    data = {'nominal':(
        (exp.x, nom.eos(exp.x)*p2f, 'f'),
        (exp.x, nom.gun.x_dot(exp.x)/magic.cm2km, 'v'))}
    data['experimental']=(
        (exp.x, exp.eos(exp.x)*p2f, 'f'),
        (exp.x, exp.gun.x_dot(exp.x)/magic.cm2km, 'v'))
    data['fit']=(
        (exp.x, opt.eos(exp.x)*p2f, 'f'),
        (exp.x, opt_gun.x_dot(exp.x)/magic.cm2km, 'v'))
    
    cm = r'$x/(\rm{cm})$'
    mu_sec = r'$t/(\mu\rm{sec})$'
    f_key = r'$f/({\rm dyn}\cdot 10^{11})$'
    v_key = r'$v/(\rm{km/s})$'
    e_key = r'$\epsilon_k/(\rm{m/s})$'
    ax_d = {
        'f':{'ax':fig.add_subplot(3,1,1), 'l_x':cm,
             'l_y':f_key, 'loc':'upper right'},
        'v':{'ax':fig.add_subplot(3,1,2), 'l_x':cm,
            'l_y':v_key, 'loc':'lower right'},
        'e':{'ax':fig.add_subplot(3,1,3), 'l_x':mu_sec,
             'l_y':e_key, 'loc':'upper right'}
    }
    for mod,xyn in data.items():
        for x,y,name in xyn:
            if mod == 'experimental':
                ax_d[name]['ax'].plot(x,y,'r-.',label=r'$\rm %s$'%mod)
            else:
                ax_d[name]['ax'].plot(x,y,label=r'$\rm %s$'%mod)
    for i in range(len(e)):
        ax_d['e']['ax'].plot(exp.t*1e6,e[i]/100,label=r'$\epsilon_%d$'%(i+1))
    for name,d in ax_d.items():
        d['ax'].legend(loc=ax_d[name]['loc'])
        d['ax'].set_xlabel(d['l_x'])
        d['ax'].set_ylabel(r'$%s$'%name)
        if 'l_y' in d:
            d['ax'].set_ylabel(d['l_y'])
    
    return fig
示例#11
0
 def test_validateReturnsFalseWhenIdIs0(self):
     file = open('gunid', 'r+')
     file.truncate()
     file.write(
         "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=0\nusername=Benjamin\n"
     )
     file.close()
     gun = Gun()
     self.assertFalse(gun.readIDFile())
示例#12
0
 def test_checkGameReturnsFalseWhenThereIsNoActiveGame(self):
     file = open('gunid', 'r+')
     file.truncate()
     file.write(
         "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n"
     )
     file.close()
     gun = Gun()
     gun.readIDFile()
     self.assertFalse(gun.checkGame())
示例#13
0
    def __init__(self, name="Queen of the Skies"):
        self.name = name
        self.missions_completed = 0
        self.status = BOMBER_SAFE

        self.crew = {
            BOMBARDIER: Crew(BOMBARDIER),
            NAVIGATOR: Crew(NAVIGATOR),
            PILOT: Crew(PILOT),
            COPILOT: Crew(COPILOT),
            ENGINEER: Crew(ENGINEER),
            RADIO_OPERATOR: Crew(RADIO_OPERATOR),
            BALL_GUNNER: Crew(BALL_GUNNER),
            PORT_WAIST_GUNNER: Crew(PORT_WAIST_GUNNER),
            STBD_WAIST_GUNNER: Crew(STBD_WAIST_GUNNER),
            TAIL_GUNNER: Crew(TAIL_GUNNER)
        }

        self.guns = {
            NOSE: Gun(NOSE, self.crew[BOMBARDIER], 15),
            PORT_CHEEK: Gun(PORT_CHEEK, self.crew[NAVIGATOR], 10),
            STBD_CHEEK: Gun(STBD_CHEEK, self.crew[NAVIGATOR], 10),
            TOP_TURRET: Gun(TOP_TURRET, self.crew[ENGINEER], 16),
            RADIO: Gun(RADIO, self.crew[RADIO_OPERATOR], 10),
            BALL_TURRET: Gun(BALL_TURRET, self.crew[BALL_GUNNER], 20),
            PORT_WAIST: Gun(PORT_WAIST, self.crew[PORT_WAIST_GUNNER], 20),
            STBD_WAIST: Gun(STBD_WAIST, self.crew[STBD_WAIST_GUNNER], 20),
            TAIL_TURRET: Gun(TAIL_TURRET, self.crew[TAIL_GUNNER], 23),
        }

        self.damage = []
示例#14
0
 def __init__(self):
     """ Constructor for the Trigger class.
     Postconditions: The gunid and user name will be assigned to 
     a "gun" (to hardware).
 """
     self.TRIGGER = 19
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(self.TRIGGER, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
     self.gun = Gun()
     self.gun.readIDFile()
     self.shotID = "Shot" + str(self.gun.id).zfill(2)
示例#15
0
 def test_readIDFileAssignsCorrectValuesFromProperlyFormattedFile(self):
     file = open('gunid', 'r+')
     file.truncate()
     file.write(
         "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n"
     )
     file.close()
     gun = Gun()
     gun.readIDFile()
     self.assertEqual(gun.id, 3)
     self.assertEqual(gun.username, "Benjamin")
示例#16
0
class Trigger:
    """ The Trigger class handles all trigger events for the gun hardware.
      Establishing which gun has which id and username, "shooting" an 
      ir shot, and adding or deleting a trigger for event detection 
      (for a gun).
  """
    def __init__(self):
        """ Constructor for the Trigger class.
        Postconditions: The gunid and user name will be assigned to 
        a "gun" (to hardware).
    """
        self.TRIGGER = 19
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.TRIGGER, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        self.gun = Gun()
        self.gun.readIDFile()
        self.shotID = "Shot" + str(self.gun.id).zfill(2)

    def __del__(self):
        GPIO.cleanup()


#    GPIO.remove_event_detect(self.TRIGGER)

    def shoot(self, pin):
        """ shoot
        Preconditions: The constructor has been called and a game has
        been started.
        Parameter pin is a GPIO input pin on the raspberry pi zero 
        board.
        Postconditions: A shot will be registered to the database
        via the fireShot definition in the gun class.
    """
        if GPIO.input(pin) == GPIO.HIGH:
            print(str(datetime.datetime.now()), "Shot")
            call(["irsend", "SEND_ONCE", "laserpi", self.shotID])
            self.gun.fireShot()
            return True

    def addTrigger(self):
        """ addTrigger
        Preconditions: The constructor has been called.
        Postconditions: Event detection for a trigger will be 
        established.
    """
        GPIO.add_event_detect(self.TRIGGER,
                              GPIO.RISING,
                              callback=self.shoot,
                              bouncetime=50)
示例#17
0
def game():
    pygame.init()       #Initialize Pygame
    pygame.mixer.pre_init(44100, -16, 2, 2048)  # Reduce Lagging for the Music
    pygame.mixer.init()     #Initialize Mixer for Background Music
    pygame.mixer.music.load('bgm.wav')      #Load the BGM File
    pygame.mixer.music.play(-1)     #Play the BGM Infinitely
    screen=pygame.display.set_mode((500,650))       #Set the Pygame Window
    pygame.display.set_caption("STARHEAD EXTERMINATOR")     #Set the Window Caption

    #Call All the Classes
    txt = "DONT SHOOT THE GREEN ONE"
    button = Button(screen,txt)
    stats = Stats()
    gun = Gun(screen)
    enemy = Enemy(screen,stats)
    host = Hostage(screen,stats)
    score = Score(screen, stats)
    enemies = Group()
    hostage = Group()
    #Start the Game Loop
    while True:
        gf.firstscreen(screen,button,stats,gun,enemies,hostage,score)      #First Display of the Game 
        if stats.game_active:       #Start when the Player Click the Button
            gf.gametrue(screen,stats,gun,enemies,hostage,score)     #Update and Behaviour of Objects in the Game
        gf.update_screen(screen,gun,enemies,hostage,button,stats)       #Update the Screen and Flip
示例#18
0
 def __init__(self):
     global registry
     self.registry = registry
     self.timer = int(time.time())
     self.notices = set()
     self.gun = Gun(self.registry)
     self.hitDucks = [False for i in range(10)]
     self.hitDuckIndex = 0
示例#19
0
    def __init__(self):
        super().__init__(title="Game",
                         width=15 * 64,
                         height=9 * 64,
                         fullscreen=False)

        # Load background image
        self.background_sprite = arcade.Sprite("assets/background.png",
                                               center_x=self.width / 2,
                                               center_y=self.height / 2)
        self.static_sprites = arcade.SpriteList(is_static=True)
        self.static_sprites.append(self.background_sprite)

        # Create game objects
        self.test_gun = Gun(300, 200)
        self.bullets = []
        self.player = Player(50, 50)
示例#20
0
    def test_loseGameReturnsFalseWhenThereIsNoOpponentInGame(self):
        file = open('gunid', 'r+')
        file.truncate()
        file.write(
            "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n"
        )
        file.close()
        gun = Gun()
        gun.readIDFile()

        mydb = connect.connect()
        cursor = mydb.cursor()
        sql = "INSERT INTO Games (current_state, winner, game_date) VALUES (2, 0, (NOW() - INTERVAL 4 HOUR + INTERVAL 11 MINUTE - INTERVAL 22 SECOND))"
        cursor.execute(sql)
        mydb.commit()

        gun.joinGame()

        self.assertFalse(gun.loseGame())

        sql = "UPDATE Games SET current_state=0 WHERE current_state=2"
        cursor.execute(sql)
        mydb.commit()

        mydb.close()
示例#21
0
 def __init__(self, i, x, y, s, t=0):
     self.identity = i
     self.x = x
     self.y = y
     self.size = s
     self.t_num = t
     self.box = pygame.Rect((self.x, self.y), (self.size, self.size))
     self.level = 1
     self.__c_mod = 1.0  # gets smaller
     self.coolness = 0  # 0 means ready to shoot
     self.__r_mod = 1.0  # gets bigger
     self.__p_mod = 1.0  # gets bigger
     self.__s_mod = 1.0  # gets bigger
     self.gun = Gun((self.x, self.y), s, t, tower_colors[self.t_num],
                    self.level)
     self.upgrade_cost = 10
     self.follow_mouse = False
     self.show_r = False
     self.font = pygame.font.SysFont('Century Gothic', 12)
示例#22
0
    def __init__(self):
        """Initialize the game and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Hit the Target")
        # self.screen_rect = self.screen.get_rect()

        # Create an instance to store game statistics.
        self.stats = GameStats(self)

        self.target = Target(self)
        self.gun = Gun(self)
        self.bullets = pygame.sprite.Group()

        # Make the Play button.
        self.play_button = Button(self, "Play")
示例#23
0
    def __init__(self, setting: settings):
        self.velocity = pygame.Vector2(0, 0)
        self.sprite_sheet = spriteSheet(setting.ship_filename, 5, 4)
        self.position = Vector2(
            setting.screen_width / 2 - self.sprite_sheet.cell_width / 2,
            setting.screen_height - self.sprite_sheet.cell_height)
        self.rect = pygame.Rect(self.position.x, self.position.y,
                                self.sprite_sheet.cell_width,
                                self.sprite_sheet.cell_height)

        self.ship_speed = setting.ship_speed
        self.life = setting.ship_life
        self.setting = setting
        self.gun = Gun(setting)
        self.moving_right = False
        self.moving_left = False
        self.score = score(0, Vector2())
        pygame.font.init()
        self.font = pygame.font.SysFont('Comic Sans', 24, True)
示例#24
0
文件: game.py 项目: 0Knowledge/pylaga
 def start(self):
     self.clear_vars()
     self.player = Player(self.player_list, self.token_list,
                          Gun(self.list_allie_shots, Bullet))
     self.player_list.add(self.player)
     self.player.set_pos(globalvars.x, globalvars.y)
     self.health.link_sprite(self.player)
     self.inputmanager = self.parent.inputmanager
     self.register_inputs()
     self.loop()
示例#25
0
    def __init__(self, center, gs=None):
        pygame.sprite.Sprite.__init__(self)

        self.gs = gs
        self.image = pygame.image.load("imgs/tank2.png")
        self.orig_image = pygame.image.load("imgs/tank2.png")
        # tank is a tad smaller than gun bc collision detecting
        self.image = pygame.transform.scale(self.image, (40, 40))
        self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
        self.rect = self.image.get_rect()
        self.rect.center = center
        self.fire_x = 0
        self.fire_y = 0
        self.fire_timer = 0
        self.tofire = False
        self.mx = 0
        self.my = 0
        self.gun = Gun(self.rect.center, self.gs)
        self.hold = False
        self.key = 0
示例#26
0
    def __init__(self, setting: settings, shoot_sound):
        self.shoot_sound = shoot_sound
        self.fleet = list()
        self.move_speed = setting.alien_speed
        self.creep_speed = setting.creep_speed
        self.gun = Gun(setting)
        self.setting = setting
        self.saucer = Saucer(setting, Vector2(-64, 64 * 2))

        for i in range(10):
            self.fleet.append(Squid(setting, pygame.Vector2(70 * i, 70)))
        for i in range(10):
            self.fleet.append(Squid(setting, pygame.Vector2(70 * i, 70 * 2)))
        for i in range(10):
            self.fleet.append(Jelly(setting, pygame.Vector2(70 * i, 70 * 3)))
        for i in range(10):
            self.fleet.append(Jelly(setting, pygame.Vector2(70 * i, 70 * 4)))
        for i in range(10):
            self.fleet.append(Crab(setting, pygame.Vector2(70 * i, 70 * 5)))
        for i in range(10):
            self.fleet.append(Crab(setting, pygame.Vector2(70 * i, 70 * 6)))
示例#27
0
    def test_joinGameCorrectlyAddsUserIntoGame(self):
        file = open('gunid', 'r+')
        file.truncate()
        file.write(
            "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n"
        )
        file.close()
        gun = Gun()
        gun.readIDFile()

        mydb = connect.connect()
        cursor = mydb.cursor()
        sql = "INSERT INTO Games (current_state, winner, game_date) VALUES (1, 0, (NOW() - INTERVAL 4 HOUR + INTERVAL 11 MINUTE - INTERVAL 22 SECOND))"
        cursor.execute(sql)
        mydb.commit()

        gun.joinGame()

        sql = "SELECT * FROM (Games INNER JOIN Game_Users ON Games.id = Game_Users.game_id) WHERE Games.current_state = 1"
        cursor.execute(sql)
        myresult = cursor.fetchall()
        self.assertEqual(len(myresult), 1)  #only one row added to database
        self.assertEqual(myresult[0][5], 3)  #gunid is 3
        self.assertEqual(myresult[0][6], "Benjamin")  #username is Benjamin

        sql = "UPDATE Games SET current_state=0 WHERE current_state=1"
        cursor.execute(sql)
        mydb.commit()

        mydb.close()
示例#28
0
    def test_fireShotCorrectlyIncrementsGunShotsFiredInDatabase(self):
        file = open('gunid', 'r+')
        file.truncate()
        file.write(
            "# User Identification File.\n# Change gunid and username.\n# Rename file to gunid.\ngunid=3\nusername=Benjamin\n"
        )
        file.close()
        gun = Gun()
        gun.readIDFile()

        mydb = connect.connect()
        cursor = mydb.cursor()
        sql = ("SELECT * FROM Guns " "WHERE gun='{}'").format(gun.id)
        cursor.execute(sql)
        myresult = cursor.fetchall()
        oldShots = myresult[0][3]

        gun.fireShot()

        sql = ("SELECT * FROM Guns " "WHERE gun='{}'").format(gun.id)
        cursor.execute(sql)
        myresult = cursor.fetchall()
        newShots = myresult[0][3]

        mydb.close()
        self.assertEqual((oldShots + 1), newShots)
示例#29
0
def main():
    bullets = [Bullet(), Bullet(), Bullet(), Bullet(), Bullet()]
    box = Box(bullets, 5)
    gun = Gun(box)
    per = Person(gun)

    #开枪
    per.fire()
    per.fire()
    per.fire()
    per.fire()
    per.fire()
    per.changeBox(5)
    per.fire()
示例#30
0
 def __init__(self, surface):
     self.surface = surface
     self.gun = Gun(surface)
     self.ducks = [Duck(surface), Duck(surface)]
     self.round = 1
     self.phase = 'start'
     self.score = 0
     self.timer = int(time.time())
     self.roundTime = 10 # Seconds in a round
     self.controlImgs = pygame.image.load(os.path.join('media', 'screenobjects.png'))
     self.hitDucks = [False for i in range(10)]
     self.hitDuckIndex = 0
     self.nextRoundSound = os.path.join('media', 'next-round.mp3')
     self.flyawaySound = os.path.join('media', 'flyaway.mp3')
     self.notices = ()
示例#31
0
	def __init__(self, center, gs=None):
		pygame.sprite.Sprite.__init__(self)

		self.gs = gs
		self.image = pygame.image.load("imgs/tank2.png")
		self.orig_image = pygame.image.load("imgs/tank2.png")
		# tank is a tad smaller than gun bc collision detecting
		self.image = pygame.transform.scale(self.image, (40, 40))
		self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
		self.rect = self.image.get_rect()
		self.rect.center = center
		self.fire_x = 0
		self.fire_y = 0
		self.fire_timer = 0
		self.tofire = False
		self.mx=0
		self.my=0	
		self.gun = Gun(self.rect.center, self.gs)
		self.hold = False
		self.key = 0
示例#32
0
    def __init__(self, texture, speed):
        super().__init__()
        self.sr = SpriteRenderer(self, texture)
        self.rb = Rigidbody(self)

        self.event_listener = EventListener(self, self.explode)
        self.event = GameEvent(self)

        self.add_components([self.rb, self.sr, self.event_listener])

        self.gun = Gun()
        self.gun.transform.set_parent(self.transform)
        self.gun.transform.local_position = pygame.math.Vector2(0, -32)
        self.instantiate(self.gun)

        self.speed = speed

        self.transform.size = pygame.math.Vector2(3,3)
        self.cooldown = 0.5
        self.cooldown_timer = 0

        self.vel = pygame.math.Vector2(0,0)
        self.acc = 100
        self.dec = 0.8
示例#33
0
class Driver(object):
    def __init__(self, surface):
        self.surface = surface
        self.gun = Gun(surface)
        self.ducks = [Duck(surface), Duck(surface)]
        self.round = 1
        self.phase = 'start'
        self.score = 0
        self.timer = int(time.time())
        self.roundTime = 10 # Seconds in a round
        self.controlImgs = pygame.image.load(os.path.join('media', 'screenobjects.png'))
        self.hitDucks = [False for i in range(10)]
        self.hitDuckIndex = 0
        self.nextRoundSound = os.path.join('media', 'next-round.mp3')
        self.flyawaySound = os.path.join('media', 'flyaway.mp3')
        self.notices = ()

    def handleEvent(self, event):
        # If we are in the shooting phase, pass event off to the gun
        if event.type == pygame.MOUSEMOTION:
            self.gun.moveCrossHairs(event.pos)
        elif event.type == pygame.MOUSEBUTTONDOWN:
            gunFired = self.gun.shoot()
            for duck in self.ducks:
                if gunFired:
                    if duck.isShot(event.pos):
                        self.score += 10
                        self.hitDucks[self.hitDuckIndex] = True
                        self.hitDuckIndex += 1
                else:
                    duck.flyOff = True

    def update(self):
        allDone = False

        # Update game based on phase
        if self.phase == 'start':
            self.startRound()
        elif self.phase == 'shoot':
            # Update all ducks
            for duck in self.ducks:
                duck.update(self.round)
            self.manageRound()
        elif self.phase == 'end':
            self.endRound()

    def render(self):
        # If there is a notice, display and return
        if len(self.notices) > 0:
            font = pygame.font.Font(FONT, 20)
            text = font.render(str(self.notices[0]), True, (255, 255, 255));
            x, y = NOTICE_POSITION
            x = x + (NOTICE_WIDTH - text.get_width()) / 2
            y = NOTICE_LINE_1_HEIGHT
            self.surface.blit(self.controlImgs, NOTICE_POSITION, NOTICE_RECT)
            self.surface.blit(text, (x, y));
            if len(self.notices) > 1:
                text = font.render(str(self.notices[1]), True, (255, 255, 255));
                x, y = NOTICE_POSITION
                x = x + (NOTICE_WIDTH - text.get_width()) / 2
                y = NOTICE_LINE_2_HEIGHT
                self.surface.blit(text, (x, y));

            return

        # Show the ducks
        for duck in self.ducks:
            duck.render()

        # Show round number
        font = pygame.font.Font(FONT, 20)
        text = font.render(("R= %d" % self.round), True, (154, 233, 0), (0, 0, 0));
        self.surface.blit(text, ROUND_POSITION);

        # Show the hit counter
        self.surface.blit(self.controlImgs, HIT_POSITION, HIT_RECT)
        startingX, startingY = HIT_DUCK_POSITION
        for i in range(10):
            x = startingX + (19 * i)
            y = startingY
            if self.hitDucks[i]:
                self.surface.blit(self.controlImgs, (x, y), HIT_DUCK_RED_RECT)
            else:
                self.surface.blit(self.controlImgs, (x, y), HIT_DUCK_WHITE_RECT)

        # Show the score
        self.surface.blit(self.controlImgs, SCORE_POSITION, SCORE_RECT)
        font = pygame.font.Font(FONT, 20)
        text = font.render(str(self.score), True, (255, 255, 255));
        x, y = FONT_STARTING_POSITION
        x -= text.get_width();
        self.surface.blit(text, (x,y));

        # Show the cross hairs
        self.gun.render()

    def manageRound(self):
        timer = int(time.time())

        # Check round end
        timesUp = (timer - self.timer) > self.roundTime
        if not (timesUp or (self.ducks[0].isFinished and self.ducks[1].isFinished)):
            return

        # Let any remaining ducks fly off
        for duck in self.ducks:
            if not duck.isFinished:
                duck.flyOff = True
                return

        # Check for fly offs and increment the index
        for duck in self.ducks:
            if not duck.isDead:
                self.hitDuckIndex += 1

        # Start new around if duck index is at the end
        if self.hitDuckIndex >= 9:
            pygame.mixer.music.load(self.nextRoundSound)
            pygame.mixer.music.play()
            self.phase = 'end'
            return

        # Populate screen with new ducks
        self.ducks = [Duck(self.surface), Duck(self.surface)]
        self.timer = int(time.time())
        self.gun.reloadIt()

    def startRound(self):
        timer = int(time.time())
        self.notices = ("ROUND", self.round)
        if (timer - self.timer) > 2:
            self.phase = 'shoot'
            self.notices = ()

    def endRound(self):
        # Pause game for new round music to play
        while pygame.mixer.music.get_busy():
            return

        # Count missed ducks - more than 4 and you're done
        missedCount = 0
        for i in self.hitDucks:
            if i == False:
                missedCount += 1
        if missedCount > 4:
            self.notices = ("GAME OVER", "")
            return

        # Prep for new round
        self.round += 1
        self.hitDucks = [False for i in range(10)]
        self.hitDuckIndex = 0
        self.phase = 'start'
        self.timer = int(time.time())
示例#34
0
文件: game.py 项目: belambic/invaders
	def start(self):
		score = 0
		lives = 3
		level = 1
		framerate = 25
		shields = 4
		alien_tick = 15
		gameover = False

		display = Display()
		gun = Gun(maxx=display.width, maxy=display.height)
		aliens = self.make_aliens(42, display.width, alien_tick)

		while True:
			self.status(display, lives, score, level)

			for alien in aliens:
				alien.move()
				display.putstring(alien.last[0], alien.last[1], "     ")
				display.putstring(alien.current[0], alien.current[1], alien.alien)

			display.putstring(gun.guny, gun.gunx, gun.gun)
			
			for index, alien in enumerate(aliens):
				hit = gun.hit(alien.current[0], alien.current[1])
				if hit:
					display.putstring(alien.current[0], alien.current[1], " BOOM ")
					score += 1
					del(aliens[index])
					break
				
				if alien.current[0] == display.height - 2:
					if lives > 0:
						lives -= 1
						aliens = self.make_aliens(42, display.width, alien_tick)
						display.erase()
					else:
						gameover = True
						display.putstring(10, 30, "Game Over!!!")
					break

			if aliens == []:
				display.putstring(10, 30, "YOU WIN!!!!")
				
			if gun.firing:
				gun.fire()
				display.putstring(gun.bullety, gun.bulletx, gun.bullet)
		
			display.refresh()
			time.sleep(1.0 / framerate)
			
			if gameover:
				display.close()
				break

			if gun.firing:
				display.putstring(gun.bullety, gun.bulletx, " ")

			if hit:
				display.putstring(alien.current[0], alien.current[1], "      ")
				
			if aliens == []:
				display.putstring(10, 30, "            ")
				level += 1
				alien_tick -= 1
				aliens = self.make_aliens(42, display.width, alien_tick)

			display.refresh()
	
			i = display.getch()
			if i == ord("a"):
				gun.left()
			elif i == ord("d"):
				gun.right()
			elif i == ord("s"):
				gun.start()
			elif i == ord("q"):
				display.close()
				break
示例#35
0
class tank(pygame.sprite.Sprite):
	def __init__(self, center, gs=None):
		pygame.sprite.Sprite.__init__(self)

		self.gs = gs
		self.image = pygame.image.load("imgs/tank1.png")
		self.orig_image = pygame.image.load("imgs/tank1.png")
		# tank is a tad smaller than gun bc collision detecting
		self.image = pygame.transform.scale(self.image, (40, 40))
		self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
		self.rect = self.image.get_rect()
		self.rect.center = center
		self.fire_x = 0
		self.fire_y = 0
		self.fire_timer = 0
		self.tofire = False
		self.mx = 0
		self.my = 0
		self.life = True

		#attach gun, has to be a different part in order
		# to move around seemlessly (as opposed to a weird
		# rotating square)
		self.gun = Gun(self.rect.center, self.gs)
		self.hold = False
		self.key = 0

	def tick(self):
		#allow for coasting w a variable set in gamespace
		if self.hold and self.key is not 0:
			self.move(self.key)

		# get movement
		dx = self.mx - self.rect.centerx
		dy = self.rect.centery - self.my
		if self.fire_timer != 0:
			self.fire_timer -= 1
		if self.tofire == True and self.fire_timer == 0:
			self.fire_timer = 60
			# can still come from center of tank since the 
			# gun will be pointing in the same direction
			# ^^ jk because of collision detection

			fire_x = self.mx
			fire_y = self.my
			# move bullets to start outside of rect, so they 
			# don't get stuck bc of collision detection
			angle = math.atan2(self.rect.centery-fire_y, fire_x-self.rect.centerx)
			pellet_center = (self.rect.centerx+math.cos(angle)*36,self.rect.centery-math.sin(angle)*36)
			pellet = Pellet(self, angle, pellet_center, self.gs)
			self.gs.pellets.append(pellet)
		else:
			# if we are moving, rotate gun
			# this class is completely referenced through
			# the tank class since it is not a real sprite,
			# jsut a sub sprite
			if dx != 0:
				self.gun.rotate(dx, dy)

	def move(self, keycode):
		"""
		Called when keydown is detected in main
		Moves objects according to key
		"""
		#self.gun.move(keycode)

		if keycode == 273 or keycode == 119:
			# trial
			if self.checkBlocks((0, -3)) is False:
				self.rect = self.rect.move(0, -3)
				self.gun.move((0,-3))
		elif keycode == 274 or keycode == 115:
			if self.checkBlocks((0, 3)) is False:
				self.rect = self.rect.move(0, 3)
				self.gun.move((0, 3))
		elif keycode == 275 or keycode == 100:
			if self.checkBlocks((3, 0)) is False:
				self.rect = self.rect.move(3, 0)
				self.gun.move((3, 0))
		elif keycode == 276 or keycode == 97:
			if self.checkBlocks((-3, 0)) is False:
				self.rect = self.rect.move(-3, 0)
				self.gun.move((-3, 0))

	def checkBlocks(self, movement):
		"""
		Return True if there is any overlap
		in tank and blocks, no explosion
		"""
		collide = False
		self.temp_rect = self.rect.move(movement[0], 0)
		for block in self.gs.blocks:
			if pygame.Rect.colliderect(self.temp_rect, block.rect):
				collide = True
		
		self.temp_rect = self.rect.move(0, movement[1])
		for block in self.gs.blocks:
			if pygame.Rect.colliderect(self.temp_rect, block.rect):
				collide = True
		
		return collide

	def explode(self):
		"""
		Create a new explosion at the center of the collision
		Explosion is another sprite, gets sent to gs
		"""
		if self.gs.tank1_life:
			self.life = False
			center = deepcopy(self.rect.center)
			self.gs.explosions.append(Explosion(center, self.gs))
示例#36
0
from bulletbox import BulletBox
from gun import Gun
from person import Person

bulletbox = BulletBox(5)
gun = Gun(bulletbox)
per = Person(gun)

per.fire()
per.fire()
per.fire()
示例#37
0
文件: enemy.py 项目: bdevorem/tanks
class Enemy(pygame.sprite.Sprite):
	def __init__(self, gs=None, center=None, angle=None, target=None, interval = None):
		"""
		Enemy class: sort of a hybrid between the user
		tank and the pellets. It is a tank, and the gun
		follows the user at all time. But it changes directions
		when it hits another enemy or a wall
		"""
		pygame.sprite.Sprite.__init__(self)
		self.gs = gs

		self.angle = angle
		self.target = target		
		self.center = center

		self.image = pygame.image.load("imgs/tank3.png")
		self.orig_image = pygame.image.load("imgs/tank3.png")
		self.image = pygame.transform.scale(self.image, (40, 40))
		self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
		self.rect = self.image.get_rect()
		self.rect.center = self.center
		self.dx = math.cos(self.angle)*2
		self.dy = math.sin(self.angle)*-2
		self.exploded = False
		self.tofire = False
		self.gun = Gun(self.rect.center, self.gs)

		#random interval at which to fire at user
		self.fire_interval = interval
		self.fire_timer = 0

	def tick(self):
		if not self.exploded:
			if not self.target.life:
				if self.target == self.gs.tank1:
					self.target = self.gs.teammate
				else:
					self.target = self.gs.tank1
			# first check if direction needs to be changed
			self.checkBounce()
			# then move. will always move, unlike user
			self.move(self.target)

			self.fire_timer += 1
			if self.fire_timer == self.fire_interval:
				#create pellets when the interval reaches
				# the time specified at creation
				self.fire_timer = 0
				fire_x, fire_y = self.target.rect.center
				angle = math.atan2(self.rect.centery-fire_y, 
									fire_x-self.rect.centerx)
				pellet_center = (self.rect.centerx+math.cos(angle)*36,
							self.rect.centery-math.sin(angle)*36)
				pellet = Pellet(self, angle, pellet_center, self.gs)
				self.gs.pellets.append(pellet)


	def move(self, tank1):
		"""
		Move tank at every tick in the same direction, until	
		another object is hit or we die
		"""
		mx, my = tank1.rect.center
		dx = mx - self.rect.centerx
		dy = self.rect.centery - my

		self.rect = self.rect.move(self.dx, self.dy)
		self.gun.move((self.dx, self.dy))

		if dx != 0:
			self.gun.rotate(dx, dy)

	def checkBounce(self):
		"""
		A check for if the motion needs to be changed due
		to a collision (a bounce)
		"""
		orig_center = self.rect.center
		self.temp_rect = self.rect.copy()
		horiz_coll = False
		vert_coll = False

		# loop through blocks and compare rectangles
		self.temp_rect = self.temp_rect.move(self.dx, 0)		
		for block in self.gs.blocks:
			if pygame.Rect.colliderect(self.temp_rect, block.rect):
				horiz_coll = True
		# same for other enemies besides self
		for enemy in self.gs.enemies:
			if enemy is not self:
				if pygame.Rect.colliderect(self.temp_rect, enemy.rect):
					horiz_coll = True
	
		# repeat for vertical collisions
		self.temp_rect = self.rect.copy()
		self.temp_rect = self.rect.move(0, self.dy)
		for block in self.gs.blocks:
			if pygame.Rect.colliderect(self.temp_rect, block.rect):
				vert_coll = True
		for enemy in self.gs.enemies:
			if enemy is not self:
				if pygame.Rect.colliderect(self.temp_rect, enemy.rect):
					vert_coll = True

		# change direction if there is 
		if horiz_coll:
			self.dx = -1 * self.dx
		if vert_coll:
			self.dy = -1 * self.dy
		if (horiz_coll or vert_coll):
			self.move(self.gs.tank1)
			self.move(self.gs.tank1)

	def explode(self):
		"""
		Function to create explosion object when enemy dies
		"""
		if not self.exploded:
			self.gs.enemies.remove(self)
			self.exploded = True
			expl_center = deepcopy(self.rect.center)
			self.gs.explosions.append(Explosion(expl_center, self.gs))
示例#38
0
    def __init__(self,player,screen,width,height,wall_gap,gap_size,seg_padding,bound_color,gravity,x_offset,sidebar_width,bullet_color,is_multiplayer,graphics_path,sound_path):
        self.graphics_path = graphics_path
        self.sound_path = sound_path
        self.player = player
        self.left_key = player.key_cannon_left
        self.right_key = player.key_cannon_right
        self.shoot_key = player.key_cannon_shoot
        self.bullet_color = bullet_color
        self.screen = screen
        self.space = pm.Space()
        self.space.gravity = gravity
        self.space._space.contents.elasticIterations = 10
        self.width = width
        self.height = height
        self.sidebar_width = sidebar_width
        self.wall_gap = wall_gap
        self.gap_size = gap_size
        self.seg_padding = seg_padding
        self.bound_color = bound_color
        self.gravity = gravity
        self.x_offset = x_offset
        self.balls_destroyed = 0
        self.point_total = 0
        self.bullet_limit = 5
        self.space.add_collisionpair_func(1,2,bullet_collision)
        self.space.add_collisionpair_func(1, 3, barrelcannon_load)
        self.swing_limit = 30 # turn this into calculation
        self.child_bonus = 1.5
        self.grandchild_bonus = 2.0
        self.running = True
        self.start_time = time.time()
        self.end_time = 0
        self.end_time_set = False
#        self.spinner_mode = False
        self.spinner_size = 25
        self.spinner_block = None #Buildblock(self,0,self.height/2,60,self.width,(255,0,0))
#        self.barrel_cannon_mode = False
        self.barrel_cannon_block = None
#        self.spinner_count = 0
        self.spinner_limit = 3
        self.spinner_upgrade_level = 0
        self.spinner_max_upgrade_level = 3
        self.barrel_cannon_limit = 1
        self.occupancy_of_blocks = [False, False, False, False, False]
        self.cannon_selected = False
        self.spinner_selected = False
        
        self.is_multiplayer = is_multiplayer
        self.bc_price = 15000
        self.spinner_price = 30000
        self.upgrade_capacity_price = 20000
        self.upgrade_reload_rate_price = 30000
        self.upgrade_spinner_price = 30000
        self.upgrade_bc_price = 25000
        self.upgrade_force_price = 10000
        self.purchases_made = 0
        
        self.virt_x_offset = self.width+self.sidebar_width
        
        display_info = pygame.display.Info()
        self.display_height = display_info.current_h    

        
        # init gun
        self.gun = Gun(self, self.width/2, -10, 15, 30, 1, 1, math.pi/120)
        self.gun.body.angle = math.pi
        self.space.add(self.gun.cannon_shape)
        
        self.balls = []
        self.bullets = []
        self.cannons = []
        self.spinners = []
#===============================================================================
#        swings contains both the connected and disconnected swings and is for drawing them
#        connected swings are the ones that are still connected to the tier1 swing
#        if the connected swing number reaches the maximum and each one has a ball, end game
#        Note: tier1 swings are ALWAYS connected
#===============================================================================
        self.swings = []
        self.connected_swings = []
        
        
        self.buy_index = 0 # current position in buying menu
        #available,upgrade level,(text name,cost),buy action 
        self.max_upgrades = [self.gun.capacity_upgrade_level_max,self.gun.rate_upgrade_level_max,3,3,self.spinner_limit,3]# corresponds to below positions in buy_info
        capacity = [1,self.gun.capacity_upgrade_level_max,[("Bullet Capacity",self.upgrade_capacity_price)],0]
        reload_rate = [1,self.gun.rate_upgrade_level_max,[("Reload Rate",self.upgrade_reload_rate_price)],0]
        impulse = [1,self.gun.impulse_upgrade_level_max,[("Gun Force",self.upgrade_force_price)],0]
        barrel_cannon = [1,3,[("Barrel Cannon",self.bc_price),("Upgrade Barrel Cannon",self.upgrade_bc_price)],0]   
        spinner_available = 0
        if self.is_multiplayer:
            spinner_available = 1
        spinner = [spinner_available,self.spinner_limit,[("Spinner",self.spinner_price)],0]
        spinner_upgrade = [0,3,[("Upgrade Spinners",self.upgrade_spinner_price)],0]
    
        self.buy_info = [capacity,reload_rate,impulse,barrel_cannon,spinner,spinner_upgrade]
        
        vert_wall_height = height-2.0*wall_gap
        horiz_wall_width = (width-(gap_size+2*wall_gap))/2.0 # width of bottom walls
        horiz_top_wall_width = (width-2*wall_gap) # width of top wall
        
        seg1_pos = (wall_gap,height/2.0) # seg1 is left vertical wall
        seg1_start = (0,-vert_wall_height/2.0)
        seg1_end = (0,vert_wall_height/2.0)
    
        seg2_pos = (width-wall_gap,height/2.0) # seg2 is right vertical wall
        seg2_start = (0,-vert_wall_height/2.0) 
        seg2_end = (0,vert_wall_height/2.0)
    
        seg3_pos = (horiz_wall_width/2.0+wall_gap,wall_gap) # seg3 is left horizontal wall
        seg3_start = (-horiz_wall_width/2.0,0)
        seg3_end =  (horiz_wall_width/2.0,-20.0)
    
        seg4_pos = (width-(horiz_wall_width/2.0+wall_gap),wall_gap) # seg4 is right horizontal wall
        seg4_start = (-horiz_wall_width/2.0,-20.0)
        seg4_end = (horiz_wall_width/2.0,0)
    
        seg5_pos = (width/2.0,height-wall_gap)
        seg5_start = (-horiz_top_wall_width/2.0,0)
        seg5_end =  (horiz_top_wall_width/2.0,0)
    
        body1 = pm.Body(pm.inf,pm.inf)
        body1.position = seg1_pos
        seg1 = pm.Segment(body1,seg1_start,seg1_end,seg_padding)
        seg1.elasticity = 1
    
        body2 = pm.Body(pm.inf,pm.inf)
        body2.position = seg2_pos
        seg2 = pm.Segment(body2,seg2_start,seg2_end,seg_padding)
        seg2.elasticity = 1
    
        body3 = pm.Body(pm.inf,pm.inf)
        body3.position = seg3_pos
        seg3 = pm.Segment(body3,seg3_start,seg3_end,seg_padding)
        seg3.elasticity = 1
    
        body4 = pm.Body(pm.inf,pm.inf)
        body4.position = seg4_pos
        seg4 = pm.Segment(body4,seg4_start,seg4_end,seg_padding)
        seg4.elasticity = 1
    
        body5 = pm.Body(pm.inf,pm.inf)
        body5.position = seg5_pos
        seg5 = pm.Segment(body5,seg5_start,seg5_end,seg_padding)
        seg5.elasticity = 1

        self.space.add(seg1,seg2,seg3,seg4,seg5)
        self.segs = [seg1,seg2,seg3,seg4,seg5]
        
        self.stage_image = pygame.image.load(self.graphics_path + "stage.png").convert_alpha()
        self.gun_base = pygame.image.load(self.graphics_path + "cannonbase.png").convert_alpha()
        self.stats_back = pygame.image.load(self.graphics_path + "statbg.png").convert_alpha()
        self.stats_back2 = pygame.image.load(self.graphics_path + "statbg2.png").convert_alpha()
示例#39
0
class Stage(object):
    def __init__(self,player,screen,width,height,wall_gap,gap_size,seg_padding,bound_color,gravity,x_offset,sidebar_width,bullet_color,is_multiplayer,graphics_path,sound_path):
        self.graphics_path = graphics_path
        self.sound_path = sound_path
        self.player = player
        self.left_key = player.key_cannon_left
        self.right_key = player.key_cannon_right
        self.shoot_key = player.key_cannon_shoot
        self.bullet_color = bullet_color
        self.screen = screen
        self.space = pm.Space()
        self.space.gravity = gravity
        self.space._space.contents.elasticIterations = 10
        self.width = width
        self.height = height
        self.sidebar_width = sidebar_width
        self.wall_gap = wall_gap
        self.gap_size = gap_size
        self.seg_padding = seg_padding
        self.bound_color = bound_color
        self.gravity = gravity
        self.x_offset = x_offset
        self.balls_destroyed = 0
        self.point_total = 0
        self.bullet_limit = 5
        self.space.add_collisionpair_func(1,2,bullet_collision)
        self.space.add_collisionpair_func(1, 3, barrelcannon_load)
        self.swing_limit = 30 # turn this into calculation
        self.child_bonus = 1.5
        self.grandchild_bonus = 2.0
        self.running = True
        self.start_time = time.time()
        self.end_time = 0
        self.end_time_set = False
#        self.spinner_mode = False
        self.spinner_size = 25
        self.spinner_block = None #Buildblock(self,0,self.height/2,60,self.width,(255,0,0))
#        self.barrel_cannon_mode = False
        self.barrel_cannon_block = None
#        self.spinner_count = 0
        self.spinner_limit = 3
        self.spinner_upgrade_level = 0
        self.spinner_max_upgrade_level = 3
        self.barrel_cannon_limit = 1
        self.occupancy_of_blocks = [False, False, False, False, False]
        self.cannon_selected = False
        self.spinner_selected = False
        
        self.is_multiplayer = is_multiplayer
        self.bc_price = 15000
        self.spinner_price = 30000
        self.upgrade_capacity_price = 20000
        self.upgrade_reload_rate_price = 30000
        self.upgrade_spinner_price = 30000
        self.upgrade_bc_price = 25000
        self.upgrade_force_price = 10000
        self.purchases_made = 0
        
        self.virt_x_offset = self.width+self.sidebar_width
        
        display_info = pygame.display.Info()
        self.display_height = display_info.current_h    

        
        # init gun
        self.gun = Gun(self, self.width/2, -10, 15, 30, 1, 1, math.pi/120)
        self.gun.body.angle = math.pi
        self.space.add(self.gun.cannon_shape)
        
        self.balls = []
        self.bullets = []
        self.cannons = []
        self.spinners = []
#===============================================================================
#        swings contains both the connected and disconnected swings and is for drawing them
#        connected swings are the ones that are still connected to the tier1 swing
#        if the connected swing number reaches the maximum and each one has a ball, end game
#        Note: tier1 swings are ALWAYS connected
#===============================================================================
        self.swings = []
        self.connected_swings = []
        
        
        self.buy_index = 0 # current position in buying menu
        #available,upgrade level,(text name,cost),buy action 
        self.max_upgrades = [self.gun.capacity_upgrade_level_max,self.gun.rate_upgrade_level_max,3,3,self.spinner_limit,3]# corresponds to below positions in buy_info
        capacity = [1,self.gun.capacity_upgrade_level_max,[("Bullet Capacity",self.upgrade_capacity_price)],0]
        reload_rate = [1,self.gun.rate_upgrade_level_max,[("Reload Rate",self.upgrade_reload_rate_price)],0]
        impulse = [1,self.gun.impulse_upgrade_level_max,[("Gun Force",self.upgrade_force_price)],0]
        barrel_cannon = [1,3,[("Barrel Cannon",self.bc_price),("Upgrade Barrel Cannon",self.upgrade_bc_price)],0]   
        spinner_available = 0
        if self.is_multiplayer:
            spinner_available = 1
        spinner = [spinner_available,self.spinner_limit,[("Spinner",self.spinner_price)],0]
        spinner_upgrade = [0,3,[("Upgrade Spinners",self.upgrade_spinner_price)],0]
    
        self.buy_info = [capacity,reload_rate,impulse,barrel_cannon,spinner,spinner_upgrade]
        
        vert_wall_height = height-2.0*wall_gap
        horiz_wall_width = (width-(gap_size+2*wall_gap))/2.0 # width of bottom walls
        horiz_top_wall_width = (width-2*wall_gap) # width of top wall
        
        seg1_pos = (wall_gap,height/2.0) # seg1 is left vertical wall
        seg1_start = (0,-vert_wall_height/2.0)
        seg1_end = (0,vert_wall_height/2.0)
    
        seg2_pos = (width-wall_gap,height/2.0) # seg2 is right vertical wall
        seg2_start = (0,-vert_wall_height/2.0) 
        seg2_end = (0,vert_wall_height/2.0)
    
        seg3_pos = (horiz_wall_width/2.0+wall_gap,wall_gap) # seg3 is left horizontal wall
        seg3_start = (-horiz_wall_width/2.0,0)
        seg3_end =  (horiz_wall_width/2.0,-20.0)
    
        seg4_pos = (width-(horiz_wall_width/2.0+wall_gap),wall_gap) # seg4 is right horizontal wall
        seg4_start = (-horiz_wall_width/2.0,-20.0)
        seg4_end = (horiz_wall_width/2.0,0)
    
        seg5_pos = (width/2.0,height-wall_gap)
        seg5_start = (-horiz_top_wall_width/2.0,0)
        seg5_end =  (horiz_top_wall_width/2.0,0)
    
        body1 = pm.Body(pm.inf,pm.inf)
        body1.position = seg1_pos
        seg1 = pm.Segment(body1,seg1_start,seg1_end,seg_padding)
        seg1.elasticity = 1
    
        body2 = pm.Body(pm.inf,pm.inf)
        body2.position = seg2_pos
        seg2 = pm.Segment(body2,seg2_start,seg2_end,seg_padding)
        seg2.elasticity = 1
    
        body3 = pm.Body(pm.inf,pm.inf)
        body3.position = seg3_pos
        seg3 = pm.Segment(body3,seg3_start,seg3_end,seg_padding)
        seg3.elasticity = 1
    
        body4 = pm.Body(pm.inf,pm.inf)
        body4.position = seg4_pos
        seg4 = pm.Segment(body4,seg4_start,seg4_end,seg_padding)
        seg4.elasticity = 1
    
        body5 = pm.Body(pm.inf,pm.inf)
        body5.position = seg5_pos
        seg5 = pm.Segment(body5,seg5_start,seg5_end,seg_padding)
        seg5.elasticity = 1

        self.space.add(seg1,seg2,seg3,seg4,seg5)
        self.segs = [seg1,seg2,seg3,seg4,seg5]
        
        self.stage_image = pygame.image.load(self.graphics_path + "stage.png").convert_alpha()
        self.gun_base = pygame.image.load(self.graphics_path + "cannonbase.png").convert_alpha()
        self.stats_back = pygame.image.load(self.graphics_path + "statbg.png").convert_alpha()
        self.stats_back2 = pygame.image.load(self.graphics_path + "statbg2.png").convert_alpha()
        
    def to_pygame(self, p):
        return int(p.x)+self.x_offset, int(-p.y+self.height)
    
    def draw_self(self):
        #draw the stage area
        self.screen.blit(self.stage_image, (self.x_offset + self.wall_gap, self.wall_gap))

        
        #draw the base of the gun
        
        
#        for seg in self.segs:
#            body = seg.body
#            pv1 = body.position + seg.a.rotated(math.degrees(body.angle))
#            pv2 = body.position + seg.b.rotated(math.degrees(body.angle))
#            p1 = self.to_pygame(pv1)
#            p2 = self.to_pygame(pv2)
#            pygame.draw.lines(self.screen,THECOLORS[self.bound_color], False, [p1,p2])

        for ball in self.balls+self.bullets:
            if ball.body.position.y < 0-ball.radius:
                self.point_total += ball.point_value * ball.point_multiplier
                if(ball.point_value > 0):
                    self.balls_destroyed += 1
                ball.destroy_self()
            else: ball.draw_self()
        for swing in self.swings:
            swing.draw_self()
        for cannon in self.cannons:
            cannon.draw_self()
            
        self.gun.draw_self(self.player.number)
        self.screen.blit(self.gun_base, (self.x_offset + self.width/2 - self.gun_base.get_width()/2, self.height - self.gun_base.get_height() + 3))
        
        for spinner in self.spinners:
            spinner.draw_self()
            
        self.draw_stats()
        self.draw_buy_menu()
        if self.spinner_block != None:
            self.spinner_block.draw_self()
        if self.barrel_cannon_block != None:
             self.barrel_cannon_block.draw_self()
       
        
    def draw_build_zone(self):
        pygame.draw.rect(self.screen, (255,55,0), (self.width/2.0, self.height/2.0, self.width, 60))
    
    def move_items(self):
        for spinner in self.spinners:
            spinner.move()
        for cannon in self.cannons:
            cannon.move()
        
    def draw_stats(self): 
        player_name_str = "Player: "+str(self.player.name)
        bullet_count_str = "Bullets Available: "+ str(self.gun.bullets_curr) #+str(len(self.bullets))
        point_total_str = "Points: "+str(int(self.point_total))
        
        if self.running:
            time_str = "Time: "+str(int(time.time() - self.start_time))
        else:
            time_str = "Time: "+str(int(self.end_time - self.start_time))
            
        stats = [player_name_str,bullet_count_str,point_total_str,time_str]            
        
        verdana = pygame.font.match_font('Verdana')
        verdana_font = pygame.font.Font(verdana,10)
        text_color = (255,255,255)
        
        y_offset = self.height/2*self.player.number
        
        if self.player.number == 0:
            self.screen.blit(self.stats_back, (self.width - 5,y_offset + 10))
        else:
            self.screen.blit(self.stats_back2, (self.width - 5,y_offset + 10))
        
        for stat in stats:
            text = verdana_font.render(stat,1,text_color)
            rect = text.get_rect()
            rect.centerx, rect.y = self.width+self.sidebar_width/2.0,y_offset + 20
        
            self.screen.blit(text,rect)
            y_offset += rect.height
            
    def draw_buy_menu(self):
        verdana = pygame.font.match_font('Verdana')
        verdana_font = pygame.font.Font(verdana,10)
        text_color_active = (255,255,255)
        text_color_inactive = (127,127,127)
        text_bg = (0,0,0)
        
        y_offset = self.height/2*self.player.number + 80
        
        for i in range(len(self.buy_info)):
            item = self.buy_info[i]
            if item[0]:
                if self.buy_index == i:
                    text_color = text_color_active
                else:
                    text_color = text_color_inactive
                text = verdana_font.render(item[2][item[3]][0]+" L"+str(abs(self.max_upgrades[i]-item[1])+1)+": "+str(item[2][item[3]][1]),1,text_color) # item[3] holds switch 
            else:
                continue
            
            rect = text.get_rect()
            rect.centerx, rect.y = self.width+self.sidebar_width/2.0,y_offset
        
            self.screen.blit(text,rect)
            y_offset += rect.height
    
    def build_down_operation(self, opponent_stage):
        if self.buy_index < len(self.buy_info)-1:
            if self.barrel_cannon_block != None:
                self.barrel_cannon_block.move_down()  
                return
            if opponent_stage != None and opponent_stage.spinner_block != None:
                opponent_stage.spinner_block.move_down()
                return
            next_index = self.buy_index+1
            while(next_index < len(self.buy_info)):
                if self.buy_info[next_index][0]:
                    self.buy_index = next_index
                    break
                else:
                    next_index = next_index+1 
               
    def build_up_operation(self, opponent_stage):
        if self.buy_index > 0:
            if self.barrel_cannon_block != None:
                self.barrel_cannon_block.move_up()
                return   
            if opponent_stage != None and opponent_stage.spinner_block != None:
                opponent_stage.spinner_block.move_up()
                return
            next_index = self.buy_index-1
            while next_index >= 0:
                if self.buy_info[next_index][0]:
                    self.buy_index = next_index
                    break
                else:
                    next_index = next_index-1
        elif self.barrel_cannon_block != None:
            self.barrel_cannon_block.move_up()   
        elif opponent_stage != None and opponent_stage.spinner_block != None:
            opponent_stage.spinner_block.move_up()             
    
    def build_operation(self, opponent_stage):
        if self.buy_index == 0: # bullet capacity
            self.buy_capacity()
        elif self.buy_index == 1: # reload rate
            self.buy_reload_rate()
        elif self.buy_index == 2:
            self.buy_gun_force()
        elif self.buy_index == 3: # barrel cannon + upgrade
            self.buy_barrel_cannon(opponent_stage)
        elif self.buy_index == 4: # spinner
            self.buy_spinner(opponent_stage)
        elif self.buy_index == 5: # spinner upgrade
            self.buy_spinner_upgrade(opponent_stage)    

                             
    def cancel_operation(self, opponent_stage):
        self.barrel_cannon_block = None        
        if opponent_stage != None:
            opponent_stage.spinner_block = None   

    def add_ball(self, ball):
        if(isinstance(ball,Bullet)):
           self.bullets.append(ball)
        else:
           self.balls.append(ball)
    
    def remove_ball(self, ball): 
       if(isinstance(ball,Bullet)):
           self.bullets.remove(ball)
       else:
           self.balls.remove(ball)
           
    def process_input(self):
        if self.player.controller:
            if (self.player.controller.get_axis(0) > 0.5):
                self.gun.move_right()
            elif (self.player.controller.get_axis(0) < -0.5):
                self.gun.move_left()
        else:
            pressed_keys = pygame.key.get_pressed()
            if pressed_keys[self.left_key]:
                self.gun.move_left()
            elif pressed_keys[self.right_key]:
                self.gun.move_right()
    
    def bullet_reload(self,time): #this is time independent with each gun
        if time-self.gun.last_reload_time >= self.gun.reload_rate:
            self.gun.last_reload_time = time
            if self.gun.bullets_curr < self.gun.max_bullets:
                self.gun.bullets_curr += 1
    
    def spawn_spinner(self):
#        print "spawn spin"
        if len(self.spinners)%2 == 0:
            direction = 2
        else:
            direction = -2
            
        new_spinner = Spinner(self, .5*self.width, -(self.spinner_block.pos_y + self.wall_gap + 30) + self.height, self.spinner_size, self.spinner_size, 0, 1, -math.pi/60, direction, .1*self.width, .9*self.width)
        self.spinners.append(new_spinner)
        
    def spawn_barrel_cannon(self):
        new_barrel_cannon = Barrelcannon(self, .5*self.width, -(self.barrel_cannon_block.pos_y + self.wall_gap + 30) + self.height, 20, 30, 1, 1, -math.pi/60, 2, .2*self.width, .8*self.width)
        
    def spawn_swing(self): # set running to False if no more swings can be spawned, signaling endgame
        if len(self.connected_swings) >= self.swing_limit: #all swings are connected
            all_have_balls = True # all the connected swings have balls
            for swing in self.connected_swings:
                if swing.ball == None:
                    all_have_balls = False
                    break

            if all_have_balls:    
                self.running = False
        else:
            init_swing_cnt = len(self.connected_swings)
            spawned = False
            while spawned == False:
                rand_swing_index = random.randint(0,len(self.connected_swings)-1)
                sel_swing = self.connected_swings[rand_swing_index]
                
                ball_spawn = False
                if sel_swing.ball == None:
                    ball_spawn = sel_swing.respawn_ball(sel_swing.circle_mass,sel_swing.radius,1, "red")
                else:
                    new_tier = sel_swing.tier + 1
                        
                    if new_tier == 2:
                        new_swing = Polyswing(self,200,550,1,1,.33*sel_swing.section_mass,500,1,.33*sel_swing.circle_mass,15,1,4,sel_swing,2,new_tier,"red")
                    else: #its tier 3
                        new_swing = Polyswing(self,200,550,1,1,.5*sel_swing.section_mass,500,1,.5*sel_swing.circle_mass,10,1,2,sel_swing,0,new_tier, "red")         
              
                if ball_spawn or len(self.connected_swings) > init_swing_cnt:
                    spawned = True
                    
    def set_end_time(self):
        if self.end_time_set == False:
            self.end_time = time.time()
            self.end_time_set = True
            
    def set_spinner_block(self):
        self.spinner_block = Buildblock(self,0,self.height/2,60,self.width,(255,0,0))
    
    def set_barrel_cannon_block(self):
        self.barrel_cannon_block = Buildblock(self,0,self.height/2,60,self.width,(0,255,0))
        
    def objects_to_send(self):
        master_list = [] # list of dictionaries
        # go through balls, swings, cannons, guns, spinners
        ball_list = []
        for ball in self.balls: # each ball takes up four slots
            ball_list.append(int(ball.body.position.x+self.virt_x_offset))
            ball_list.append(int(self.display_height-int(ball.body.position.y)))
            ball_list.append(ball.color_index)
            ball_list.append(ball.radius)
        master_list.append(ball_list)
        
        bullet_list = []
        for bullet in self.bullets: # each bullet takes up four slots
            bullet_list.append(int(bullet.body.position.x+self.virt_x_offset))
            bullet_list.append(int(self.display_height-int(bullet.body.position.y)))
            bullet_list.append(bullet.color_index)
            #bullet_list.append(bullet.radius)
        master_list.append(bullet_list)
        
        swing_list = []    
        for swing in self.swings:
            for section in swing.sections: 
                if section != swing.sections[-1]:
                    length = self.distance(section.body.position, swing.sections[swing.sections.index(section)+1].body.position)
                    angle = self.angle(section.body.position, swing.sections[swing.sections.index(section)+1].body.position)
#                    print angle
                    
                    if len(swing.sections) == 2:
                        image = 0
                        #vine_scaled = pygame.transform.scale(self.vine_short, (6, int(length + 2)))
                    else: #its longer than 2
                        if section == swing.sections[0]: #first section
                            image = 1
                            #vine_scaled = pygame.transform.scale(self.vine_top, (6, int(length + 2)))
                        elif section == swing.sections[-2]: # second to last section
                            image = 2
                            #vine_scaled = pygame.transform.scale(self.vine_bot, (6, int(length + 2)))
                        else: #everything else
                            image = 3
                            #vine_scaled = pygame.transform.scale(self.vine_mid, (6, int(length + 2)))
                    
                    vine_angle = int(90 + (angle*180)/math.pi)
                    #vine_turned = pygame.transform.rotate(vine_scaled, 90 + (angle*180)/math.pi)
                    #vine_flipped = pygame.transform.flip(vine_turned, True, True)
                    
                    #at 0 degrees it points to the right and it rotates CCW
                    
                    if angle <= 0 and angle > -math.pi/2:

                        xpos = -math.sin(angle) * -3
                        ypos = math.cos(angle) * -3
                        
                    elif angle  <= -math.pi/2 and angle > -math.pi:
                        
                        xpos = -math.sin(angle) * (-3) + math.cos(angle) * (length + 2)
                        ypos = -math.cos(angle) * (-3)

                    elif angle  <= math.pi and angle > math.pi/2:
                        
                        xpos = math.cos(angle) * (length + 2) + math.sin(angle) * -3
                        ypos = -math.sin(angle) * (length + 2)
                    else:
                        xpos = math.sin(angle) * (-3)
                        ypos = math.cos(angle) * -3 + -math.sin(angle) * (length + 2)

                    swing_list.append(image)
                    swing_list.append(int(section.body.position.x+self.virt_x_offset + xpos))
                    swing_list.append(int(self.display_height - section.body.position.y + ypos))
                    swing_list.append(vine_angle)
                    swing_list.append(int(length))
                    
#                    self.stage.screen.blit(vine_turned, (section.body.position.x+self.stage.x_offset + xpos, self.stage.display_height - section.body.position.y + ypos))                
#                swing_list.append(int(section.body.position.x+self.virt_x_offset))
#                swing_list.append(int(self.display_height-int(section.body.position.y)))
        master_list.append(swing_list)
        
        cannon_list = []
        for cannon in self.cannons: # each cannon takes up 9 slots
            
            if cannon.body.angle <= 0 and cannon.body.angle > -math.pi/2:
                #print "down to left"
                xpos = math.cos(cannon.body.angle) * (-cannon.width) + -math.sin(cannon.body.angle) * (-cannon.height) 
                ypos = -math.sin(cannon.body.angle) * (-cannon.width) + -math.cos(cannon.body.angle) * (cannon.height) 
            elif cannon.body.angle <= -math.pi/2 and cannon.body.angle > -math.pi:
                #print "left to up"
                xpos = -math.cos(cannon.body.angle) * (-cannon.width) + -math.sin(cannon.body.angle) * (-cannon.height) 
                ypos = -math.sin(cannon.body.angle) * (-cannon.width) + -math.cos(cannon.body.angle) * (-cannon.height) 
            elif cannon.body.angle <= -math.pi and cannon.body.angle > -3*math.pi/2:
                #print "up to right"
                xpos = -math.cos(cannon.body.angle) * (-cannon.width) + math.sin(cannon.body.angle) * (-cannon.height) 
                ypos = math.sin(cannon.body.angle) * (-cannon.width) + -math.cos(cannon.body.angle) * (-cannon.height)
            else:
                #print "right to down"
                xpos = math.cos(cannon.body.angle) * (-cannon.width) + math.sin(cannon.body.angle) * (-cannon.height) 
                ypos = math.sin(cannon.body.angle) * (-cannon.width) + math.cos(cannon.body.angle) * (-cannon.height)
            
            x = cannon.body.position.x+self.virt_x_offset + xpos
            y = self.display_height - cannon.body.position.y + ypos
            angle = int((cannon.body.angle*180)/math.pi)
            
            if(cannon.loaded):
                isLoaded = 1
            else:
                isLoaded = 0
            cannon_list.append(int(x))
            cannon_list.append(int(y))
            cannon_list.append(angle)
            cannon_list.append(isLoaded)
        master_list.append(cannon_list)
        
        spinner_list = []
        for spinner in self.spinners: # each spinner takes up 8 slots
            seg1_pt1 = spinner.seg1.body.position+spinner.seg1.a.rotated(math.degrees(spinner.seg1.body.angle))
            seg1_pt2 = spinner.seg1.body.position+spinner.seg1.b.rotated(math.degrees(spinner.seg1.body.angle))
            seg1_pt1_x = self.virt_x_offset+seg1_pt1.x
            seg1_pt1_y = -seg1_pt1.y+self.height
            seg1_pt2_x = self.virt_x_offset+seg1_pt2.x
            seg1_pt2_y = -seg1_pt2.y+self.height
            
            seg2_pt1 = spinner.seg2.body.position+spinner.seg2.a.rotated(math.degrees(spinner.seg1.body.angle))
            seg2_pt2 = spinner.seg2.body.position+spinner.seg2.b.rotated(math.degrees(spinner.seg1.body.angle))
            seg2_pt1_x = self.virt_x_offset+seg2_pt1.x
            seg2_pt1_y = -seg2_pt1.y+self.height
            seg2_pt2_x = self.virt_x_offset+seg2_pt2.x
            seg2_pt2_y = -seg2_pt2.y+self.height
                      
            seg1_pts = [seg1_pt1_x,seg1_pt1_y,seg1_pt2_x,seg1_pt2_y]
            seg2_pts = [seg2_pt1_x,seg2_pt1_y,seg2_pt2_x,seg2_pt2_y]
            
            spinner_list.append(seg1_pts[0])
            spinner_list.append(seg1_pts[1])
            spinner_list.append(seg1_pts[2])
            spinner_list.append(seg1_pts[3])
            spinner_list.append(seg2_pts[0])
            spinner_list.append(seg2_pts[1])
            spinner_list.append(seg2_pts[2])
            spinner_list.append(seg2_pts[3])
        master_list.append(spinner_list)
        
        #gun
        if self.gun.body.angle > math.pi:
            xpos = -math.cos(self.gun.body.angle) * (-self.gun.width - 3) + -math.sin(self.gun.body.angle) * (-3*self.gun.height - 3) 
            ypos = -math.sin(self.gun.body.angle) * (-self.gun.width - 3) + -math.cos(self.gun.body.angle) * (-3*self.gun.height - 3) 
        else:
            xpos = -math.cos(self.gun.body.angle) * (-self.gun.width - 3) + -math.sin(self.gun.body.angle) * (-self.gun.height + 3) 
            ypos = -math.sin(self.gun.body.angle) * (self.gun.width + 3) + -math.cos(self.gun.body.angle) * (-3*self.gun.height - 3) 
        
        x = self.gun.cannon_shape.body.position.x + self.virt_x_offset + xpos
        y = self.display_height - self.gun.cannon_shape.body.position.y + ypos
        gun_angle = int((self.gun.body.angle*180)/math.pi)
        
        master_list.append(int(x))
        master_list.append(int(y))
        master_list.append(gun_angle)
        #    TODO: add block occupancy info too
        master_list.append(self.point_total)
        master_list.append(self.gun.bullets_curr)
        master_list.append(self.running)
        
        return master_list

    def distance(self, p1, p2):
            x1 = p1.x
            x2 = p2.x
            
            y1 = p1.y
            y2 = p2.y
            return math.sqrt( ( x1-x2 )**2 + ( y1-y2 )**2 )
        
    def angle(self, p1, p2):
            x1 = p1.x
            x2 = p2.x
            
            y1 = p1.y
            y2 = p2.y
            return math.atan2(y2-y1, x2-x1)
   
    def buy_capacity(self):
        # capacity = [1,self.gun.capacity_upgrade_level_max,[("Upgrade Capacity",self.upgrade_capacity_price)],self.buy_capacity]
        info = self.buy_info[0]
        upgrade_price = info[2][0][1]
        upgrade_level = info[1]
        if self.point_total >= upgrade_price and upgrade_level > 0:
            info[1] -= 1
            self.gun.max_bullets += 1
            self.point_total -= upgrade_price
            self.purchases_made += 1
        if info[1] == 0: # if no more upgrades are possible
            info[0] = 0
            self.build_up_operation(None)
            
    def buy_reload_rate(self):
        # reload_rate = [1,self.gun.rate_upgrade_level_max,[("Reload Rate",self.upgrade_reload_rate_price)],self.buy_reload_rate]
        info = self.buy_info[1]
        upgrade_price = info[2][0][1]
        upgrade_level = info[1]
        if self.point_total >= upgrade_price and upgrade_level > 0:
            info[1] -= 1
            self.gun.reload_rate -= 0.2
            self.point_total -= upgrade_price
            self.purchases_made += 1
        if info[1] == 0: # if no more upgrades are possible
            info[0] = 0
            self.build_up_operation(None)
            
    def buy_gun_force(self):
        info = self.buy_info[2]
        upgrade_price = info[2][0][1]
        upgrade_level = info[1]
        if self.point_total >= upgrade_price and upgrade_level > 0:
            info[1] -= 1
            self.gun.impulse_upgrade_level += 1
            self.point_total -= upgrade_price
            self.purchases_made += 1
        if info[1] == 0: # if no more upgrades are possible
            info[0] = 0
            self.build_up_operation(None)
            
    def buy_barrel_cannon(self,opponent_stage):
        # barrel_cannon = [1,3,[("Barrel Cannon",self.bc_price),("Upgrade Barrel Cannon",self.upgrade_bc_price)],self.buy_barrel_cannon]
        info = self.buy_info[3]
        upgrade_level = info[1]
        if len(self.cannons) == 0: # if building cannon
            upgrade_price = info[2][0][1]
            if self.barrel_cannon_block == None and (opponent_stage == None or opponent_stage.spinner_block == None):
                if self.point_total >= upgrade_price and upgrade_level > 0:
                    self.set_barrel_cannon_block()
            elif self.barrel_cannon_block and self.occupancy_of_blocks[self.barrel_cannon_block.get_occupancy_index()] == False:
                info[1] -= 1
                self.spawn_barrel_cannon()
                self.occupancy_of_blocks[self.barrel_cannon_block.get_occupancy_index()] = True
                self.barrel_cannon_block = None
                self.point_total -= upgrade_price
                self.purchases_made += 1
                self.buy_info[3][3] = 1 # switch to display Cannon Upgrade
        else: # if upgrading cannon
            upgrade_price = info[2][1][1]
            if self.point_total >= upgrade_price and upgrade_level > 0:
                for cannon in self.cannons:
                    if cannon.upgrade < cannon.upgrade_max:
                        info[1] -= 1
                        cannon.upgrade += 1 
                        self.point_total -= upgrade_price
                        self.purchases_made += 1
                if info[1] == 0: # if no more upgrades are possible
                    info[0] = 0
                    self.build_up_operation(None) 
            
    def buy_spinner(self,opponent_stage):
        info = self.buy_info[4]
        upgrade_level = info[1]
        upgrade_price = info[2][0][1]
        if self.barrel_cannon_block == None and opponent_stage.spinner_block == None:
            if len(opponent_stage.spinners) < opponent_stage.spinner_limit and self.point_total >= upgrade_price and upgrade_level:
                opponent_stage.set_spinner_block()
        elif opponent_stage.spinner_block != None and opponent_stage.occupancy_of_blocks[opponent_stage.spinner_block.get_occupancy_index()] == False:
            info[1] -= 1
            opponent_stage.spawn_spinner()
            opponent_stage.occupancy_of_blocks[opponent_stage.spinner_block.get_occupancy_index()] = True
            opponent_stage.spinner_block = None
            self.point_total -= upgrade_price
            self.purchases_made += 1
            if len(opponent_stage.spinners) >= opponent_stage.spinner_limit:
                info[0] = 0 # disable display on buy menu
                self.build_up_operation(None)
            if self.buy_info[5][1] != 0:
                self.buy_info[5][0] = 1 # enable display for spinner upgrades

    def buy_spinner_upgrade(self,opponent_stage):
        info = self.buy_info[5]
        upgrade_level = info[1]
        upgrade_price = info[2][0][1]
        if self.point_total >= upgrade_price and upgrade_level > 0:
            info[1] -=1
            self.point_total -= upgrade_price
            self.purchases_made += 1
            
            opponent_stage.spinner_size += 10
            for spinner in opponent_stage.spinners:
                opponent_stage.space.remove(spinner.seg1,spinner.seg2)      
                spinner.seg1 = pm.Segment(spinner.body, (-opponent_stage.spinner_size/2,0), (opponent_stage.spinner_size/2,0), 5)
                spinner.seg2 = pm.Segment(spinner.body, (0,-opponent_stage.spinner_size/2), (0,opponent_stage.spinner_size/2), 5)              
                opponent_stage.space.add(spinner.seg1,spinner.seg2)
            
            if info[1] == 0: # if no more upgrades are possible
                info[0] = 0
                self.build_up_operation(None)
示例#40
0
class PlayerBase(DirectObject):
    def __init__(self):
        # Player Model setup
        self.player = Actor("Player",
                            {"Run":"Player-Run",
                            "Sidestep":"Player-Sidestep",
                            "Idle":"Player-Idle"})
        self.player.setBlend(frameBlend = True)
        self.player.setPos(0, 0, 0)
        self.player.pose("Idle", 0)
        self.player.reparentTo(render)
        self.player.hide()

        self.footstep = base.audio3d.loadSfx('footstep.ogg')
        self.footstep.setLoop(True)
        base.audio3d.attachSoundToObject(self.footstep, self.player)

        # Create a brush to paint on the texture
        splat = PNMImage("../data/Splat.png")
        self.colorBrush = PNMBrush.makeImage(splat, 6, 6, 1)

        CamMask = BitMask32.bit(0)
        AvBufMask = BitMask32.bit(1)
        self.avbuf = None
        if base.win:
            self.avbufTex = Texture('avbuf')
            self.avbuf = base.win.makeTextureBuffer('avbuf', 256, 256, self.avbufTex, True)
            cam = Camera('avbuf')
            cam.setLens(base.camNode.getLens())
            self.avbufCam = base.cam.attachNewNode(cam)
            dr = self.avbuf.makeDisplayRegion()
            dr.setCamera(self.avbufCam)
            self.avbuf.setActive(False)
            self.avbuf.setClearColor((1, 0, 0, 1))
            cam.setCameraMask(AvBufMask)
            base.camNode.setCameraMask(CamMask)

            # avbuf renders everything it sees with the gradient texture.
            tex = loader.loadTexture('gradient.png')
            np = NodePath('np')
            np.setTexture(tex, 100)
            np.setColor((1, 1, 1, 1), 100)
            np.setColorScaleOff(100)
            np.setTransparency(TransparencyAttrib.MNone, 100)
            np.setLightOff(100)
            cam.setInitialState(np.getState())
            #render.hide(AvBufMask)

        # Setup a texture stage to paint on the player
        self.paintTs = TextureStage('paintTs')
        self.paintTs.setMode(TextureStage.MDecal)
        self.paintTs.setSort(10)
        self.paintTs.setPriority(10)

        self.tex = Texture('paint_av_%s'%id(self))

        # Setup a PNMImage that will hold the paintable texture of the player
        self.imageSizeX = 64
        self.imageSizeY = 64
        self.p = PNMImage(self.imageSizeX, self.imageSizeY, 4)
        self.p.fill(1)
        self.p.alphaFill(0)
        self.tex.load(self.p)
        self.tex.setWrapU(self.tex.WMClamp)
        self.tex.setWrapV(self.tex.WMClamp)

        # Apply the paintable texture to the avatar
        self.player.setTexture(self.paintTs, self.tex)

        # team
        self.playerTeam = ""
        # A lable that will display the players team
        self.lblTeam = DirectLabel(
            scale = 1,
            pos = (0, 0, 3),
            frameColor = (0, 0, 0, 0),
            text = "TEAM",
            text_align = TextNode.ACenter,
            text_fg = (0,0,0,1))
        self.lblTeam.reparentTo(self.player)
        self.lblTeam.setBillboardPointEye()

        # basic player values
        self.maxHits = 3
        self.currentHits = 0
        self.isOut = False

        self.TorsorControl = self.player.controlJoint(None,"modelRoot","Torsor")

        # setup the collision detection
        # wall and object collision
        self.playerSphere = CollisionSphere(0, 0, 1, 1)
        self.playerCollision = self.player.attachNewNode(CollisionNode("playerCollision%d"%id(self)))
        self.playerCollision.node().addSolid(self.playerSphere)
        base.pusher.addCollider(self.playerCollision, self.player)
        base.cTrav.addCollider(self.playerCollision, base.pusher)
        # foot (walk) collision
        self.playerFootRay = self.player.attachNewNode(CollisionNode("playerFootCollision%d"%id(self)))
        self.playerFootRay.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -1))
        self.playerFootRay.node().setIntoCollideMask(0)
        self.lifter = CollisionHandlerFloor()
        self.lifter.addCollider(self.playerFootRay, self.player)
        base.cTrav.addCollider(self.playerFootRay, self.lifter)

        # Player weapon setup
        self.gunAttach = self.player.exposeJoint(None, "modelRoot", "WeaponSlot_R")
        self.color = LPoint3f(1, 1, 1)
        self.gun = Gun(id(self))
        self.gun.reparentTo(self.gunAttach)
        self.gun.hide()
        self.gun.setColor(self.color)

        self.hud = None

        # Player controls setup
        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0}
        # screen sizes
        self.winXhalf = base.win.getXSize() / 2
        self.winYhalf = base.win.getYSize() / 2
        self.mouseSpeedX = 0.1
        self.mouseSpeedY = 0.1
        # AI controllable variables
        self.AIP = 0.0
        self.AIH = 0.0

        self.movespeed = 5.0

        self.userControlled = False

        self.accept("Bulet-hit-playerCollision%d" % id(self), self.hit)
        self.accept("window-event", self.recalcAspectRatio)

    def runBase(self):
        self.player.show()
        self.gun.show()
        taskMgr.add(self.move, "moveTask%d"%id(self), priority=-4)

    def stopBase(self):
        taskMgr.remove("moveTask%d"%id(self))
        self.ignoreAll()
        self.gun.remove()
        self.footstep.stop()
        base.audio3d.detachSound(self.footstep)
        self.player.delete()

    def setKey(self, key, value):
        self.keyMap[key] = value

    def setPos(self, pos):
        self.player.setPos(pos)

    def setColor(self, color=LPoint3f(0,0,0)):
        self.color = color
        self.gun.setColor(color)
        c = (color[0], color[1], color[2], 1.0)
        self.lblTeam["text_fg"] = c

    def setTeam(self, team):
        self.playerTeam = team
        self.lblTeam["text"] = team


    def shoot(self, shotVec=None):
        self.gun.shoot(shotVec)
        if self.hud != None:
            self.hud.updateAmmo(self.gun.maxAmmunition, self.gun.ammunition)

    def reload(self):
        self.gun.reload()
        if self.hud != None:
            self.hud.updateAmmo(self.gun.maxAmmunition, self.gun.ammunition)

    def recalcAspectRatio(self, window):
        self.winXhalf = window.getXSize() / 2
        self.winYhalf = window.getYSize() / 2

    def hit(self, entry, color):
        self.currentHits += 1

        # Create a brush to paint on the texture
        splat = PNMImage("../data/Splat.png")
        splat = splat * LColorf(color[0], color[1], color[2], 1.0)
        self.colorBrush = PNMBrush.makeImage(splat, 6, 6, 1)

        self.paintAvatar(entry)

        if self.currentHits >= self.maxHits:
            base.messenger.send("GameOver-player%d" % id(self))
            self.isOut = True

    def __paint(self, s, t):
        """ Paints a point on the avatar at texture coordinates (s, t). """
        x = (s * self.p.getXSize())
        y = ((1.0 - t) * self.p.getYSize())

        # Draw in color directly on the avatar
        p1 = PNMPainter(self.p)
        p1.setPen(self.colorBrush)
        p1.drawPoint(x, y)

        self.tex.load(self.p)
        self.tex.setWrapU(self.tex.WMClamp)
        self.tex.setWrapV(self.tex.WMClamp)

        self.paintDirty = True

    def paintAvatar(self, entry):
        """ Paints onto an avatar.  Returns true on success, false on
        failure (because there are no avatar pixels under the mouse,
        for instance). """

        # First, we have to render the avatar in its false-color
        # image, to determine which part of its texture is under the
        # mouse.
        if not self.avbuf:
            return False

        #mpos = base.mouseWatcherNode.getMouse()
        mpos = entry.getSurfacePoint(self.player)
        ppos = entry.getSurfacePoint(render)

        self.player.showThrough(BitMask32.bit(1))
        self.avbuf.setActive(True)
        base.graphicsEngine.renderFrame()
        self.player.show(BitMask32.bit(1))
        self.avbuf.setActive(False)

        # Now we have the rendered image in self.avbufTex.
        if not self.avbufTex.hasRamImage():
            print "Weird, no image in avbufTex."
            return False
        p = PNMImage()
        self.avbufTex.store(p)
        ix = int((1 + mpos.getX()) * p.getXSize() * 0.5)
        iy = int((1 - mpos.getY()) * p.getYSize() * 0.5)
        x = 1
        if ix >= 0 and ix < p.getXSize() and iy >= 0 and iy < p.getYSize():
            s = p.getBlue(ix, iy)
            t = p.getGreen(ix, iy)
            x = p.getRed(ix, iy)
        if x > 0.5:
            # Off the avatar.
            return False

        # At point (s, t) on the avatar's map.

        self.__paint(s, t)
        return True

    def move(self, task):
        if self is None: return task.done
        if self.userControlled:
            if not base.mouseWatcherNode.hasMouse(): return task.cont
            self.pointer = base.win.getPointer(0)
            mouseX = self.pointer.getX()
            mouseY = self.pointer.getY()

            if base.win.movePointer(0, self.winXhalf, self.winYhalf):
                p = self.TorsorControl.getP() + (mouseY - self.winYhalf) * self.mouseSpeedY
                if p <-80:
                    p = -80
                elif p > 90:
                    p = 90
                self.TorsorControl.setP(p)

                h = self.player.getH() - (mouseX - self.winXhalf) * self.mouseSpeedX
                if h <-360:
                    h = 360
                elif h > 360:
                    h = -360
                self.player.setH(h)
        else:
            self.TorsorControl.setP(self.AIP)
            self.player.setH(self.AIH)

        forward =  self.keyMap["forward"] != 0
        backward = self.keyMap["backward"] != 0

        if self.keyMap["left"] != 0:
            if self.player.getCurrentAnim() != "Sidestep" and not (forward or backward):
                self.player.loop("Sidestep")
                self.player.setPlayRate(5, "Sidestep")
            self.player.setX(self.player, self.movespeed * globalClock.getDt())
        elif self.keyMap["right"] != 0:
            if self.player.getCurrentAnim() != "Sidestep" and not (forward or backward):
                self.player.loop("Sidestep")
                self.player.setPlayRate(5, "Sidestep")
            self.player.setX(self.player, -self.movespeed * globalClock.getDt())
        else:
            self.player.stop("Sidestep")
        if forward:
            if self.player.getCurrentAnim() != "Run":
                self.player.loop("Run")
                self.player.setPlayRate(5, "Run")
            self.player.setY(self.player, -self.movespeed * globalClock.getDt())
        elif backward:
            if self.player.getCurrentAnim() != "Run":
                self.player.loop("Run")
                self.player.setPlayRate(-5, "Run")
            self.player.setY(self.player, self.movespeed * globalClock.getDt())
        else:
            self.player.stop("Run")

        if not (self.keyMap["left"] or self.keyMap["right"] or
                self.keyMap["forward"] or self.keyMap["backward"] or
                self.player.getCurrentAnim() == "Idle"):
            self.player.loop("Idle")
            self.footstep.stop()
        else:
            self.footstep.play()

        return task.cont
示例#41
0
class Teammate(pygame.sprite.Sprite):
	def __init__(self, center, gs=None):
		pygame.sprite.Sprite.__init__(self)

		self.gs = gs
		self.image = pygame.image.load("imgs/tank2.png")
		self.orig_image = pygame.image.load("imgs/tank2.png")
		# tank is a tad smaller than gun bc collision detecting
		self.image = pygame.transform.scale(self.image, (40, 40))
		self.orig_image = pygame.transform.scale(self.orig_image, (40, 40))
		self.rect = self.image.get_rect()
		self.rect.center = center
		self.fire_x = 0
		self.fire_y = 0
		self.fire_timer = 0
		self.tofire = False
		self.mx=0
		self.my=0	
		self.gun = Gun(self.rect.center, self.gs)
		self.hold = False
		self.key = 0

	def tick(self):
		if self.hold and self.key is not 0:
			self.move(self.key)

		dx = self.mx - self.rect.centerx
		dy = self.rect.centery - self.my
		if self.fire_timer != 0:
			self.fire_timer -= 1
		if self.tofire == True and self.fire_timer == 0:
			self.fire_timer = 60
			# can still come from center of tank since the 
			# gun will be pointing in the same direction
			# ^^ jk because of collision detection

			fire_x, fire_y = self.mx, self.my
			angle = math.atan2(self.rect.centery-fire_y, fire_x-self.rect.centerx)
			pellet_center = (self.rect.centerx+math.cos(angle)*36,self.rect.centery-math.sin(angle)*36)
			pellet = Pellet(self, angle, pellet_center, self.gs)
			self.gs.pellets.append(pellet)

			#########################################################
			# SOUND
			#if pygame.mixer.music.get_busy() == False:
			#	pygame.mixer.music.load("screammachine.wav")
			#	pygame.mixer.music.set_volume(1)
			#	pygame.mixer.music.play()
		else:
			#pygame.mixer.stop()
			if dx != 0:
				self.gun.rotate(dx, dy)

	def move(self, keycode):
		"""
		Called when keydown is detected in main
		"""
		#self.gun.move(keycode)

		if keycode == 273 or keycode == 119:
			# trial
			if self.checkBlocks((0, -3)) is False:
				self.rect = self.rect.move(0, -3)
				self.gun.move((0,-3))
		elif keycode == 274 or keycode == 115:
			if self.checkBlocks((0, 3)) is False:
				self.rect = self.rect.move(0, 3)
				self.gun.move((0, 3))
		elif keycode == 275 or keycode == 100:
			if self.checkBlocks((3, 0)) is False:
				self.rect = self.rect.move(3, 0)
				self.gun.move((3, 0))
		elif keycode == 276 or keycode == 97:
			if self.checkBlocks((-3, 0)) is False:
				self.rect = self.rect.move(-3, 0)
				self.gun.move((-3, 0))

	def checkBlocks(self, movement):
		"""
		Return True if there is any overlap
		"""
		collide = False
		self.temp_rect = self.rect.move(movement[0], 0)
		for block in self.gs.blocks:
			if pygame.Rect.colliderect(self.temp_rect, block.rect):
				collide = True
		
		self.temp_rect = self.rect.move(0, movement[1])
		for block in self.gs.blocks:
			if pygame.Rect.colliderect(self.temp_rect, block.rect):
				collide = True
		
		return collide

	def explode(self):
		if self.gs.tank1_life:
			self.gs.tank1_life = False
			center = deepcopy(self.rect.center)
			self.gs.explosions.append(Explosion(center, self.gs))
示例#42
0
    def __init__(self):
        # Player Model setup
        self.player = Actor("Player",
                            {"Run":"Player-Run",
                            "Sidestep":"Player-Sidestep",
                            "Idle":"Player-Idle"})
        self.player.setBlend(frameBlend = True)
        self.player.setPos(0, 0, 0)
        self.player.pose("Idle", 0)
        self.player.reparentTo(render)
        self.player.hide()

        self.footstep = base.audio3d.loadSfx('footstep.ogg')
        self.footstep.setLoop(True)
        base.audio3d.attachSoundToObject(self.footstep, self.player)

        # Create a brush to paint on the texture
        splat = PNMImage("../data/Splat.png")
        self.colorBrush = PNMBrush.makeImage(splat, 6, 6, 1)

        CamMask = BitMask32.bit(0)
        AvBufMask = BitMask32.bit(1)
        self.avbuf = None
        if base.win:
            self.avbufTex = Texture('avbuf')
            self.avbuf = base.win.makeTextureBuffer('avbuf', 256, 256, self.avbufTex, True)
            cam = Camera('avbuf')
            cam.setLens(base.camNode.getLens())
            self.avbufCam = base.cam.attachNewNode(cam)
            dr = self.avbuf.makeDisplayRegion()
            dr.setCamera(self.avbufCam)
            self.avbuf.setActive(False)
            self.avbuf.setClearColor((1, 0, 0, 1))
            cam.setCameraMask(AvBufMask)
            base.camNode.setCameraMask(CamMask)

            # avbuf renders everything it sees with the gradient texture.
            tex = loader.loadTexture('gradient.png')
            np = NodePath('np')
            np.setTexture(tex, 100)
            np.setColor((1, 1, 1, 1), 100)
            np.setColorScaleOff(100)
            np.setTransparency(TransparencyAttrib.MNone, 100)
            np.setLightOff(100)
            cam.setInitialState(np.getState())
            #render.hide(AvBufMask)

        # Setup a texture stage to paint on the player
        self.paintTs = TextureStage('paintTs')
        self.paintTs.setMode(TextureStage.MDecal)
        self.paintTs.setSort(10)
        self.paintTs.setPriority(10)

        self.tex = Texture('paint_av_%s'%id(self))

        # Setup a PNMImage that will hold the paintable texture of the player
        self.imageSizeX = 64
        self.imageSizeY = 64
        self.p = PNMImage(self.imageSizeX, self.imageSizeY, 4)
        self.p.fill(1)
        self.p.alphaFill(0)
        self.tex.load(self.p)
        self.tex.setWrapU(self.tex.WMClamp)
        self.tex.setWrapV(self.tex.WMClamp)

        # Apply the paintable texture to the avatar
        self.player.setTexture(self.paintTs, self.tex)

        # team
        self.playerTeam = ""
        # A lable that will display the players team
        self.lblTeam = DirectLabel(
            scale = 1,
            pos = (0, 0, 3),
            frameColor = (0, 0, 0, 0),
            text = "TEAM",
            text_align = TextNode.ACenter,
            text_fg = (0,0,0,1))
        self.lblTeam.reparentTo(self.player)
        self.lblTeam.setBillboardPointEye()

        # basic player values
        self.maxHits = 3
        self.currentHits = 0
        self.isOut = False

        self.TorsorControl = self.player.controlJoint(None,"modelRoot","Torsor")

        # setup the collision detection
        # wall and object collision
        self.playerSphere = CollisionSphere(0, 0, 1, 1)
        self.playerCollision = self.player.attachNewNode(CollisionNode("playerCollision%d"%id(self)))
        self.playerCollision.node().addSolid(self.playerSphere)
        base.pusher.addCollider(self.playerCollision, self.player)
        base.cTrav.addCollider(self.playerCollision, base.pusher)
        # foot (walk) collision
        self.playerFootRay = self.player.attachNewNode(CollisionNode("playerFootCollision%d"%id(self)))
        self.playerFootRay.node().addSolid(CollisionRay(0, 0, 2, 0, 0, -1))
        self.playerFootRay.node().setIntoCollideMask(0)
        self.lifter = CollisionHandlerFloor()
        self.lifter.addCollider(self.playerFootRay, self.player)
        base.cTrav.addCollider(self.playerFootRay, self.lifter)

        # Player weapon setup
        self.gunAttach = self.player.exposeJoint(None, "modelRoot", "WeaponSlot_R")
        self.color = LPoint3f(1, 1, 1)
        self.gun = Gun(id(self))
        self.gun.reparentTo(self.gunAttach)
        self.gun.hide()
        self.gun.setColor(self.color)

        self.hud = None

        # Player controls setup
        self.keyMap = {"left":0, "right":0, "forward":0, "backward":0}
        # screen sizes
        self.winXhalf = base.win.getXSize() / 2
        self.winYhalf = base.win.getYSize() / 2
        self.mouseSpeedX = 0.1
        self.mouseSpeedY = 0.1
        # AI controllable variables
        self.AIP = 0.0
        self.AIH = 0.0

        self.movespeed = 5.0

        self.userControlled = False

        self.accept("Bulet-hit-playerCollision%d" % id(self), self.hit)
        self.accept("window-event", self.recalcAspectRatio)