def create_zombie(ai_settings, screen, zombies, zombie_number, row_number): zombie = Zombie(ai_settings, screen) zombie_width = zombie.rect.width zombie.x = zombie_width + 2 * zombie_width * zombie_number zombie.rect.x = zombie.x zombie.rect.y = zombie.rect.height + 2 * zombie.rect.height * row_number zombies.add(zombie)
def main(args): zombie = Zombie(args['field'], args['position'], args['infected'], args['infection_radius'], args['infection_cooldown']) mqtt_server_addr = args['server'][0] mqtt_queue = args['server'][1] producer = get_producer_connection(mqtt_server_addr, KAFKA_CONNECTION_TRIES) kill = Event() zombie_broadcast = Thread(target=thread_zombie_broadcast, args=(kill, zombie, args['zombie_port'])) zombie_listen = Thread(target=thread_zombie_listen, args=(kill, zombie, args['zombie_port'])) server_con_thread = Thread(target=thread_server_con, args=(kill, zombie, mqtt_server_addr, mqtt_queue, producer)) zombie_broadcast.start() zombie_listen.start() server_con_thread.start() if args['interactive']: interactive(zombie) else: automatic(zombie, args) zombie.alive = False kill.set() zombie_broadcast.join() zombie_listen.join() server_con_thread.join() logging.info('program ended')
def __init__(self): self.screen = pg.display.set_mode(SIZE) self.clock = pg.time.Clock() self.running = True self.paused = False self.debug = False self.shift = False self.follow = False self.minimap = False self.FPS = 60 self.bg = Background(SIZE) self.camera = Camera(w=WIDTH, h=HEIGHT) self.blocks = [] self.fading = [] self.fading_zombies = [] self.screenshot_counter = 0 self.destroyers = pg.sprite.Group() self.player = Ninja(position=(200, 100), screen=self.bg.rect) zombie1 = Zombie((100, 500), self.bg.rect, False) zombie2 = Zombie((700, 50), self.bg.rect, True) self.zombies = pg.sprite.Group(zombie1, zombie2) self.reset() self.run()
def do_step(): # Buffer all the move_by calls and do at once. # Note that this does not buffer other state changes made in objects, # such as a teleport - we really should have that facility for a proper # simulation of a time step # we should also enforce the restriction on the move limit for each # type of object. At the moment, you can get around this limit by calling # move_by in the compute_next_move method! moves = [ ] # give the defenders a chance to tell the normals what to do # and try to teleport any zombies for p in Defender.get_all_present_instances(): moves.append( (p,) + p.compute_next_move() ) # then give the normals a chance for p in Normal.get_all_present_instances(): moves.append( (p,) + p.compute_next_move() ) # and finally the zombies, which may have been teleported to new positions for p in Zombie.get_all_present_instances(): moves.append( (p,) + p.compute_next_move() ) # then execute the moves, even though other state may have been changed # earlier for (p, delta_x, delta_y) in moves: p.move_by(delta_x, delta_y) # then convert normals into zombies if the zombies are close enough # Warning: z - number of zombies, n - number of normals, then the # time complexity of this is O( z n ) for z in Zombie.get_all_present_instances(): for n in Normal.get_all_present_instances(): d_e_e = z.distances_to(n)[3] d_touch = z.get_touching_threshold() # print(z.get_name(), n.get_name(), d_e_e, d_touch) if d_e_e <= d_touch: x = n.get_xpos() y = n.get_ypos() new_z = Zombie(size=n.get_size(), haircolor='green', xpos = x, ypos = y, move_limit=person_move_limit) new_z.arrive() n.leave() Person.del_instance(n)
def run(self): self.start_screen() params = self.menu.run() running = True self.hitokiri = Hitokiri(self.hitokiri_sprites, position=(300, 290), horisontal_move=False, weapont_sprites=self.weapont_sprites, life=params['life']) self.hart = Hart(self.screen, self.hitokiri) font = pygame.font.Font(None, 30) while running: self.screen.fill([255, 255, 255]) self.screen.blit(self.backround_image, (0, 0)) ss = random.randint(1, params['random']) # параметр из меню if ss == 2: Zombie(self.zombie_sprites, horisontal_move=True, position=(20, 280), hitokiri=self.hitokiri, weapont_sprites=self.weapont_sprites, hitokiri_sprites=self.hitokiri_sprites) if ss == 3: Zombie(self.zombie_sprites, direction=-1, horisontal_move=True, position=(WIDTH - 20, 280), hitokiri=self.hitokiri, weapont_sprites=self.weapont_sprites, hitokiri_sprites=self.hitokiri_sprites) for event in pygame.event.get(): # при закрытии окна if event.type == pygame.QUIT: terminate() # меняем состояние хитокири: if event.type == pygame.KEYDOWN: self.hitokiri.set_state_down(event) if event.type == pygame.KEYUP: self.hitokiri.set_state_up(event) if event.type == pygame.MOUSEBUTTONUP: pass self.weapont_sprites.update() self.weapont_sprites.draw(self.screen) self.hitokiri_sprites.update() self.zombie_sprites.update() self.zombie_sprites.draw(self.screen) self.hitokiri_sprites.draw(self.screen) text_m = font.render(f'SIZE: {self.hitokiri.zomby_kill} ', 0, (255, 255, 255)) self.hart.write(10, 10) # жизни self.screen.blit(text_m, (10, 50)) # очки # если жизни кончились, то выходим из цикла if self.hitokiri.life < 1: running = False pygame.display.flip() self.clock.tick(FPS * params['fps']) # концовка, экран не перерисовывается # сверху пишется "game over" text_go = self.font_zombie.render('GAME OVER', 1, (255, 215, 0)) self.screen.blit(text_go, (280, 130)) pygame.display.flip() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT or event.type == pygame.KEYDOWN: terminate()
def _create_zombie(self): #Create a zombie and place it on the right hand side of screen zombie = Zombie(self) zombie_width, zombie_height = zombie.rect.size max_y = self.settings.screen_height - zombie_height random_entry = randint(0, max_y) zombie.y = random_entry zombie.x = (self.settings.screen_width + randint(50, 200)) zombie.rect.x = zombie.x zombie.rect.y = zombie.y self.zombies.add(zombie)
def enter(): gfw.world.init(['bg', 'zombie', 'player']) global player player = Player() gfw.world.add(gfw.layer.player, player) bg = gobj.ImageObject('kpu_1280x960.png', (canvas_width // 2, canvas_height // 2)) gfw.world.add(gfw.layer.bg, bg) global zombie_time zombie_time = 1 Zombie.load_all_images()
def create_new_world(): global boy, zombies boy = Boy() zombies = [Zombie() for i in range(100)] game_world.add_object(boy, 1) game_world.add_objects(zombies, 1)
def run_game(): tick = 0; while 1: if game_settings.game_active: gf.check_events(screen, game_settings, squares, plants, bullets); # screen.fill(game_settings.bg_color); tick += 1; if tick % 30 == 0: zombies.add(Zombie(screen, game_settings)); zombies_hit = groupcollide(zombies, bullets, False, False); #zombies_hit = dictionary of sprites; bullets will go straight through the zombies if both are false # print zombies_hit for zombie in zombies_hit: #empty dictionary - zombies are objects put in zombies list (.add() above) # print zombie; if zombie.yard_row == zombies_hit[zombie][0].yard_row: # print "Same row!"; bullets.remove(zombies_hit[zombie][0]); zombie.hit(1); #calling the zombie's local hit method - passed 1 damage - .hit adjusts their health if (zombie.health <= 0): zombies.remove(zombie); #removes zombie from game game_settings.zombie_in_row[zombie.yard_row] -= 1; #removes the 1 zombie from the row as its' killed - plant will keep shooting until # of zombies in row = 0 gf.update_screen(screen, game_settings, background, zombies, squares, plants, bullets, tick); pygame.display.flip();
def fire(stats, ai_settings, snow_pea, screen, bullets, zombies, buckethead_zombies, float_zombies): # 自动发射豌豆,生成僵尸 stats.bullet_accumulate += 1 if stats.bullet_accumulate >= ai_settings.bullet_max_accumulate: stats.bullet_accumulate = 0 new_bullet = Bullet(snow_pea, screen) bullets.add(new_bullet) stats.zombie_accumulate += 1 if stats.zombie_accumulate >= ai_settings.zombie_max_accumulate and stats.zombie_number > 0: stats.zombie_number -= 1 stats.zombie_accumulate = 0 new_zombie = Zombie(screen) zombies.add(new_zombie) stats.buckethead_zombie_accumulate += 1 if stats.level_2: if stats.buckethead_zombie_accumulate >= ai_settings.buckethead_zombie_max_accumulate and stats.buckethead_zombie_number > 0: stats.buckethead_zombie_number -= 1 stats.buckethead_zombie_accumulate = 0 new_zombie = Buckethead_Zombie(screen) buckethead_zombies.add(new_zombie) stats.float_zombie_accumulate += 1 if stats.level_3: if stats.float_zombie_accumulate >= ai_settings.float_zombie_max_accumulate and stats.float_zombie_number > 0: stats.float_zombie_number -= 1 stats.float_zombie_accumulate = 0 new_zombie = Float_Zombie(screen) float_zombies.add(new_zombie)
def run_game(): tick = 0; while 1: gf.check_events(screen,game_settings, squares, plants,bullets,icons); if game_settings.game_active: tick += 1; if tick % 30 == 0: zombies.add(Zombie(screen,game_settings)); zombies_hit = groupcollide(zombies, bullets, False, False); # print zombies_hit; for zombie in zombies_hit: # print zombie; # print zombies_hit[zombie]; if zombie.yard_row == zombies_hit[zombie][0].yard_row: # print "Same row!!!"; bullets.remove(zombies_hit[zombie][0]); zombie.hit(1); if(zombie.health <= 0): zombies.remove(zombie); game_settings.zombie_in_row[zombie.yard_row] -= 1; game_settings.zombies_killed += 1; # Create a dictionary with a key of Zombie and a value of a list of Plants that zombie has colided with zombies_eating = groupcollide(zombies, plants, False, False); # Loop through the dictionary for zombie in zombies_eating: # Set a var for the Plant (to save our eyes) damaged_plant = zombies_eating[zombie][0]; # Check to see if the zombie and plant are in the same row if zombie.yard_row == damaged_plant.yard_row: # Zombie has run into a plant in it's row # start/continue eating... stop moving if neccessary zombie.moving = False; # Check to see if zombie takes a bite if time.time() - zombie.started_eating > zombie.damage_time: # print "Zombie just took a bite"; # Run chomp zombie.zombie_chomp(damaged_plant); # plant.take_damage(); # update zombies last bite time zombie.started_eating = time.time() # remove the plant if it's 0 or below if damaged_plant.health <= 0: plants.remove(damaged_plant); # start the zombie march again zombie.moving = True; # zombies_eating = { # "key": 2, # <Zombie>: [ # <Plant>, # <Plant>, # <Plant>, # <Plant> # ] # } gf.update_screen(screen,game_settings,background,zombies,squares,plants,bullets,tick,icons); pygame.display.flip();
def create_fighter(ai_settings, screen, fighter, zombies): zombie = Zombie(ai_settings, screen) number_zombies_x = get_number_zombies_x(ai_settings, zombie.rect.width) number_rows = get_number_rows(ai_settings, fighter.rect.height, zombie.rect.height) for row_number in range(number_rows): for zombie_number in range(number_zombies_x): create_zombie(ai_settings, screen, zombies, zombie_number, row_number)
def generate_zombie_start(): global Zombie_Generate_num for i in range(1, 6): m = Zombie((get_canvas_width() + random.randint(0, 5) * 10, get_canvas_height() - i * 100), 'Zombie') gfw.world.add(gfw.layer.zombie, m) Zombie_Generate_num += 1
def create_horde(settings, screen, zombies, survivor): zombie = Zombie(settings, screen) number_zombies_x = get_number_zombies_x(settings, zombie.rect.width) for row_number in range( get_number_rows(settings, survivor.rect.height, zombie.rect.height)): for zombie_number in range(number_zombies_x): create_zombie(settings, screen, zombies, zombie_number, row_number)
def update(): gfw.world.update() global zombie_time zombie_time -= gfw.delta_time if zombie_time <= 0: gfw.world.add(gfw.layer.zombie, Zombie()) zombie_time = 5
def main_loop(survivor, clock): total_frames = 0 while survivor.health > 0: Tile.draw_all(display) interaction(display, survivor) Zombie.spawn(display, total_frames, survivor) survivor.movement() text(display, survivor.health, Zombie.left_round + len(Zombie.instances), clock.get_fps(), Zombie.level, survivor.ammo, Drop.actives) Bullet.update(display) survivor.draw(display) Zombie.update(display, survivor) PickUp.update(display, survivor, total_frames) Drop.update(display, survivor) clock.tick(Options.fps) pygame.display.flip() total_frames += 1
def create_game(self): return Zombie( grid_height = 4, grid_width = 4, obstacle_list = [(2,2)], zombie_list = [(3,0)], human_list = [(3,1)] )
def enter(): server.boy = Boy() game_world.add_object(server.boy, 1) server.zombie = Zombie() game_world.add_object(server.zombie, 1) server.ground = Ground() game_world.add_object(server.ground, 0)
def spwanZombies(time): if p.zombieCount < p.wave * 5: if random.randint(1, 100) > 75: z = Zombie(p, 10, p.x, p.y) e.drawables.add(z) e.objects.append(z) e.collisions[z] = (p, p.ouch) p.zombieCount = p.zombieCount + 1 zombies.append(z)
def create_new_world(): global boy boy = Boy() game_world.add_object(boy, 1) with open('zombie_data.json', 'r') as f: zombie_data_list = json.load(f) for data in zombie_data_list: zombie = Zombie(data['name'], data['x'], data['y'], data['size']) game_world.add_object(zombie, 1)
def main(): my_hero = Hero() goblin = Goblin() zombie = Zombie() medic = Medic() shadow = Shadow() while (goblin.alive() or zombie.alive()) and my_hero.alive(): my_hero.print_status() print() print("What do you want to do?") print("1. fight goblin") print("2. fight zombie") print("3. fight medic") print("4. fight shadow") print("5. do nothing") print("6. flee") print("> ",) user_input = input() if user_input == "1": goblin.print_status() # my_hero attacks goblin my_hero.attack(goblin) if goblin.health > 0: # Goblin attacks my_hero goblin.attack(my_hero) elif user_input == "2": zombie.print_status() my_hero.attack(zombie) zombie.attack(my_hero) zombie.alive() elif user_input == "3": medic.print_status() my_hero.attack(medic) medic.attack(my_hero) medic.alive() elif user_input == "4": shadow.print_status() shadow.attack(my_hero) my_hero.attack(shadow) shadow.alive() elif user_input == "5": pass elif user_input == "6": print("Goodbye.") break else: print("Invalid input %r" % user_input)
def create_new_world(): global boy, zombie boy = Boy() game_world.add_object(boy, 1) with open('zombie_data.json', 'r') as f: zombie_data_list = json.load(f) # f라는 파일을 역직렬화 해서 리스트로 for data in zombie_data_list: # json 파일을 바꿈으로 내가 원하는 레벨을 설계할 수 있다. zombie = Zombie(data['name'], data['x'], data['y'], data['size']) game_world.add_object(zombie, 1)
def update(self): # 更新对象 # 补足僵尸 if len(self.zombies) < self.settings.zombie_number: new_zombie = Zombie(self, (random() * 200, random() * 200)) if pygame.sprite.spritecollideany(new_zombie, self.zombies) == None: self.zombies.add(new_zombie) # 更新各对象状态 self.player.update() self.bullets.update() self.zombies.update() # 计算子弹击中僵尸 bullets_zombies_collisions = pygame.sprite.groupcollide( self.bullets, self.zombies, True, False) for bullet, zombies in bullets_zombies_collisions.items(): for zombie in zombies: zombie.hit_bullet(bullet) # 去除死亡僵尸 for zombie in self.zombies.copy(): if not zombie.alive: self.zombies.remove(zombie) self.stats.score += self.settings.zombie_kill_score # 奖励 if random() < self.settings.zombie_kill_bonus_change: self.player.change_hp(int(self.player.hp_limit * 0.1)) # 更新最高分 self.stats.update() if not self.player.blink: # 计算僵尸碰撞玩家,闪烁时玩家无敌,不计算 player_zombies_collisions = pygame.sprite.spritecollideany( self.player, self.zombies) if player_zombies_collisions: self.player.hit_zombie() # 判断游戏结束 if self.player.alive == False: self.stats.game_over = True return # 去除出界子弹 for bullet in self.bullets.copy(): if not bullet.alive: self.bullets.remove(bullet) self.ui.update()
def enter(): global boy boy = Boy() game_world.add_object(boy, 1) global zombie zombie = Zombie() game_world.add_object(zombie, 1) ground = Ground() game_world.add_object(ground, 0)
def addZombie(self, c, address): for z in self.zombies: if z.address == address and not z.active(): z.openedSocket.close() z.openedSocket = c return True zombie = Zombie(c, len(self.zombies), address) self.zombies.append(zombie) return True
def update_tickspeed(self): self.ticks += 1 if (self.ticks % 120) == 0: self.zombies.add(Zombie(self)) if (self.ticks % 120) == 0: for zombie in self.zombies.copy(): zombie.seconds -= 1 if zombie.seconds == 0: self.zombies.remove(zombie) if self.ticks > 10000000: self.ticks = 1
def main(): ''' main entry point ''' player = Player('Barry') monster = Zombie() print('%s approachs a %s' % (player.name, monster.name)) while monster.is_alive() and player.is_alive(): # See if player wants to attack the monster attack = prompt_next_action(player, monster.name) if attack: # Player chooses to attack the monster attack_monster(player, monster, attack) else: print('%s runs away like a little girl' % player.name) break #print('Player health %d' % player.health) #print('Player strength %d' % player.strength) #print('Player magick %d' % player.magick) #print('Monster health %d' % monster.health) print('Game over')
def make_zombie_herd(self, num_of_zombies, zombie_health, delta): """Creates a herd of zombies Creates a list of zombies generated in random positions on the screen start_x_pos for each zombie is a number in [-1000, 0) start_y_pos for each zombie is a random position along the y-axis Args: num_of_zombies: the amount of zombies to be generated in the herd height: the height of the display Returns: a sprite group of zombies """ zombie_herd = pygame.sprite.Group() for _ in range(num_of_zombies): start_x = random.randint(-1050, -50) start_y = self.game_display.get_height() * random.uniform(0.1, 0.9) zombie = Zombie(start_x, start_y) zombie.health = zombie_health zombie.delta = delta zombie_herd.add(zombie) return zombie_herd
def enter(): global boy boy = Boy() game_world.add_object(boy, 1) global zombie zombie = Zombie() game_world.add_object(zombie, 1) global balls balls = [Ball() for i in range(20)] game_world.add_objects(balls, 1) ground = Ground() game_world.add_object(ground, 0)
def create_new_world(): global playTime playTime = get_time() print(playTime) global boy boy = Boy() game_world.add_object(boy, 1) # fill here with open('zombie_data.json', 'r') as f: zombie_data_list = json.load(f) for data in zombie_data_list: zombie = Zombie(data['name'], data['x'], data['y'], data['size']) zombies.append(zombie) game_world.add_object(zombie, 6) global time_CreateMonster global time_UpdateCreateMonster global posX global posY global posOffsetX global Monster_Hp global Monster_Speed global Monster_Exp time_CreateMonster += 0.1 if playTime >= 5: print('make_monster') for n in range(random.randint(0, 2 + 1), random.randint(3, 5 + 1)): PosX = posX + posOffsetX * n Monster_Hp = 100 Monster_Speed = 400 Monster_Exp = 50 # x, y, scaleX, scaleY, hp, speed, radius, exp, filename GameObject = moster.CMonster(PosX, posY, 114, 76, Monster_Hp, Monster_Speed, 25, Monster_Exp, "Enemy01.png") game_world.add_object(GameObject, 8) # game_world.remove_object(GameObject) pass
def setup(self): self.game_status = "Game is on" # Sprite lists self.player_list = arcade.SpriteList() self.zombie_list = arcade.SpriteList() self.bullet_list = arcade.SpriteList() self.player = Player() self.player.center_x = 50 self.player.center_y = 50 self.player_list.append(self.player) self.zombie = Zombie("images/zombie/zombie_stand.png", SPRITE_SCALING_PLAYER) self.zombie.center_x = 500 self.zombie.center_y = 200 self.zombie_list.append(self.zombie)
def main(): from zombie import Zombie from zombie import modules from optparse import OptionParser #Check python version required = (2,4) version = sys.version_info[:2] if version < required: required = '.'.join(map(lambda x: str(x), required)) print 'Zombie requires at least Python ', required return 0 installed = modules.__all__ usage = """usage: %prog INPUT OUTPUT [options]""" descr = """Zombie converts documents from one arbitrary format to another.""" parser = OptionParser(usage=usage, description=descr) parser.add_option('-i', dest='imodule', help='Override auto detection for input module', type='string') parser.add_option('-o', dest='omodule', help='Override auto detection for output module', type='string') parser.add_option('-e', dest='encoding', help='Specify encoding for output module, not all modules use this.', type='string') parser.add_option('-v', dest='verbose', help='Enable verbose output', action='store_true') parser.add_option('-t', dest='title', help='Explicitly set title for conversion', type='string') parser.add_option('-l', dest='list', help='List available modules', action="store_true") options, args = parser.parse_args() if len(args) < 2 or options.list: if options.list: print 'Modules available to Zombie:' for module in modules.__all__: print "\t* " + module else: parser.print_help() return 0 args = { 'input' : args[0], 'output' : args[1], 'omod' : options.omodule, 'imod' : options.imodule, 'title' : options.title, 'encoding': options.encoding, 'verbose' : options.verbose, } job = Zombie( input = args['input'], output = args['output'], imod = args['imod'], omod = args['omod'], title = args['title'] ) if job.omod: job.omod.VERBOSE = args['verbose'] or False job.omod.CHARSET = args['encoding'] or 'utf-8' if job.convert(): output_thread = job.finalize() output_thread.join() #Wait for output thread to rejoin else: errors = ['Conversion failed for the following reasons:',] if not job.imod: errors.append('No suitable input module found') if not job.omod: errors.append('No suitable output module found') if not job.intermediate: errors.append('Input module did not produce a usable intermediate object') if not job.output: errors.append('Output module did not produce a usable output object') print '\n\t'.join(errors) return 0
class Game: def __init__(self, socket, server): self.round = 0 self.zombie = None self.socket = socket self.server = server self.account_name = '' self.account_password_hash = '' self.account_info = () self.has_started = False self.combo_found = False self.create_commands() Attack.create_attacks(self) def quit(self): if not self.has_started: self.server.disconnect(self.socket) else: self.display(color.YELLOW + "Save yo game? Yes or no?" + color.END) return self.maybe_quit def maybe_quit(self, text): res = text.strip().lower() if res == 'yes': self.save() elif res != 'no': return self.quit() self.server.disconnect(self.socket) def save(self): c = self.server.db.cursor() c.execute('UPDATE users SET has_healed=?, number_of_games_played=?, punch_upgrade=?, kick_upgrade=?, total_kills=?, rank=?, kills_since_last_rank_up=?, new_game=?, current_kills=?, wave=?, xp=?, health=? WHERE username = ?', self.player.info_to_save()) c.execute("SELECT float_value FROM stats WHERE record = 'total kills'") c.execute("UPDATE stats SET float_value = float_value + ? WHERE record = 'total kills'", (self.player.current_kills,)) self.server.db.commit() self.display(color.YELLOW + "Game saved!" + color.END) def signin(self, text = None): self.display(color.MAGENTA + 'Welcome to Zombie Smack Down!' + color.END) self.display(color.MAGENTA + 'Total kills worldwide: %d' % self.stats()['total kills'] + color.END) self.display("Enter 'signin' if you've been here before and have an account, or enter 'signup' to create an account.") self.display("An account is only necessary to save your progress. If you wish to play as a guest, simply enter 'guest'.") self.display("If you hate fun therefore do not wish to play zombie smack down, enter 'quit'.") return self.do_signin def do_signin(self, text): method = text.strip().lower() if method == 'sign in' or method == 'signin': self.display('Username: '******'sign up' or method == 'signup': self.display('Enter a username: '******'quit': self.display('Bye!') self.quit() else: self.display('What?') return self.do_signin def create_account_name(self, text): self.account_name = text.strip() c = self.server.db.cursor() c.execute('SELECT username FROM users WHERE username = ?', (self.account_name,)) if c.fetchone(): self.display(color.YELLOW + 'That username is already taken. Please pick another ;(' + color.END) self.display('Username: '******'Enter a password: '******'\xff\xfb\x01') return self.create_account_password def create_account_password(self, text): self.socket.send(b'\xff\xfc\x01') self.account_password_hash = bcrypt.hashpw(text.encode(), bcrypt.gensalt(12)) self.create_account() self.start() def create_account(self): c = self.server.db.cursor() c.execute('INSERT INTO users VALUES (NULL, ?, ?, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0)', (self.account_name, self.account_password_hash)) c.execute("UPDATE stats SET float_value = float_value + 1 WHERE record = 'total users'") self.server.db.commit() self.display('Account created!') self.player = Player(self, self.account_name, False, 0, 0, 0, 0, 1, 0, True, 0, 0, 0, 0) def signin_username(self, text): name = text.strip() c = self.server.db.cursor() c.execute('SELECT * FROM users WHERE username = ?', (name,)) self.account_info = c.fetchone() if self.account_info: self.display('Password: '******'\xff\xfb\x01') return self.signin_password else: self.display(color.YELLOW + 'Unknown username.' + color.END) self.quit() def signin_password(self, text): self.socket.send(b'\xff\xfc\x01\n') if bcrypt.hashpw(text.encode(), self.account_info[2]) == self.account_info[2]: a = self.account_info[1:] self.display('Welcome %s!' % a[0]) self.player = Player(self, a[0], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13]) self.start() else: self.display(color.YELLOW + 'Wrong passoword.' + color.END) self.quit() #### END SERVER/ACCOUNT CRAP #### def stats(self): c = self.server.db.cursor() _stats = {} for row in c.execute("SELECT * FROM stats WHERE record IN ('total kills', 'total users')"): _stats[row[1]] = row[2] return _stats def start(self): self.display(color.MAGENTA + 'Type help or ? for help' + color.END) self.display('> ', newLine = False) self.generate_zombie() self.has_started = True def generate_zombie(self): self.zombie = Zombie(self, *ZOMBIE_TYPES[self.player.wave - 1]) def display(self, string, newLine = True): if newLine: string += '\n' try: self.socket.send(string.encode()) except OSError: pass def check_regex(self, feedback, regex_str): match = re.compile(regex_str).match(feedback) if match: return match.groups() else: return None def parse_input(self, feedback): feedback = feedback.strip().lower() match = None cmd_found = None for command in self.commands: match = self.check_regex(feedback, command.regex) if match is not None: cmd_found = command.func break status = None if match is None: attack = Attack.ATTACKS.get(feedback) if attack: status = self.player.attack(self.zombie, attack) else: self.display("What?") else: status = cmd_found(match) self.print_prompt(feedback) return status if status else self.parse_input def create_commands(self): self.commands = [] tmp = [ ['^info$', 'info', 'Gives info', lambda x: self.info() ], ['^(help|\?)( ([\w\s]+))?$', 'help', 'Gives help', lambda x: self.help(x[2]) ], ['^quit|exit$', 'quit', 'If you want to leave.', lambda x: self.quit() ], ['^heal( (\d+))?$', 'heal', 'It heals you.', lambda x: self.player.heal(x[1]) ], ['^save$', 'save', 'It saves the game', lambda x: self.save() ], ['^combolist$', 'combolist', 'It lists the combos you have unlocked.', lambda x: self.combolist() ] ] for tmpJr in tmp: self.commands.append(Command(*tmpJr)) def print_prompt(self, feedback = ""): if not (feedback == "quit" or feedback == "exit"): self.display('> ', newLine = False) def combolist(self): combo_count = 1 self.display(color.MAGENTA + 'Unlocked combos:' + color.END) for a in Attack.ATTACK_KEYS: attack = Attack.ATTACKS[a] if attack.isCombo and combo_count <= self.player.rank: attack.describe() combo_count += 1 def info(self): self.player.info() self.display('') self.zombie.info() def help(self, cmd = None): if not cmd: names = ", ".join([str(command.name) for command in self.commands]) self.display('Here are some helpful commands: ' + names) # also explain/mention kick and punch else: # handle the case of cmd being an attack cmd = cmd.lower().strip() for command in self.commands: if cmd == command.name: the_command = command self.display(color.MAGENTA + the_command.name) self.display(the_command.desc + color.END)
import pprint pygame.init() FRAME_TIME = 50 #50ms is 20 frames per second if __name__ == '__main__': print("Starting Pumpkin Hero...") screen_vars = ScreenVars() screen = pygame.display.set_mode((screen_vars.get_width(), screen_vars.get_height())) black = (0,0,0) witch = Witch(50,0,75,75) zombie = Zombie(250,0,75,75) monster = Monster(450,0,75,75) skeleton = Skeleton(650,0,75,75) done = False last_time = time.time()*1000.0 SPEED = 5 game = Game() key_monitor = KeyMonitor() #Message pump while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN and event.key == pygame.K_q:
def generate_zombie(self): self.zombie = Zombie(self, *ZOMBIE_TYPES[self.player.wave - 1])
def runGame(): pygame.init() screen = pygame.display.set_mode(SCREENRECT.size) background = pygame.Surface(SCREENRECT.size).convert() background.fill((0, 0, 0)) screen.blit(background, (0, 0)) pygame.display.update() clock = pygame.time.Clock() spriteGroupList = GameWorld.getSpriteGroups() AllSprites = spriteGroupList[0] WallSprites = spriteGroupList[1] RoadSprites = spriteGroupList[2] # for i in range(GameWorld.x): # for j in range(GameWorld.y): # screen.blit(GameWorld.arrayX[i][j].image, GameWorld.arrayX[i][j].rect) AllSprites.draw(screen) # -testzombie- TestZombie1 = Zombie(ZOMBIESIZE, GameWorld.arrayX[3][3], TILESIZE, GameWorld.arrayX) TestZombie2 = Zombie(ZOMBIESIZE, GameWorld.arrayX[3][16], TILESIZE, GameWorld.arrayX) TestZombie3 = Zombie(ZOMBIESIZE, GameWorld.arrayX[8][5], TILESIZE, GameWorld.arrayX) TestZombie4 = Zombie(ZOMBIESIZE, GameWorld.arrayX[9][15], TILESIZE, GameWorld.arrayX) TestZombie5 = Zombie(ZOMBIESIZE, GameWorld.arrayX[12][13], TILESIZE, GameWorld.arrayX) TestZombie6 = Zombie(ZOMBIESIZE, GameWorld.arrayX[18][5], TILESIZE, GameWorld.arrayX) TestZombie7 = Zombie(ZOMBIESIZE, GameWorld.arrayX[18][13], TILESIZE, GameWorld.arrayX) zombietimer = 0 # ------------ HealthDisplay = "Health: " + str(Player.health) FuelDisplay = "Fuel: " + str(Player.fuel) GameWorld.placeHuman(Player, 0, 0) GameWorld.placeZombie(TestZombie1, 1, 1) GameWorld.placeZombie(TestZombie2, 1, 1) GameWorld.placeZombie(TestZombie3, 1, 1) GameWorld.placeZombie(TestZombie4, 1, 1) GameWorld.placeZombie(TestZombie5, 1, 1) GameWorld.placeZombie(TestZombie6, 1, 1) GameWorld.placeZombie(TestZombie7, 1, 1) movers = pygame.sprite.RenderPlain( Player, TestZombie1, TestZombie2, TestZombie3, TestZombie4, TestZombie5, TestZombie6, TestZombie7 ) movers.draw(screen) # screen.blit(GameWorld.arrayX[0][0].human.image, GameWorld.arrayX[0][0].human.rect) pygame.display.update() pygame.mixer.music.load("sounds/Contra_Boss_Battle.mid") pygame.mixer.music.play(-1) mainTitle = Title("images/title.png", 150, 350) titles = pygame.sprite.RenderPlain(mainTitle) titles.draw(screen) pygame.display.update() ENTER = False while ENTER is False: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.mixer.music.stop() elif event.type == KEYDOWN and event.key == K_RETURN: ENTER = True elif event.type == KEYDOWN and event.key == K_s: Player.isSim = True ENTER = True screen.blit(background, (0, 0)) AllSprites.draw(screen) movers.draw(screen) pygame.display.flip() ticks = 0 while 1: font = pygame.font.Font("extras/04b03.TTF", 24) HealthText = font.render(HealthDisplay, 0, (230, 0, 0)) FuelText = font.render(FuelDisplay, 0, (230, 0, 0)) HealthRect = HealthText.get_rect() FuelRect = FuelText.get_rect() HealthRect.topleft = [1, SCREENRECT.height - 20] FuelRect.topleft = [1, SCREENRECT.height - 40] screen.blit(FuelText, FuelRect) screen.blit(HealthText, HealthRect) pygame.display.update() clock.tick(30) # zombie random timer zombietimer = zombietimer + 1 if zombietimer >= 10: zombietimer = 0 TestZombie1.getNewDirection() TestZombie1.move() TestZombie2.getNewDirection() TestZombie2.move() TestZombie3.getNewDirection() TestZombie3.move() TestZombie4.getNewDirection() TestZombie4.move() TestZombie5.getNewDirection() TestZombie5.move() TestZombie6.getNewDirection() TestZombie6.move() TestZombie7.getNewDirection() TestZombie7.move() # update hp when zombie moves HealthDisplay = "Health: " + str(Player.health) Player.updateHealth() if Player.isSim == False: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.mixer.music.stop() return elif event.type == KEYDOWN: if (event.key == K_RIGHT) or (event.key == K_LEFT) or (event.key == K_UP) or (event.key == K_DOWN): Player.translateKey(event.key) # update hp when player moves HealthDisplay = "Health: " + str(Player.health) Player.updateHealth() else: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.mixer.music.stop() return if ticks == 30: Player.doSelfMove() # update hp when player moves HealthDisplay = "Health: " + str(Player.health) Player.updateHealth() if Player.health <= 0: font = pygame.font.Font("extras/04b03.TTF", 36) text = font.render("THE ZOMBIES GOT YOU! GAME OVER!", 0, (230, 0, 0)) textpos = text.get_rect(centerx=SCREENRECT.width / 2, centery=SCREENRECT.height / 2) screen.blit(text, textpos) pygame.display.update() pygame.mixer.music.fadeout(5000) time.sleep(5) return if Player.tile.helipad == True: font = pygame.font.Font("extras/04b03.TTF", 36) text = font.render("CONGRATULATIONS, YOU ESCAPED!", 0, (230, 0, 0)) textpos = text.get_rect(centerx=SCREENRECT.width / 2, centery=SCREENRECT.height / 2) screen.blit(text, textpos) pygame.display.update() pygame.mixer.music.fadeout(5000) time.sleep(5) return if ticks == 30: ticks = 0 else: ticks = ticks + 1 movers.update() screen.blit(background, (0, 0)) AllSprites.draw(screen) movers.draw(screen) pygame.display.flip()