Example #1
0
class Asteroid(games.Sprite):
    """ Астеройд, прямолинейно движущийся по экрану. """
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    images = {SMALL: games.load_image(os.path.join(STATIC, 'cartman_small.jpg')),
              MEDIUM: games.load_image(os.path.join(STATIC, 'cartman_medium.jpg')),
              LARGE: games.load_image(os.path.join(STATIC, 'cartman_big.jpg'))}

    SPEED = 2

    def __init__(self, x, y, size):
        """ Инициализирует спрайт с изображением астеройда. """
        super(Asteroid, self).__init__(
            image=Asteroid.images[size],
            x=x, y=y,
            dx=random.choice([1, -1]) * Asteroid.SPEED * random.random() / size,
            dy=random.choice([1, -1]) * Asteroid.SPEED * random.random() / size)

        self.size = size

    def update(self):
        """ Заставляет астеройд обогнуть экран. """
        if self.top > games.screen.height:
            self.bottom = 0

        if self.bottom < 0:
            self.top = games.screen.height

        if self.left > games.screen.width:
            self.right = 0

        if self.right < 0:
            self.left = games.screen.width
Example #2
0
File: bots.py Project: LewB/GridBug
class GridObject(games.Sprite):
    ### A non-moving grid sprite ###
    TYPE = "XX"
    _SV_image = games.load_image("PyBugger/images/sv_grid.bmp")
    _SH_image = games.load_image("PyBugger/images/sh_grid.bmp")
      
    def __init__(self, x, y, imgtype):
        ityp = imgtype
        if ityp == "FH":
            image = self._SH_image
        elif ityp == "FV":
            image = self._SV_image
        else:
            ityp = "XX"
            image = None
        if image:
            super(GridObject, self).__init__(
                                    image = image,
                                    x = x, y = y,
                                    dx = 0, dy = 0)
            games.gscreen.add(self)
        self.TYPE = ityp
        self.tickable = 0
        
    def die(self):
        self.destroy()
Example #3
0
def buildBlocks():
	#Set the various block colors
	redB = games.load_image("topblock.jpg")
	blueB = games.load_image("midblock.jpg")
	greenB = games.load_image("lowblock.jpg")
	yelB = games.load_image("botblock.jpg")
	
	#set initial position
	topCor = 50
	
	#Build a 8x10 grid of blocks for the level
	for down in range(0,8):
		rowCount = 230
		if down < 1:
			imgBuffer = redB
		if down < 3 and down > 1:
			imgBuffer = blueB
		if down < 5 and down > 3:
			imgBuffer = greenB
		if down < 8 and down > 5:
			imgBuffer = yelB
		for across in range(0,10):
			placeBlk = Block(image = imgBuffer,
							x = rowCount,
							y = topCor)
			games.screen.add(placeBlk)
			rowCount += 20
		topCor += 10
Example #4
0
 def __init__(self, x, y, size):
     if size == 1:
         image = games.load_image("res/singleBuilding.png")
     elif size == 2:
         image = games.load_image("res/doubleBuilding.png")
     super(Building, self).__init__(image=image, x=x, y=y)
     self.setBounds(x, y, self.get_width(), self.get_height())
 def __init__(self, x, y, size):
     if size == 1:
         image = games.load_image("res/singleBuilding.png")
     elif size == 2:
         image = games.load_image("res/doubleBuilding.png")
     super(Building, self).__init__(image=image, x=x, y=y)
     self.setBounds(x, y, self.get_width(), self.get_height())
    def update(self):
	"""A method to update the tank"""
        self.nametag.value = self.name + " " + str(int(self.hp))
        if int(self.hp) < int(self.maxHp) / 2 and self.state == 0:
            self.image = games.load_image("res/" + self.name + "_body_damaged.png")
            self.turret.image = games.load_image("res/" + self.name + "_turret_damaged.png")
            self.state = 1
        self.square.x = self.x
        self.square.y = self.y - 80
Example #7
0
class Asteroid(Wrapper):
    """ Астеройд, прямолинейно движущийся по экрану. """
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    images = {
        SMALL: games.load_image(os.path.join(STATIC, 'cartman_small.jpg')),
        MEDIUM: games.load_image(os.path.join(STATIC, 'cartman_medium.jpg')),
        LARGE: games.load_image(os.path.join(STATIC, 'cartman_big.jpg'))
    }

    speed = 3
    # SPAWN - количество новых астеройдов, но которое распадается один взорванный
    SPAWN = 2
    POINTS = 30
    # total - общая численность астеройдов
    total = 0

    def __init__(self, game, x, y, size, speed=3):
        """ Инициализирует спрайт с изображением астеройда. """
        Asteroid.total += 1
        self.speed = speed
        super(Asteroid, self).__init__(image=Asteroid.images[size],
                                       x=x,
                                       y=y,
                                       dx=random.choice([1, -1]) *
                                       Asteroid.SPEED * random.random() / size,
                                       dy=random.choice([1, -1]) *
                                       Asteroid.SPEED * random.random() / size)

        self.game = game
        self.size = size

    def die(self):
        """ Разрушает астеройд. """
        Asteroid.total -= 1

        self.game.score.value += int(Asteroid.POINTS / self.size)
        self.game.score.right = games.screen.width - 10

        # если размеры астеройда крупные или средние, заменить его 2-мя более мелкими астеройдами
        if self.size != Asteroid.SMALL:
            for i in range(Asteroid.SPAWN):
                new_asteroid = Asteroid(game=self.game,
                                        x=self.x,
                                        y=self.y,
                                        size=self.size - 1)
                games.screen.add(new_asteroid)

        # если больше астеройдов не осталось, переходим на следующий уровень
        if Asteroid.total == 0:
            self.game.advance()

        super(Asteroid, self).die()
Example #8
0
 def update(self):
     """A method to update the tank"""
     self.nametag.value = self.name + " " + str(int(self.hp))
     if int(self.hp) < int(self.maxHp) / 2 and self.state == 0:
         self.image = games.load_image("res/" + self.name +
                                       "_body_damaged.png")
         self.turret.image = games.load_image("res/" + self.name +
                                              "_turret_damaged.png")
         self.state = 1
     self.square.x = self.x
     self.square.y = self.y - 80
Example #9
0
def main():
    nebula_image = games.load_image(os.path.join(STATIC, 'background.jpg'),
                                    transparent=False)
    games.screen.background = nebula_image

    ship_image = games.load_image(os.path.join(STATIC, 'mario.png'))
    the_ship = Ship(image=ship_image,
                    x=games.screen.width / 2,
                    y=games.screen.height / 2)
    games.screen.add(the_ship)

    games.screen.mainloop()
class Asteroid(Wrapper):
    """ An asteroid which floats across the screen. """
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    POINTS = 30
    total = 0
    Asteroid.total += 1
    images = {SMALL: games.load_image("asteroid_small.bmp"),
              MEDIUM: games.load_image("asteroid_med.bmp"),
              LARGE: games.load_image("asteroid_big.bmp") }
    SPEED = 2

    def __init__(self, x, y, size):
        """ Initialize asteroid sprite. """
        super(Asteroid, self).__init__(
            image = Asteroid.images[size],
            x = x, y = y,
            dx = random.choice([1, -1]) * Asteroid.SPEED * random.random()/size,
            dy = random.choice([1, -1]) * Asteroid.SPEED * radom.random()/size)
        self.size = size
        self.game = game

    def update(self):
        """ Wrap around screen. """
        if self.top > games.screen.height:
            self.bottom = 0

        if self.bottom < 0:
            self.top = games.screen.height

        if self.left > games.screen.height
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
        # check if missile overlaps any other object
        if self.overlapping_sprites:
            for sprite in self.overlapping_sprites:
                sprite.die()

    def main():
        # establish background
        nebula_image = games.load_image("nebula.jpg")
        games.screen.background = nebula_image

        # create 8 asteroids
        for i in range(8):
            x = random.randrange(games.screen.width)
            y = random.randrange(games.screen.height)
            size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE])
            new_asteroid = Asteroid(x = x, y = y, size = size)
            games.screen.add(new_asteroid)
Example #11
0
class Asteroid(games.Sprite):
    """ Астеройд, прямолинейно движущийся по экрану. """
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    images = {
        SMALL: games.load_image(os.path.join(STATIC, 'cartman_small.jpg')),
        MEDIUM: games.load_image(os.path.join(STATIC, 'cartman_medium.jpg')),
        LARGE: games.load_image(os.path.join(STATIC, 'cartman_big.jpg'))
    }

    SPEED = 2
    # SPAWN - количество новых астеройдов, но которое распадается один взорванный
    SPAWN = 2

    def __init__(self, x, y, size):
        """ Инициализирует спрайт с изображением астеройда. """
        super(Asteroid, self).__init__(image=Asteroid.images[size],
                                       x=x,
                                       y=y,
                                       dx=random.choice([1, -1]) *
                                       Asteroid.SPEED * random.random() / size,
                                       dy=random.choice([1, -1]) *
                                       Asteroid.SPEED * random.random() / size)

        self.size = size

    def update(self):
        """ Заставляет астеройд обогнуть экран. """
        if self.top > games.screen.height:
            self.bottom = 0

        if self.bottom < 0:
            self.top = games.screen.height

        if self.left > games.screen.width:
            self.right = 0

        if self.right < 0:
            self.left = games.screen.width

    def die(self):
        """ Разрушает астеройд. """
        # если размеры астеройда крупные или средние, заменить его 2-мя более мелкими астеройдами
        if self.size != Asteroid.SMALL:
            for i in range(Asteroid.SPAWN):
                new_asteroid = Asteroid(x=self.x, y=self.y, size=self.size - 1)
                games.screen.add(new_asteroid)
        self.destroy()
Example #12
0
class Ship(games.Sprite):
    """ The player's ship. """
    image = games.load_image("ship.bmp")
    VELOCITY_STEP = .03
    ROTATION_STEP = 3
    sound = games.load.sound("thrust.wav")
    # apply thrust based on up arrow key
    # Add SFX queue whenever key pressed
    if games.keyboard.is_pressed(games.K_UP):
        Ship.sound.play()
    # change velocity components based on ship's angle
    angle = self.angle * math.pi / 180 # convert to radians
    # sin and cos of velocity for angular movement
    self.dx += Ship.VELOCITY_STEP * math.sin(angle)
    self.dy += Ship.VELOCITY_STEP * -math.cos(angle)
    def update(self):
        """ Rotate based on keys pressed. """
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP
        # wrap the ship around screen
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
    # create the ship
    the_ship = Ship(image = Ship(image = Ship.image,
    x = games.screen.width/2
    y = games.screen.height/2)
    games.screen.add(the_ship))
Example #13
0
File: bots.py Project: LewB/GridBug
class SayObject(games.Sprite):
    # Speech Balloon
    TYPE = "SB"
    _say_img = games.load_image("PyBugger/images/Bubble.bmp")
    #_new_img = _say_img
    
    def __init__(self, value, x = 0, y = 0):
        
        self._text = SayText(value, 0, 0)
        txwidth = self._text.get_width()
        txheight = self._text.get_height()
        if txwidth % 10 == 0:
            txwidth += 1
        #print("Width: " + str(txwidth))
        self._new_img = games.pygame.transform.smoothscale(self._say_img, (txwidth+20, txheight+40))
        kcolor = self._new_img.get_at((0,0))
        self._new_img.set_colorkey((kcolor))
        
        cx = x + (txwidth / 2) - 10
        cy = y - 4
        super(SayObject, self).__init__(
                image = self._new_img,
                x = cx, y = cy,
                is_collideable=False)
        self._text.x = cx
        self._text.y = cy - 2
        self._tickable = 0
        
        games.gscreen.add(self)
        games.gscreen.add(self._text)
class Chef(games.Sprite):
    """ A chef which moves left and right, dropping pizzas. """
    image = games.load_image("chef.bmp")

    def __init__(self, y = 55, speed = 3, odds_change = 200):
        """ Initialize the Chef object. """
        super(Chef, self).__init__(image = Chef.image, x = games.screen.width / 2, y = y, dx = speed)
        self.odds_change = odds_change
        self.time_til_drop = 0

    def update(self):
        """ Determine if directions needs to be reversed. """
        if self.left < 0 or self.right > games.screen.width:
            self.dx = -self.dx
        elif random.randrange(self.odds_change) == 0:
            self.dx = -self.dx

        self.check_drop()

    def check_drop(self):
        """ Decrease countdown or drop pizza and reset countdown. """
        if self.time_til_drop > 0:
            self.time_til_drop -= 1
        else:
            new_pizza = Pizza(x = self.x)
            games.screen.add(new_pizza)

            # set buffer to approx 30% of pizza height, regardless of pizza speed.
            self.time_til_drop = int(new_pizza.height * 1.3 / Pizza.speed) + 1
Example #15
0
def main():
	"""Start the main game"""
	#Initialize player location, block placements and ball placement
	user = Player()
	games.screen.add(user)
	
	borderimage = games.load_image("sideborder.jpg")
	border1 = sideBorder(image = borderimage, 
						x = games.screen.width/4, 
						y = games.screen.height/2)
	border2 = sideBorder(image = borderimage,
						x = games.screen.width - games.screen.width/4, 
						y = games.screen.height/2)
	games.screen.add(border1)
	games.screen.add(border2)
	
	infoTxt = games.Text(value = "Controls", size = 30, color = color.white, top = 10, left =  10)
	infoTxt2 = games.Text(value = "A: Left", size = 10, color = color.white, top = 60, left = 10)
	infoTxt3 = games.Text(value = "S: Right", size = 10, color = color.white, top = 90, left = 10)
	infoTxt4 = games.Text(value = "SPACE: Launch Ball", size = 10, color = color.white, top = 120, left = 10)
	
	games.screen.add(infoTxt)
	games.screen.add(infoTxt2)
	games.screen.add(infoTxt3)
	games.screen.add(infoTxt4)

	buildBlocks()
	#continue till death
	games.screen.mainloop()
def mainGame(instance):
    """Called to run the client, requires data for the tank and the host/port"""

    #Open the screen
    #reload(games)
    #games.screen.quit()
    #quit()
    #games.init(1024, 768, 30)

    try:
        #reload(games)
        #This sets the initial conditions for the client
        username = instance[0]
        stats = instance[1]
        host = instance[2]
        port = instance[3]

        #Establish background
        back = games.load_image("res/background.png")
        games.screen.background = back

        #Set up the game controller and feed it the conditions
        fat_controller = GameController(stats, host, port, username, False)
        games.screen.add(fat_controller)

        #Start the game
        games.screen.mainloop()
    #Exceptions - can communicate with the login client
    except GameInProgressException as message:
        return message

    except HostDisconnectedException as message:
        return message
Example #17
0
    def __init__(self, x, y, angle, name, hp, username, turret, team,
                 clientteam):
        """ Initialize player sprite. """
        image = games.load_image("res/" + name + "_body.png")
        super(Player, self).__init__(image=image, x=x, y=y, angle=angle)
        self.name = name
        self.username = username
        self.team = team
        self.clientTeam = clientteam
        if self.team == self.clientTeam:
            self.square = superSquare(False, self.x, self.y - 80)
        else:
            self.square = superSquare(True, self.x, self.y - 80)

        self.hp = int(hp)
        self.userTag = games.Text(value=self.username,
                                  x=x,
                                  y=y - 90,
                                  color=colour.black,
                                  size=20)
        self.nametag = games.Text(value=name + " " + str(self.hp),
                                  x=x,
                                  y=y - 70,
                                  color=colour.black,
                                  size=20)
        games.screen.add(self.nametag)
        games.screen.add(self.square)
        games.screen.add(self.userTag)
        self.maxHp = hp
        self.state = 0
        self.turret = turret
Example #18
0
def mainGame(instance):
    """Called to run the client, requires data for the tank and the host/port"""

    #Open the screen
    #reload(games)
    #games.screen.quit()
    #quit()
    #games.init(1024, 768, 30)

    try:
        #reload(games)
        #This sets the initial conditions for the client
        username = instance[0]
        stats = instance[1]
        host = instance[2]
        port = instance[3]

        #Establish background
        back = games.load_image("res/background.png")
        games.screen.background = back

        #Set up the game controller and feed it the conditions
        fat_controller = GameController(stats, host, port, username, False)
        games.screen.add(fat_controller)

        #Start the game
        games.screen.mainloop()
    #Exceptions - can communicate with the login client
    except GameInProgressException as message:
        return message

    except HostDisconnectedException as message:
        return message
Example #19
0
class Bullet(games.Sprite):
    """A class to create a bullet"""
    image = games.load_image("res/Bullet_Sprite.png")

    def __init__(self, x, y, angle, ownerId, damage, bulletID, penetration):
        super(Bullet, self).__init__(image=Bullet.image, x=x, y=y, angle=angle)
        self.ownerId = ownerId
        self.damage = damage
        self.bulletID = bulletID
        self.ded = False
        self.penetration = penetration

    def getBulletVector(self):
        """Returns the ballistic vector for this bullet"""
        return Vector(self.x, self.y,
                      self.x + math.cos(math.radians(self.angle)) * 3,
                      self.y + math.sin(math.radians(self.angle)) * 3)

    def getx1x2(self):
        """Returns the endpoints of the vector"""
        return self.x, self.y, self.x + 5 * math.cos(math.radians(
            self.angle)), self.y + 5 * math.sin(math.radians(self.angle))

    def returnValues(self):
        """Returns the attributes of the bullet"""
        return [
            self.x, self.y, self.angle, self.ownerId, self.damage,
            self.bulletID, self.penetration
        ]

    def getVector(self):
        """Another method to get the ballistic vector"""
        x1, y1, x2, y2 = self.getx1x2()
        return Vector(x1, y1, x2, y2)
Example #20
0
class Asteroid(Wrapper):
    """ An asteroid which floats across the screen. """
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    SPEED = 2
    SPAWN = 2
    POINTS = 30

    total = 0
    images = {
        SMALL: games.load_image("asteroid_small.bmp"),
        MEDIUM: games.load_image("asteroid_med.bmp"),
        LARGE: games.load_image("asteroid_big.bmp")
    }

    def __init__(self, game, x, y, size):
        """ Initialize asteroid sprite. """
        super(Asteroid, self).__init__(image = Asteroid.images[size], x = x, y = y, \
            dx = random.choice([1, -1]) * Asteroid.SPEED * random.random() / size, \
            dy = random.choice([1, -1]) * Asteroid.SPEED * random.random() / size)
        self.size = size
        self.game = game
        Asteroid.total += 1

    def die(self):
        """ Destroy asteroid. """
        Asteroid.total -= 1
        self.game.score.value += int(Asteroid.POINTS / self.size)
        self.game.score.right = games.screen.width - 10

        # if asteroid isn't small, replace with two smaller asteroids
        if self.size != Asteroid.SMALL:
            for _ in range(Asteroid.SPAWN):
                new_asteroid = Asteroid(game=self.game,
                                        x=self.x,
                                        y=self.y,
                                        size=self.size - 1)
                games.screen.add(new_asteroid)

        # if all asteroids are gone, advance to next level.
        if Asteroid.total == 0:
            self.game.advance()

        super(Asteroid, self).die()
Example #21
0
class Ship(games.Sprite):
    """ Корабль игрока. """
    image = games.load_image(os.path.join(STATIC, 'mario.jpg'))
    # thrust.wav - звук ускоряющегося рывка
    sound = games.load_sound(os.path.join(STATIC, 'thrust.wav'))
    ROTATION_STEP = 3
    # VELOCITY_STEP - константа для описания изменения скорости корабля
    VELOCITY_STEP = .03
    # MISSILE_DELAY - количество обновлений экрана, в течение которых игрок не может выпустить ракету после очередного
    # запуска
    MISSILE_DELAY = 25

    def __init__(self, x, y):
        """ Инициализирует спрайт с изображением космического корабля. """
        super(Ship, self).__init__(image=Ship.image, x=x, y=y)
        # с помощью missile_wait будет отсчитываться задержка, упреждающая запуск очередной ракеты
        self.missile_wait = 0

    def update(self):
        """ Вращает корабль при нажатии клавиш со стрелками. """
        # вращает корабль при нажатии <- и ->
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP

        # корабль совершает рывок при нажатии стрелки вверх
        if games.keyboard.is_pressed(games.K_UP):
            Ship.sound.play()

            # изменение горизонтальной и вертикальной скорости корабля с учётом угла поворота
            angle = self.angle * math.pi / 180  # преобразование в радианы
            self.dx += Ship.VELOCITY_STEP * math.sin(angle)
            self.dy += Ship.VELOCITY_STEP * -math.cos(angle)

        # корабль будет 'огибать' экран
        if self.top > games.screen.height:
            self.bottom = 0

        if self.bottom < 0:
            self.top = games.screen.height

        if self.left > games.screen.width:
            self.right = 0

        if self.right < 0:
            self.left = games.screen.width

        # если запуск следующей ракеты пока ещё не разрешён, вычесть 1 из длины оставшегося интервала ожидания
        if self.missile_wait > 0:
            self.missile_wait -= 1

        # если нажат Space и интервал ожидания истёк, выпустить ракету
        if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0:
            new_missile = Missile(self.x, self.y, self.angle)
            games.screen.add(new_missile)
            self.missile_wait = Ship.MISSILE_DELAY
Example #22
0
class Ship(Collider):
    """ Корабль игрока. """
    image = games.load_image(os.path.join(STATIC, 'ship.bmp'))
    # thrust.wav - звук ускоряющегося рывка
    sound = games.load_sound(os.path.join(STATIC, 'thrust.wav'))
    ROTATION_STEP = 3
    # VELOCITY_STEP - константа для описания изменения скорости корабля
    VELOCITY_STEP = .03
    # VELOCITY_MAX - константа ограничивающая максимальную скорость корабля
    VELOCITY_MAX = 3
    # MISSILE_DELAY - количество обновлений экрана, в течение которых игрок не может выпустить ракету после очередного
    # запуска
    MISSILE_DELAY = 25

    def __init__(self, game, x, y):
        """ Инициализирует спрайт с изображением космического корабля. """
        super(Ship, self).__init__(image=Ship.image, x=x, y=y)
        self.game = game
        self.missile_wait = 0

    def update(self):
        """ Вращает, ускоряет и выпускает ракеты при нажатии клавиш. """
        super(Ship, self).update()

        # вращает корабль при нажатии <- и ->
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP

        # корабль совершает рывок при нажатии стрелки вверх
        if games.keyboard.is_pressed(games.K_UP):
            Ship.sound.play()
            # изменение горизонтальной и вертикальной скорости корабля с учётом угла поворота
            angle = self.angle * math.pi / 180  # преобразование в радианы
            self.dx += Ship.VELOCITY_STEP * math.sin(angle)
            self.dy += Ship.VELOCITY_STEP * -math.cos(angle)

            # ограничение горизонтальной и вертикальной скорости
            self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
            self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)

        # если запуск следующей ракеты пока ещё не разрешён, вычесть 1 из длины оставшегося интервала ожидания
        if self.missile_wait > 0:
            self.missile_wait -= 1

        # если нажат Space и интервал ожидания истёк, выпустить ракету
        if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait == 0:
            new_missile = Missile(self.x, self.y, self.angle)
            games.screen.add(new_missile)
            self.missile_wait = Ship.MISSILE_DELAY

    def die(self):
        """ Разрушает корабль и завершает игру. """
        self.game.end()
        super(Ship, self).die()
Example #23
0
class Asteroid(Wrapper):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3
    images = {SMALL: games.load_image(os.path.join(STATIC, 'asteroid_small.bmp')),
              MEDIUM: games.load_image(os.path.join(STATIC, 'asteroid_med.bmp')),
              LARGE: games.load_image(os.path.join(STATIC, 'asteroid_big.bmp'))}

    SPEED = 2
    SPAWN = 2
    POINTS = 30
    total = 0

    def __init__(self, game, x, y, size):
        Asteroid.total += 1

        super(Asteroid, self).__init__(
            image=Asteroid.images[size],
            x = x, y = y,
            dx = random.choice([1, -1]) * Asteroid.SPEED * random.random() / size,
            dy = random.choice([1, -1]) * Asteroid.SPEED * random.random() / size)

        self.game = game
        self.size = size

    def die(self):
        Asteroid.total -= 1

        self.game.score.value += int(Asteroid.POINTS / self.size)
        self.game.score.right = games.screen.width - 10

        if self.size != Asteroid.SMALL:
            for i in range(Asteroid.SPAWN):
                new_asteroid = Asteroid(game = self.game,
                                        x = self.x,
                                        y = self.y,
                                        size = self.size - 1)
                games.screen.add(new_asteroid)

        if Asteroid.total == 0:
            self.game.advance()

        super(Asteroid, self).die()
class Missile(Collider):
    """ A missile launched by the player's ship. """
    image = games.load_image("missile.bmp")
    sound = games.load_sound("missile.wav")
    BUFFER = 40
    VELOCITY_FACTOR = 7
    LIFETIME = 40
    MISSILE_DELAY = 25
    def __init__(self, ship_x, ship_y, ship_angle):
        """ Initialize the missile sprite. """
        Missile.sound.play()
        # convert to radians
        angle = ship_angle * math.pi / 180

        # calculate missile's starting position
        buffer_x = Missile.BUFFER * math.sin(angle)
        buffer_y = Missile.BUFFER * -math.cos(angle)
        x = ship_x + buffer_x
        y = ship_y + buffer_y

        # calculate missile's velocity components
        dx = Missile.VELOCITY_FACTOR * math.sin(angle)
        dy = Missile.VELOCITY_FACTOR * -math.cos(angle)

        # create the missile
        super(Missile, self).__init__(image = Missile.image,
        x = x, y = y, dx = dx, dy = dy)

        self.lifetime = Missile.LIFETIME

        def update(self):
            """ Move the missile. """
            # if lifetime is up, destroy the missile
            self.lifetime -= 1
            if self.lifetime == 0:
                self.destroy()
            # wrap the missile screen around
            if self.top > games.screen.height:
                self.bottom = 0
            if self.bottom < 0:
                self.top = games.screen.height
            if self.left > games.screen.width:
                self.right = 0
            if self.right < 0:
                self.left = games.screen.width
        def die(self):
            """ Destroy the missile. """
            self.destroy()
        # check if ship overlaps any other object
        if self.overlapping_sprites:
            if self.overlapping_sprites:
                for sprite in self.overlapping_sprites:
                    sprite.die()
                super(Asteroid, self).die()
                super(Missile, self).update()
Example #25
0
 def endGame(self, stats):
     """Close the server connection and return to the tank selection screen"""
     self.connection.close()
     #print "Connection to server closed"
     games.screen.clear()
     try:
         games.Screen.quit()
     except Exception:
         games.screen.quit()
     games.screen.background = games.load_image("res/notinprogress.png")
     raise EndOfGame(str(stats))
Example #26
0
class Ship(games.Sprite):
    """ Корабль игрока. """
    image = games.load_image(os.path.join(STATIC, 'ship.bmp'))
    ROTATION_STEP = 3

    def update(self):
        """ Вращает корабль при нажатии клавиш со стрелками. """
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP
    def endGame(self, stats):
	"""Close the server connection and return to the tank selection screen"""
        self.connection.close()
        #print "Connection to server closed"
        games.screen.clear()
        try:
            games.Screen.quit()
        except Exception:
            games.screen.quit()
        games.screen.background = games.load_image("res/notinprogress.png")
        raise EndOfGame(str(stats))
Example #28
0
 def update(self):
     image = games.load_image("Pizza.gif")
     if self.bottom > games.screen.height:
         gameovermessage = games.Message(value="GAME OVER",
                                         size=50,
                                         color=color.red,
                                         x=games.screen.width / 2,
                                         y=games.screen.height / 2,
                                         lifetime=5 * games.screen.fps,
                                         after_death=games.screen.quit)
         games.screen.quit()
     self.y += 3
Example #29
0
    def __init__(self):
        """ Cursor Initializer """
        super(Cursor,
              self).__init__(image=games.load_image("Sprites/cursor.png"),
                             x=games.mouse.x,
                             y=games.mouse.y)

        self.mouseClicked = False
        self.mouseCounter = 0

        # Load gunshot sound
        self.gunShotSound = games.load_sound("Sounds/shot.wav")
    def main():
        # establish background
        nebula_image = games.load_image("nebula.jpg")
        games.screen.background = nebula_image

        # create 8 asteroids
        for i in range(8):
            x = random.randrange(games.screen.width)
            y = random.randrange(games.screen.height)
            size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE])
            new_asteroid = Asteroid(x = x, y = y, size = size)
            games.screen.add(new_asteroid)
Example #31
0
class Missile(games.Sprite):
    """ Ракета, которую может выпустить космический корабль игрока. """
    image = games.load_image(os.path.join(STATIC, 'mario_missile.jpeg'))
    sound = games.load_sound(os.path.join(STATIC, 'missile.wav'))
    BUFFER = 40
    VELOCITY_FACTOR = 7
    LIFETIME = 40

    def __init__(self, ship_x, ship_y, ship_angle):
        """ Инициализация спрайта с изображением ракеты. """
        Missile.sound.play()

        # преобразование в радианы
        angle = ship_angle * math.pi / 180

        # вычисление начальной позиции ракеты
        buffer_x = Missile.BUFFER * math.sin(angle)
        buffer_y = Missile.BUFFER * -math.cos(angle)
        x = ship_x + buffer_x
        y = ship_y + buffer_y

        # вычисление горизонатльной и вертикальной скорости ракеты
        dx = Missile.VELOCITY_FACTOR * math.sin(angle)
        dy = Missile.VELOCITY_FACTOR * -math.cos(angle)

        # создание ракеты
        super(Missile, self).__init__(image=Missile.image,
                                      x=x,
                                      y=y,
                                      dx=dx,
                                      dy=dy)
        # атрибут lifetime ограничивает время странствия ракеты по космосу
        self.lifetime = Missile.LIFETIME

    def update(self):
        """ Перемещаем ракету. """
        # если lifetime ракеты истёк, то она уничтожается
        self.lifetime -= 1
        if self.lifetime == 0:
            self.destroy()

        # ракета будет огибать экран
        if self.top > games.screen.height:
            self.bottom = 0

        if self.bottom < 0:
            self.top = games.screen.height

        if self.left > games.screen.width:
            self.right = 0

        if self.right < 0:
            self.left = games.screen.width
Example #32
0
    def __init__(self):
        super(Game, self).__init__(image=Game.image, x=0, y=0)

        # Instructions Labels
        self.instructions = games.Text(
            value="Shoot as many ducks as possible in 1 minute!",
            size=35,
            x=320,
            y=100,
            color=color.white)
        self.instructions2 = games.Text(value="Press \"P\" To Pause",
                                        size=35,
                                        x=320,
                                        y=140,
                                        color=color.white)
        games.screen.add(self.instructions)
        games.screen.add(self.instructions2)

        # Paused Game Sprite
        self.paused = games.Sprite(
            image=games.load_image("Sprites/paused.png"),
            x=320,
            y=240,
            dx=0,
            dy=0)

        # Final Results Labels
        self.results = games.Text(value="",
                                  size=35,
                                  x=320,
                                  y=100,
                                  color=color.white)  # How many ducks were hit
        self.results2 = games.Text(value="",
                                   size=35,
                                   x=320,
                                   y=140,
                                   color=color.white)  # Accuracy

        # Counters to delay events
        self.spawnCounter = 0
        self.menuCounter = 0

        self.keyDelay = 0
        self.keyDelayStart = False

        self.playing = False  # Set to true after instructions go away

        # Create the timer for the game
        self.gameTimer = Clock()
        games.screen.add(self.gameTimer)
Example #33
0
def main():
    # назначаем фоновую картинку
    nebula_image = games.load_image(os.path.join(STATIC, 'background.jpg'))
    games.screen.background = nebula_image

    # создаём 8 астеройдов
    for i in range(8):
        x = random.randrange(games.screen.width)
        y = random.randrange(games.screen.height)
        size = random.choice([Asteroid.SMALL, Asteroid.MEDIUM, Asteroid.LARGE])
        new_asteroid = Asteroid(x=x, y=y, size=size)
        games.screen.add(new_asteroid)

    games.screen.mainloop()
Example #34
0
    def play(self):
        # begin theme music
        games.music.load("theme.mid")
        games.music.play(-1)

        # load and set background
        bg_image = games.load_image("nebula.jpg")
        games.screen.background = bg_image

        # advance to the next level
        self.advance()

        # start the game
        games.screen.mainloop()
Example #35
0
def main():
    # Setup background
    games.screen.background = games.load_image("background.png",
                                               transparent=False)

    game = Game()
    crosshair = Cursor()

    games.screen.add(game)
    games.screen.add(crosshair)

    games.mouse.is_visible = False

    games.screen.mainloop()
class Ship(Wrapper):
    """ The player's ship. """
    image = games.load_image("ship.bmp")
    VELOCITY_STEP = .03
    ROTATION_STEP = 3
    sound = games.load.sound("thrust.wav")
    # apply thrust based on up arrow key
    # Add SFX queue whenever key pressed
    if games.keyboard.is_pressed(games.K_UP):
        Ship.sound.play()
    # change velocity components based on ship's angle
    angle = self.angle * math.pi / 180 # convert to radians
    # sin and cos of velocity for angular movement
    self.dx += Ship.VELOCITY_STEP * math.sin(angle)
    self.dy += Ship.VELOCITY_STEP * -math.cos(angle)
    # cap velocity in each direction
    self.dx = min(max(self.dx, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
    self.dy = min(max(self.dy, -Ship.VELOCITY_MAX), Ship.VELOCITY_MAX)
    # create the ship
    the_ship = Ship(image = Ship(image = Ship.image,
    x = games.screen.width/2
    y = games.screen.height/2)
    games.screen.add(the_ship))
    def __init__(self, x, y):
        """ Initialize ship sprite. """
        super(Ship, self).__init__(image = Ship.image, x = x, y = y)
        self.missile_wait = 0
    def update(self):
        """ Rotate based on keys pressed. """
        if games.keyboard.is_pressed(games.K_LEFT):
            self.angle -= Ship.ROTATION_STEP
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.angle += Ship.ROTATION_STEP
        # wrap the ship around screen
        if self.top > games.screen.height:
            self.bottom = 0
        if self.bottom < 0:
            self.top = games.screen.height
        if self.left > games.screen.width:
            self.right = 0
        if self.right < 0:
            self.left = games.screen.width
        # if waiting until the ship can fire next, decrease wait
        if self.missile_wait > 0:
            self.missile_wait -= 1
        # fire missile if spacebar pressed and missile wait is over
        if games.keyboard.is_pressed(games.K_SPACE) and self.missile_wait = 0:
            new_missile = Missile(self.x, self.y, self.angle)
            games.screen.add(new_missile)
            self.missile_wait = Ship.MISSILE_DELAY
Example #37
0
File: bots.py Project: LewB/GridBug
 def __init__(self):
     ### Initialize Game object. ###
     # load and set background
     
     #bg = games.gscreen.get_background()
     #bg.fill(color.yellow, None, 0)
     #bg.convert()
     bg = games.load_image("PyBugger/images/BackGrid.jpg", transparent=False)
     games.gscreen.background = bg
     self.disp = games.gscreen._display
     games.pygame.display.set_caption("Foxcroft Python Game Window")
     ht = games.gscreen.height
     wd = games.gscreen.width
     self.fg = games.pygame.Surface((ht,wd))
     surfcolor = self.fg.get_at((0,0))
     self.fg.set_colorkey(surfcolor)
     self.auto_run = False
     self.running = True
     self.tip = None
     self.msg = []
 def __init__(self, x, y, angle, turret, speed, hull_traverse, hp, reload, armour, name, id, damage, penetration,
              username, team):
     image = games.load_image("res/" + str(name) + "_body.png")
     super(LocalPlayer, self).__init__(image=image, x=x, y=y, angle=angle)
     self.name = name
     self.team = team
     self.turret = turret
     self.penetration = penetration
     self.bullets = []
     self.newBullets = None
     self.username = username
     self.reload = reload
     self.damage = damage
     self.id = id
     self.va = []
     self.fire = games.load_sound("res/Sounds/ms-1-45mm.ogg")
     self.idle = games.load_sound("res/Sounds/idle.ogg")
     self.moving = games.load_sound("res/Sounds/moving.ogg")
     self.canMove = False
     self.turret.canMove = False
     self.speed = speed
     self.hull_traverse = hull_traverse
     self.hp = int(hp)
     self.maxHp = self.hp
     self.reload_counter = self.reload
     self.armour = armour
     self.userTag = games.Text(value=self.username, x=x, y=y - 90, color=colour.black, size=20)
     self.nametag = games.Text(value=str(self.name) + " " + str(self.hp),
                               x=x,
                               y=y - 70,
                               color=colour.black,
                               size=20)
     self.reloadText = games.Text(value="Reload in: " + str(self.reload_counter), left=10, top=10, color=colour.red,
                                  size=30)
     self.orig_height = self.height - 30
     self.orig_width = self.width
     games.screen.add(self.userTag)
     games.screen.add(self.reloadText)
     games.screen.add(self.nametag)
    def __init__(self, x, y, angle, name, hp, username, turret, team, clientteam):
        """ Initialize player sprite. """
        image = games.load_image("res/" + name + "_body.png")
        super(Player, self).__init__(image=image, x=x, y=y, angle=angle)
        self.name = name
        self.username = username
        self.team = team
        self.clientTeam = clientteam
        if self.team == self.clientTeam:
            self.square = superSquare(False, self.x, self.y - 80)
        else:
            self.square = superSquare(True, self.x, self.y - 80)

        self.hp = int(hp)
        self.userTag = games.Text(value=self.username, x=x, y=y - 90, color=colour.black, size=20)
        self.nametag = games.Text(value=name + " " + str(self.hp), x=x, y=y - 70, color=colour.black, size=20)
        games.screen.add(self.nametag)
        games.screen.add(self.square)
        games.screen.add(self.userTag)
        self.maxHp = hp
        self.state = 0
        self.turret = turret
Example #40
0
from pygame import *
import __init__, color, games
games.init(screen_width=1000, screen_height=700, fps=50)
image=games.load_image("pic.jpg")
image2=games.Sprite(image=image, x=games.screen.width/2, y=games.screen.height/2)
games.screen.add(image2)
games.screen.mainloop()
    def update(self):
	"""Checks for user input and updates the client"""
        #Check for keyboard input
        if self.canMove:
            self.last_x = self.x
            self.last_y = self.y
            self.turret.last_x = self.turret.x
            self.turret.last_y = self.turret.y
            self.last_a = self.angle
            if games.keyboard.is_pressed(games.K_w):
                self.x += self.speed * math.cos(math.radians(self.angle))
                self.y += self.speed * math.sin(math.radians(self.angle))
                self.turret.x += self.speed * math.cos(math.radians(self.angle))
                self.turret.y += self.speed * math.sin(math.radians(self.angle))
                try:
                    self.idle.stop()
                except Exception:
                    pass
                    #self.moving.play(loops=-1)

            elif games.keyboard.is_pressed(games.K_s):
                self.x -= self.speed * math.cos(math.radians(self.angle))
                self.y -= self.speed * math.sin(math.radians(self.angle))
                self.turret.x -= self.speed * math.cos(math.radians(self.angle))
                self.turret.y -= self.speed * math.sin(math.radians(self.angle))
                self.idle.stop()
                #self.moving.play(loops=-1)
            else:
                try:
                    self.moving.stop()
                except Exception:
                    pass
                    #self.idle.play(loops=-1)

            if games.keyboard.is_pressed(games.K_a):
                self.angle -= self.hull_traverse
                self.turret.angle -= self.hull_traverse

            if games.keyboard.is_pressed(games.K_d):
                self.angle += self.hull_traverse
                self.turret.angle += self.hull_traverse

            if games.keyboard.is_pressed(games.K_SPACE):
                if self.reload_counter == 0:
                    self.newBullets = Bullet(self.x + self.getBulletOffsetX(), self.y + self.getBulletOffsetY(),
                                             self.turret.angle, self.id, self.damage, -1, self.penetration)
                    self.reload_counter = self.reload
                    self.fire.play()
            self.reload_counter = int(self.reload_counter)
            if self.reload_counter > 0:
                #print "RELOAD: "+str(self.reload_counter)
                self.reload_counter -= 1
                self.reloadText.set_value("Reload in: " + str(self.reload_counter))

            if self.reload_counter == 0:
                self.reloadText.set_value("Ready to fire!")
                self.reloadText.set_color(colour.black)
            else:
                self.reloadText.set_color(colour.red)

        self.nametag.x = self.x
        self.nametag.y = self.y - 70
        self.nametag.value = self.name + " " + str(int(self.hp))
        self.userTag.x = self.x
        self.userTag.y = self.y - 90
        if self.hp < self.maxHp / 2:
            self.image = games.load_image("res/" + self.name + "_body_damaged.png")
            self.turret.image = games.load_image("res/" + self.name + "_turret_damaged.png")
        if self.hp <= 0:
            self.hp = 0
            self.canMove = False
            self.turret.canMove = False
 def __init__(self, enemy, x, y):
     if enemy:
         image = games.load_image("res/Enemy.png")
     else:
         image = games.load_image("res/Friendly.png")
     super(superSquare, self).__init__(image=image, x=x, y=y)
 def __init__(self, x, y, angle, turret_traverse, name):
     image = games.load_image("res/" + name + "_turret.png")
     super(LocalTurret, self).__init__(image=image, x=x, y=y, angle=angle)
     self.name = name
     self.canMove = False
     self.turret_traverse = turret_traverse
    def setupGame(self,stats, host, port, username):
	"""A method to load in all resources and set the game in motion"""
        #Create a connection
        self.connection = netComms.networkComms(host, int(port))
        self.stats = stats
        self.username = username
        #Open resources
        self.fire = games.load_sound("res/Sounds/ms-1-45mm.ogg")
        self.idle = games.load_sound("res/Sounds/marder-idle.ogg")
        self.moskau = games.load_sound("res/Sounds/Moskau.ogg")
        self.moving = games.load_sound("res/Sounds/marder-moving.ogg")
        self.loadingSongs = [games.load_sound("res/Sounds/WoT-Opening-1.ogg"),
                             games.load_sound("res/Sounds/WoT-Opening-2.ogg"),
                             games.load_sound("res/Sounds/WoT-Opening-3.ogg")]
        self.battleSongs = [games.load_sound("res/Sounds/WoT-Battle-1.ogg"),
                            games.load_sound("res/Sounds/WoT-Battle-2.ogg"),
                            games.load_sound("res/Sounds/WoT-Battle-3.ogg"),
                            games.load_sound("res/Sounds/WoT-Battle-4.ogg"),
                            games.load_sound("res/Sounds/WoT-Battle-5.ogg")]

        self.despawnToServer = []
        self.damageDone = []
        name = self.stats[0]
        hp = self.stats[1]
        damage = self.stats[2]
        penetration = self.stats[3]
        reload = self.stats[4]
        armour = self.stats[5]
        hull_traverse = self.stats[6]
        turret_trav = self.stats[7]
        speed = self.stats[8]
        self.bg = games.load_image("background.png")
        self.update_ticks = 100
        self.bulletType = Bullet(0, 0, 0, 0, 0, 0, 0)

        #Create local instances of player and turret
        #First we have to handshake

        self.connection.send(["handshake", name, hp, self.username])

        #This will return us the currently connected players and our ID
        #print "RECV: "+str(self.connection.recieved)

        self.id = self.connection.recieved[0]

        if int(self.id) % 2 == 0:
            self.team = 0
        else:
            self.team = 1

        self.serverPlayers = self.connection.recieved[1]

        #Start countdown to the game
        self.countdown = self.connection.recieved[2]

        #Add a timer
        self.timerTop = games.Text(value="Game will start in:", x=400, y=300, size=50, color=colour.white)
        self.timerMain = games.Text(value=str(self.countdown), x=400, y=400, size=50, color=colour.white)

        if self.countdown == 0:
            self.close()
            #Set the map
        self.map = self.connection.recieved[3]
        self.drawMap(self.map)


        #Create these players, excluding us, as our movement is handled locally
        #Add us
        #We will get the data in the form [x,y,angle,turret angle]
        self.clientTurret = LocalTurret(self.serverPlayers[self.id][0], self.serverPlayers[self.id][1],
                                        self.serverPlayers[self.id][3], turret_trav, name)
        self.client = LocalPlayer(self.serverPlayers[self.id][0], self.serverPlayers[self.id][1],
                                  self.serverPlayers[self.id][2], self.clientTurret, speed,
                                  hull_traverse, hp, reload, armour, name, self.id, damage, penetration, self.username,
                                  self.team)

        #Start the countdown
        self.countdownThread = Thread(target=self.countingDown)
        self.countdownThread.start()

        #Add us to the screen
        games.screen.add(self.client)
        games.screen.add(self.clientTurret)
        games.screen.add(self.timerTop)
        games.screen.add(self.timerMain)
        #We have handled us, remove us from the list
        self.serverPlayers.pop(self.id)
        #Create some variables to hold the players
        self.serverInstances = []
        self.serverInstancesTurret = []
        self.bullets = []
        self.toDespawn = []
        self.toRebound = []
        #Add everyone
        for p in self.serverPlayers:
            #Add a new turret instance
            self.serverInstancesTurret.append(Turret(p[0], p[1], p[3], p[4]))
            #Add a new player instance
            self.serverInstances.append(
                Player(p[0], p[1], p[2], p[4], p[5], p[6], self.serverInstancesTurret[-1], p[7], self.client.team))
            #add them
            games.screen.add(self.serverInstances[-1])
            games.screen.add(self.serverInstancesTurret[-1])
 def __init__(self, x, y, angle, name):
     image = games.load_image("res/" + name + "_turret.png")
     super(Turret, self).__init__(image=image, x=x, y=y, angle=angle)
     self.name = name