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)
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
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)
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!')
def install(*scripts): """install scripts""" if scripts.__len__() >= 1: for index in xrange(0, scripts.__len__()): bat = Bat(scripts[index]) bat.install() else: print('Please use `vimpyre install <script-name>` and try again!')
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!')
def update(*scripts): """update scripts""" if scripts.__len__() >= 1: for index in xrange(0, scripts.__len__()): bat = Bat(scripts[index]) bat.update() else: print('Please use `vimpyre update <script-name>` and try again!')
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!')
def doremove(self, args): """remove scripts""" scripts = args.scripts if len(scripts) >= 1: for index in xrange(0, len(scripts)): bat = Bat(scripts[index]) bat.remove() else: console('Please use `vimpyre remove <script-name>` and try again!')
def __init__(self, *args, **kwargs): # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck'
def __init__(self, *args, **kwargs): # Cách điển hình để thừa kế thuộc tính là gọi super # super(Batman, self).__init__(*args, **kwargs) # Tuy nhiên với đa thừa kế, super() sẽ chỉ gọi lớp cơ sở tiếp theo trong danh sách MRO. # Vì thế, ta sẽ gọi cụ thể hàm __init__ của các lớp chả. # Sử dụng *args và **kwargs cho phép việc truyền đối số gọn gàng hơn, # trong đó mỗi lớp cha sẽ chịu trách nhiệm cho những phần thuộc về nó Human.__init__(self, 'anonymous', *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # ghi đè giá trị của thuộc tính name self.name = 'Sad Affleck'
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() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". Human.__init__(self, 'anonymous', *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck'
def __init__(self, *args, **kwargs): # Обычно для наследования атрибутов необходимо вызывать super: # super(Batman, self).__init__(*args, **kwargs) # Однако здесь мы имеем дело с множественным наследованием, а super() # работает только со следующим базовым классом в списке MRO. # Поэтому вместо этого мы вызываем __init__ для всех родителей. # Использование *args и **kwargs обеспечивает чистый способ передачи # аргументов, когда каждый родитель "очищает слой луковицы". Superhero.__init__(self, 'анонимный', movie=True, superpowers=['Богатый'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # переопределить значение атрибута name self.name = 'Грустный Бен Аффлек'
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() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. # The use of *args and **kwargs allows for a clean way to pass arguments, # with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) # override the value for the name attribute self.name = 'Sad Affleck'
def dosearch(self, args): """search script""" bat = Bat(args.script) 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!')
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!')
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)
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)
def search(*scripts): """search script""" if scripts.__len__() > 1: print('Please search one script name!') sys.exit(1) bat = Bat(scripts[0]) rets = bat.search() print('=> => Send bats to search vim-scripts ...') if rets: for item in rets: if os.path.exists(VIM_PATH + 'vimpyre/%s' % item['name']): print('\033[1m%s\033[m => %s \033[1m[installed]\033[m' % (item['name'].encode('utf-8'), item['description'].encode('utf-8'))) else: print('\033[1m%s\033[m => %s' % (item['name'].encode('utf-8'), item['description'].encode('utf-8'))) else: print('No such vim-scripts! Please use `vimpyre syncdb` and try again!')
def list_all(): bat = Bat() bat.list_all()
def syncdb(): bat = Bat() bat.syncdb()
species = 'Baty' 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)
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
def remove_all(): bat = Bat() bat.remove_all()
def update_all(): bat = Bat() bat.update_all()
def init(): bat = Bat() bat.install_base()
def __init__(self, *args, **kwargs): # super(Batman, self).__init__(*args, **kwargs) # doesn't work for multiple inheritance Human.__init__(self, 'anonymous', *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) self.name = 'Sad Affleck'
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
def doinit(self, args): """intialize enviroment""" bat = Bat() bat.install_base()
def get_sample_bat_sections(): return {0:Bat(SAMPLE_BAT)}
def list_installed(): bat = Bat() bat.list_installed()
species = 'Летучая мышь' def __init__(self, can_fly=True): self.fly = can_fly # В этом классе также есть метод say def say(self, msg): msg = '... ... ...' return msg # И свой метод тоже def sonar(self): return '))) ... (((' if __name__ == '__main__': b = Bat() print(b.say('привет')) print(b.fly) # И еще одно определение класса, унаследованное от Superhero и Bat # superhero.py from superhero import Superhero from bat import Bat # Определите Batman как дочерний класс, унаследованный от Superhero и Bat class Batman(Superhero, Bat): def __init__(self, *args, **kwargs): # Обычно для наследования атрибутов необходимо вызывать super: # super(Batman, self).__init__(*args, **kwargs)
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)
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()
# 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
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()
species = 'Baty' 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)
def doremove_all(self, args): """remove all scripts """ bat = Bat() bat.remove_all()
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()
def doupdate_all(self, args): """update all scripts""" bat = Bat() bat.update_all()
def dolist_installed(self, args): """list installed scripts""" bat = Bat() bat.list_installed()
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()
species = 'Baty' def __init__(self, can_fly=True): self.fly = can_fly # instance methods - always receive the current class as the 1st arg def say(self, msg): msg = '... ... ...' return msg def sonar(self): return '))) ... (((' if __name__ == '__main__': b = Bat() print(b.say('hello')) # '... ... ...' as msg is overidden in say() print(b.fly) # 'True' from human import Human from bat import Bat class Batman(Human, Bat): species = 'Superhero' def __init__(self, *args, **kwargs): # super(Batman, self).__init__(*args, **kwargs) # doesn't work for multiple inheritance Human.__init__(self, 'anonymous', *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs)