示例#1
0
文件: game.py 项目: tandemdude/pong
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("My Pong Game")
        self.screen = pygame.display.set_mode((800, 600))
        self.running = True
        self.clock = pygame.time.Clock()
        self.walls = [Wall((10, 10), 780, 10),
                      Wall((10, 580), 780,
                           10)]  # Position and dimensions of walls
        self.background = pygame.Surface((800, 600))
        self.background.fill(pygame.Color("#000000"))
        self.ball = Ball((400, 300))
        self.font = pygame.font.Font(None, 50)

        control_scheme_1 = ControlScheme()
        control_scheme_1.up = pygame.K_w
        control_scheme_1.down = pygame.K_s

        control_scheme_2 = ControlScheme()
        control_scheme_2.up = pygame.K_UP
        control_scheme_2.down = pygame.K_DOWN

        self.bats = [
            Bat((10, 200), 10, 100, control_scheme_1),
            Bat((780, 200), 10, 100, control_scheme_2)
        ]  # Position and dimensions of paddles, their respective control schemes
        self.score = Score(self.font)
示例#2
0
def create_bat(ai_settings, screen, bats, bat_number, row_number):
    bat = Bat(ai_settings, screen)
    bat_width = bat.rect.width
    bat.x = bat_width + 2 * bat_width * bat_number
    bat.rect.x = bat.x
    bat.rect.y = bat.rect.height + 2 * bat.rect.height * row_number
    bats.add(bat)
示例#3
0
def run(pca, function, lb, ub, generations):
    alpha_gamma = 0.95
    algorithm = Bat(
        # Dimension
        100,
        # Population
        100,
        # Generations
        generations,
        # Loudness
        0.9,
        # Pulse rate
        0.9,
        # Min. Freq.
        0.0,
        # Max. Freq.
        5.0,
        # Lower bound
        lb,
        # Upper bound
        ub,
        function,
        alpha=0.99,
        gamma=0.9,
        use_pca=pca,
        levy=True)
    return_dict = algorithm.run_bats()
    print(
        f"Best: {return_dict['best']}, values: {return_dict['final_fitness']}")
    return return_dict
示例#4
0
def update(*scripts):
    """update scripts"""
    if len(scripts) >= 1:
        for index in xrange(0, len(scripts)):
            bat = Bat(scripts[index])
            bat.update()
    else:
        console('Please use `vimpyre update <script-name>` and try again!')
示例#5
0
def install(*scripts):
    """install scripts"""
    if len(scripts) >= 1:
        for index in xrange(0, len(scripts)):
            bat = Bat(scripts[index])
            bat.install()
    else:
        console('Please use `vimpyre install <script-name>` and try again!')
示例#6
0
def browse(*scripts):
    """browse script's homepage in your web browser"""
    if len(scripts) >= 1:
        for index in xrange(0, len(scripts)):
            bat = Bat(scripts[index])
            bat.open_homepage()
    else:
        console('Please use `vimpyre browse <script-name>` and try again!')
示例#7
0
def create_fleet(ai_settings, screen, ship, bats):
    bat = Bat(ai_settings, screen)
    number_bats_x = get_numbers_bats_x(ai_settings, bat.rect.width)
    number_rows = get_numbers_rows(ai_settings, ship.rect.height,
                                   bat.rect.height)

    for row_number in range(number_rows):
        for bat_number in range(number_bats_x):
            create_bat(ai_settings, screen, bats, bat_number, row_number)
示例#8
0
 def spawn_enemy(self):
     map_width = self.map.get_width_map()
     map_height = self.map.get_height_map()
     y_poz = randint(1, map_height - 2)
     x_poz = randint(1, map_width - 2)
     if self.map.is_valid_position(x_poz, y_poz):
         enemy = Bat(x_poz * config.TILESIZE, y_poz * config.TILESIZE)
         self.enemy.append(enemy)
         self.objects.append(enemy)
示例#9
0
def search(*scripts):
    """search script"""
    if len(scripts) > 1:
        console('Please search one script name!')
        sys.exit(1)

    bat = Bat(scripts[0])
    rets = bat.search()

    console('=> => Send bats to search vim-scripts ...')
    if rets:
        for item in rets:
            if path.isdir(path.join(VIM_PATH, 'vimpyre', item['name'])):
                console('\033[1m%s\033[m => %s \033[1m[installed]\033[m' %
                        (item['name'].encode('utf-8'),
                         item['description'].encode('utf-8')))
            else:
                console('\033[1m%s\033[m => %s' %
                        (item['name'].encode('utf-8'),
                         item['description'].encode('utf-8')))
    else:
        console('No such vim-scripts!')
示例#10
0
def init():
    bat = Bat()
    bat.install_base()
示例#11
0
def update_all():
    bat = Bat()
    bat.update_all()
 def fight():
   fight = True
   #PROBABLY CHANGE
   opponent = PaintbrushTown.challenger()
   if opponent == 'Rocky':
     enemy = 'bat'
   elif opponent == 'Slander':
     enemy = 'rat'
   elif opponent == 'Kyle':
     enemy = 'caterpillar'
   print(opponent,'chooses', enemy,'\b!')
   if(enemy == 'bat'):
     combatant = Bat()
     Bat.work()
   elif(enemy == 'caterpillar'):
     combatant = Caterpillar()
     Caterpillar.work()
   elif(enemy == 'rat'):
     combatant = Rat()
     Rat.work()
   time.sleep(1)
   while(True):
     start,attack, = '0','0'
     while start != 'k' and start != 'b' and start != 'm':
       start = input('Which bokémon would you like to start with?\n[k = Kennen, b = Belldolpine, m = Meister Beast]\n').lower()
     while(fight == True):
       #PLAYER TURN
       if start == 'k':
         print('You have chosen Kennen!')
         you = 'Kennen'
         pc = Kennen()
       elif start == 'b':
         print('You have chosen Belldolpine!')
         you = 'Belldolpine'
         pc = Belldolpine()
       elif start == 'm':
         print('You have chosen Meister Beast!')
         you = 'MeisterBeast'
         pc = MeisterBeast()
       while attack != 'b' and attack != 's':
         attack = input('Would you like to use your basic attack [b] or your special attack [s]\n')
         if attack == 'b':
           print(you,'does', pc.basicDamage, 'damage to the', enemy)
           combatant.takeDamage(pc.basicDamage)
           attack = '0'
           break
         if attack == 's':
           print(you, 'does', pc.specialDamage, 'damage to the', enemy)
           combatant.takeDamage(pc.specialDamage)
           attack = '0'
           break 
       #ENEMY TURN
       if(combatant.hp > 0):
         time.sleep(1)
         print('The', enemy, 'attacks!')
         combatant.basicAttack()
         print('The', enemy, 'does', combatant.basicAttack(), 'damage to you!')
         pc.takeDamage(combatant.damage)
       else:
         time.sleep(1)
         print('The', enemy, 'is knocked unconscious!\nYou have won!\n',opponent,'congradulates you and hands you a badge.')
         time.sleep(1)
         print('You should take the badge back to Professor Cottonwood so you can go find your parents.')
         time.sleep(5)
         pc.heal()
         fight = False
     break
示例#13
0
def play():
    global game_over
    #initialize pygame & window
    screen = pygame.display.get_surface()
    
   
    #fill background
    bg = pygame.Surface((screen.get_size()))
    bg.fill(BG)
    bg = bg.convert()
    screen.blit(bg, (0, 0))
    
    #initialize scoreboard
    score_board = Score(bg)
    score_board.game_over = game_over_screen
    score_board.win = win_screen
   
    #initialize the wall (bricks)
    wall, wall_g = init_wall(score_board)
    
    #initialize the bat
    bat = Bat(10)
    batsprite = pygame.sprite.RenderPlain(bat)
    
    #initialize the ball
    ball = Ball((255, 255, 255), 5, bat, wall, score_board)
    ballsprite = pygame.sprite.RenderPlain(ball)
    
    clock = pygame.time.Clock()
    pause = False 
    game.init()

    t1 = threading.Thread(target=tutorial, args=())
    t1.start()

    out_count = 0

    while True:
        
        while pause == True:
            clock.tick(60)
            pygame.mouse.set_visible(True)
            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        bat.movepos = [0,0]
                        pause = False
                        game.resume()
                        game.notify("Game Resumed")
                              
                elif event.type == QUIT:
                    sys.exit(0)
                else:
                    game.handle_pause_event(event)
                    
        while game_over == True:
            clock.tick(60)
            pygame.mouse.set_visible(True)
            game.game_over_screen()
            pygame.display.flip()
            for event in pygame.event.get():                              
                if event.type == QUIT:
                    sys.exit(0) 
                else:
                    game.handle_event(event)
                    
        while win == True:
            clock.tick(60)
            pygame.mouse.set_visible(True)
            game.win_screen()
            pygame.display.flip()
            for event in pygame.event.get():                              
                if event.type == QUIT:
                    sys.exit(0) 
                else:
                    game.handle_win_event(event)
                
        #handle events
        while pause == False and game_over == False and win == False:
            clock.tick(60) #max frame rate
            
            for event in pygame.event.get():
                if event.type == QUIT:
                    sys.exit(0)
                
                if event.type == KEYDOWN:
                    if event.key == K_LEFT:
                        bat.moveleft()
                    elif event.key == K_RIGHT:
                        bat.moveright()   
                    elif event.key == K_SPACE:
                        screen.blit(bg, ball.rect, ball.rect)
                        ball.shoot()
                    elif event.key == K_ESCAPE:
                        pause = True 
                        game.pause()
                        
                elif event.type == KEYUP:
                    if event.key == K_LEFT or event.key == K_RIGHT:
                        bat.movepos = [0, 0]
                elif event.type == MOUSEMOTION:
                
                    pygame.mouse.set_visible(False)
                    
                    x, y = pygame.mouse.get_pos()
                    bx, by = bat.rect.midtop
                    if x > screen.get_width()-(bat.width/2):
                        x = screen.get_width()-(bat.width/2)
                        
                    elif x < bat.width/2:
                        x = bat.width/2
                        
                    screen.blit(bg, bat.rect, bat.rect)
                    bat.rect.midtop = (x,by)
            
            if not screen.get_rect().contains(ball.rect):
                out_count += 1
                if out_count >= 10:
                    score_board.die()  
            else:
                out_count = 0        
                      
            cols, side = break_wall(ballsprite, wall_g)
            
            if cols:
                if side is 'left' or side is 'right':
                    ball.deflect(1.5)
                if side is 'top' or side is 'bottom':
                    ball.deflect(2.5) 
                elif side == 'topright' or side == 'topleft':
                    ball.deflect(1)
                elif side == 'bottomright' or side == 'bottomleft':
                    ball.deflect(1)    
                else:
                    ball.deflect(1)
                for i in range(len(cols)):
                    cols[i].destroy()
                    
            side = coll_side(ball.area.get_rect(), ball.rect, True, True)
            if side == 'top':
                score_board.die()
        
            if score_board.updated_level != 0:
                print 'speed increased'
                ball.increment_speed = 3
            if pause == False:        
            	for y in range(5):
                    for i in range(30):
                        if wall[y][i].destroyed == False:
                            screen.blit(bg, wall[y][i].rect, wall[y][i].rect)
                            #wall[y][i].destroy()
                        
                        
                score_board.update()
                
                screen.blit(bg, bat.rect, bat.rect)
                screen.blit(bg, ball.rect, ball.rect)
                ballsprite.update()
                batsprite.update()
                ballsprite.draw(screen)
                batsprite.draw(screen)
                wall_g.draw(screen)
                
            pygame.display.update()
示例#14
0
# Screen object
s = Screen()
create_screen(s)
s.tracer(0)  # Turn off animation

# Net object
n = Turtle()
draw_net(n)

# Create Score objects
player_score = Score((-200, C.HALF_HEIGHT - 100))
ai_score = Score((200, C.HALF_HEIGHT - 100))

# Create bats
player_bat = Bat((-C.HALF_WIDTH + 40, randint(-C.HALF_HEIGHT, C.HALF_HEIGHT)))
ai_bat = Bat((C.HALF_WIDTH - 40, randint(-C.HALF_HEIGHT, C.HALF_HEIGHT)))

# Create Ball object
ball = Ball()

# Listen for screen events
s.listen()

# Screen Events
# The functions player_bat.move_up and player_bat.move_down are not actually called here.
# They are passed to the event handler mainloop() when the "key" is pressed
s.onkey(player_bat_up, "Up")
s.onkey(player_bat_down, "Down")

# MAIN GAME LOOP
示例#15
0
from turtle import Turtle, Screen
import time
from bat import Bat
from ball import Ball
from scoreboard import Score
import random
screen = Screen()
screen.setup(width=1200, height=800)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)
game_is_on = True
bat1 = Bat(0)
bat2 = Bat(1)
ball = Ball()
score_right = Score("right")
score_left = Score("left")
screen.listen()
screen.onkeypress(bat1.up, "w")
screen.onkeypress(bat1.down, "s")
screen.onkeypress(bat2.up, "Up")
screen.onkeypress(bat2.down, "Down")
rally = 0
goal_right = 0
goal_left = 0
while game_is_on:
    goal = False

    screen.update()
    time.sleep(0.02)
    ball.move()
示例#16
0
def get_sample_bat_sections():
    return {0:Bat(SAMPLE_BAT)}
示例#17
0
def remove_all():
    bat = Bat()
    bat.remove_all()
示例#18
0
SCREENWIDTH = 400
SCREENHEIGHT = 400

background = pygame.image.load("The_Cave_artwork.jpg")

speed = 25
# Open a new window
# The window is defined as (width, height), measured in pixels
size = (SCREENWIDTH, SCREENHEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("My Animation")
screen.blit(background, (0, 0))

all_sprites_list = pygame.sprite.Group()

Bat1 = Bat(GREY, 20, 30)
Bat1.rect.x = 200
Bat1.rect.y = 300

Bat2 = Bat(GREY, 20, 30)
Bat2.rect.x = 100
Bat2.rect.y = 300

all_sprites_list.add(Bat1)
all_sprites_list.add(Bat2)

all_bats = pygame.sprite.Group()
all_bats.add(Bat1)
all_bats.add(Bat2)

# This loop will continue until the user exits the game
示例#19
0
def main():
    pygame.init()
    pygame.display.set_caption('Interference')
    pygame.key.set_repeat(10, 10)  # keypresses to auto-repeat every 10msec
    rects = []  # create a list

    screen = pygame.display.set_mode((screenwidth, screenheight))
    background = Background("assets/level1-stage.gif", [0, 0])
    bgsurface = pygame.Surface(screen.get_size())
    bgsurface = bgsurface.convert()  # speeds up blitting
    bgsurface.fill([0, 0, 255])  # set background to blue
    # if we only use a portion of the background image, change the first two values here:
    bgsurface.blit(
        background.image.subsurface(0, 0, screenwidth, screenheight), (0, 0))
    screen.blit(bgsurface, (0, 0))  # get the bgsurface onto the screen surface
    pygame.display.update()  # update the entire display

    # instantiate the sprites
    ball_sprite = Ball()
    bat_sprite = Bat()

    # store all sprite rects we create into this list
    rects.append(ball_sprite.getrect())
    rects.append(bat_sprite.getrect())

    balls_group = pygame.sprite.Group(ball_sprite)
    characters_group = pygame.sprite.Group(bat_sprite)

    while True:  # this is a forever loop
        ev = pygame.event.poll()
        if ev.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)

        batmoved = 0
        if ev.type == KEYDOWN:  # button pressed?
            if (ev.key == btn_left):
                batloc = [-1, 0]
                bat_sprite.movepos(batloc)
                ball_sprite.accel(-1)  # influence ball speed if needed
                batmoved = -1
            elif (ev.key == btn_right):
                batloc = [1, 0]
                bat_sprite.movepos(batloc)
                ball_sprite.accel(1)  # influence ball speed if needed
                batmoved = 1

        # check for collisions
        collide = pygame.sprite.collide_rect(bat_sprite, ball_sprite)
        if collide:
            ball_sprite.collision(bat_sprite.getrect(), batmoved)

        # clear the sprite(s) and then update and redraw them
        characters_group.clear(screen, bgsurface)
        balls_group.clear(screen, bgsurface)
        characters_group.update()
        balls_group.update()
        characters_group.draw(screen)
        balls_group.draw(screen)

        pygame.display.update(rects)
示例#20
0
def list_installed():
    bat = Bat()
    bat.list_installed()
示例#21
0
    def __init__(self, can_fly=True):
        self.fly = can_fly

    # This class also has a say method
    def say(self, msg):
        msg = '... ... ...'
        return msg

    # And its own method as well
    def sonar(self):
        return '))) ... ((('


if __name__ == '__main__':
    b = Bat()
    print(b.say('hello'))
    print(b.fly)

# And yet another class definition that inherits from Superhero and Bat
# superhero.py
from superhero import Superhero
from bat import Bat


# Define Batman as a child that inherits from both Superhero and Bat
class Batman(Superhero, Bat):
    def __init__(self, *args, **kwargs):
        # Typically to inherit attributes you have to call super:
        # super(Batman, self).__init__(*args, **kwargs)
        # However we are dealing with multiple inheritance here, and super()
示例#22
0
    def __init__(
        self, roomnumber, floorNumber
    ):  #FIXME: les couleurs dans design niveaux ne sont pas homogenes.
        self.floorNumber = floorNumber
        if floorNumber == 1:  #python doesn't have switch statements smh
            floordesignPath = 'design niveaux/lvl1.png'
        elif floorNumber == 2:
            floordesignPath = 'design niveaux/lvl2.png'
        elif floorNumber == 3:
            floordesignPath = 'design niveaux/lvl3.png'
        elif floorNumber == 4:
            floordesignPath = 'design niveaux/lvl4.png'
        elif floorNumber == 5:
            floordesignPath = 'design niveaux/lvl5.png'
        elif floorNumber == 6:
            floordesignPath = 'design niveaux/salle du boss.png'

        floordesign = pygame.image.load(floordesignPath)
        self.roomnumber = roomnumber
        self.roomBlocks = []
        for y in range(9):
            for x in range(16):
                color = floordesign.get_at((x + (roomnumber * 16), y))
                #                print("x = " + str(x+ (roomnumber*16)) + "; y = " + str(y) + "; color = " + str(color))
                if color == (0, 0, 0, 255):  # wall
                    self.roomBlocks.append(Wall((x, y)))
                elif color == (88, 88, 88, 255):  # spike
                    if floordesign.get_at(
                        (x + (roomnumber * 16), y + 1)) == (0, 0, 0, 255):
                        self.roomBlocks.append(Spike((x, y)))
                    elif floordesign.get_at(
                        (x + (roomnumber * 16) + 1, y)) == (0, 0, 0, 255):
                        self.roomBlocks.append(Spike((x, y), 1))
                    elif floordesign.get_at(
                        (x + (roomnumber * 16) - 1, y)) == (0, 0, 0, 255):
                        self.roomBlocks.append(Spike((x, y), 3))
                    elif floordesign.get_at(
                        (x + (roomnumber * 16), y - 1)) == (0, 0, 0, 255):
                        self.roomBlocks.append(Spike((x, y), 2))
                    else:
                        self.roomBlocks.append(Spike((x, y)))
                elif color == (18, 189, 99, 255):
                    self.roomBlocks.append(Coin((x, y)))
                elif color == (189, 18, 18, 255):
                    #enemy
                    if floordesign.get_at(
                        (x + (roomnumber * 16), y + 1)) == (0, 0, 0, 255):
                        if floorNumber == 1:
                            self.roomBlocks.append(Slime((x, y)))
                        elif floorNumber == 2:
                            self.roomBlocks.append(Slime2((x, y)))
                        elif floorNumber == 3:
                            self.roomBlocks.append(Slime3((x, y)))
                        elif floorNumber == 4:
                            self.roomBlocks.append(Slime4((x, y)))
                        elif floorNumber == 5:
                            self.roomBlocks.append(Slime5((x, y)))
                    else:
                        # bat
                        if floorNumber == 1:
                            self.roomBlocks.append(Bat((x, y)))
                        elif floorNumber == 2:
                            self.roomBlocks.append(Bat2((x, y)))
                        elif floorNumber == 3:
                            self.roomBlocks.append(Bat3((x, y)))
                        elif floorNumber == 4:
                            self.roomBlocks.append(Bat4((x, y)))
                        elif floorNumber == 5:
                            self.roomBlocks.append(Bat5((x, y)))
                elif color == (23, 18, 189, 255):
                    #spring
                    self.roomBlocks.append(Spring((x, y)))
                elif color == (215, 223, 1, 255):
                    self.roomBlocks.append(SpawnPoint((x, y)))
                elif color == (230, 89, 1, 255):
                    self.roomBlocks.append(Button((x, y)))
                elif color == (168, 7, 125, 255):
                    self.roomBlocks.append(PNJ((x, y)))
                elif color == (9, 199, 254):
                    self.roomBlocks.append(Table((x, y)))
                elif color == (124, 48, 201):
                    self.roomBlocks.append(Boss((x, y)))