游戏截图
动态演示
源码分享
state/tool.py
import os import json from abc import abstractmethod import pygame as pg from . import constants as c class state(): def __init__(self): self.start_time = 0.0 self.current_time = 0.0 self.done = false self.next = none self.persist = {} @abstractmethod def startup(self, current_time, persist): '''abstract method''' def cleanup(self): self.done = false return self.persist @abstractmethod def update(self, surface, keys, current_time): '''abstract method''' class control(): def __init__(self): self.screen = pg.display.get_surface() self.done = false self.clock = pg.time.clock() self.fps = 60 self.keys = pg.key.get_pressed() self.mouse_pos = none self.mouse_click = [false, false] # value:[left mouse click, right mouse click] self.current_time = 0.0 self.state_dict = {} self.state_name = none self.state = none self.game_info = {c.current_time:0.0, c.level_num:c.start_level_num} def setup_states(self, state_dict, start_state): self.state_dict = state_dict self.state_name = start_state self.state = self.state_dict[self.state_name] self.state.startup(self.current_time, self.game_info) def update(self): self.current_time = pg.time.get_ticks() if self.state.done: self.flip_state() self.state.update(self.screen, self.current_time, self.mouse_pos, self.mouse_click) self.mouse_pos = none self.mouse_click[0] = false self.mouse_click[1] = false def flip_state(self): previous, self.state_name = self.state_name, self.state.next persist = self.state.cleanup() self.state = self.state_dict[self.state_name] self.state.startup(self.current_time, persist) def event_loop(self): for event in pg.event.get(): if event.type == pg.quit: self.done = true elif event.type == pg.keydown: self.keys = pg.key.get_pressed() elif event.type == pg.keyup: self.keys = pg.key.get_pressed() elif event.type == pg.mousebuttondown: self.mouse_pos = pg.mouse.get_pos() self.mouse_click[0], _, self.mouse_click[1] = pg.mouse.get_pressed() print('pos:', self.mouse_pos, ' mouse:', self.mouse_click) def main(self): while not self.done: self.event_loop() self.update() pg.display.update() self.clock.tick(self.fps) print('game over') def get_image(sheet, x, y, width, height, colorkey=c.black, scale=1): image = pg.surface([width, height]) rect = image.get_rect() image.blit(sheet, (0, 0), (x, y, width, height)) image.set_colorkey(colorkey) image = pg.transform.scale(image, (int(rect.width*scale), int(rect.height*scale))) return image def load_image_frames(directory, image_name, colorkey, accept): frame_list = [] tmp = {} # image_name is "peashooter", pic name is 'peashooter_1', get the index 1 index_start = len(image_name) + 1 frame_num = 0; for pic in os.listdir(directory): name, ext = os.path.splitext(pic) if ext.lower() in accept: index = int(name[index_start:]) img = pg.image.load(os.path.join(directory, pic)) if img.get_alpha(): img = img.convert_alpha() else: img = img.convert() img.set_colorkey(colorkey) tmp[index]= img frame_num += 1 for i in range(frame_num): frame_list.append(tmp[i]) return frame_list def load_all_gfx(directory, colorkey=c.white, accept=('.png', '.jpg', '.bmp', '.gif')): graphics = {} for name1 in os.listdir(directory): # subfolders under the folder resources\graphics dir1 = os.path.join(directory, name1) if os.path.isdir(dir1): for name2 in os.listdir(dir1): dir2 = os.path.join(dir1, name2) if os.path.isdir(dir2): # e.g. subfolders under the folder resources\graphics\zombies for name3 in os.listdir(dir2): dir3 = os.path.join(dir2, name3) # e.g. subfolders or pics under the folder resources\graphics\zombies\coneheadzombie if os.path.isdir(dir3): # e.g. it's the folder resources\graphics\zombies\coneheadzombie\coneheadzombieattack image_name, _ = os.path.splitext(name3) graphics[image_name] = load_image_frames(dir3, image_name, colorkey, accept) else: # e.g. pics under the folder resources\graphics\plants\peashooter image_name, _ = os.path.splitext(name2) graphics[image_name] = load_image_frames(dir2, image_name, colorkey, accept) break else: # e.g. pics under the folder resources\graphics\screen name, ext = os.path.splitext(name2) if ext.lower() in accept: img = pg.image.load(dir2) if img.get_alpha(): img = img.convert_alpha() else: img = img.convert() img.set_colorkey(colorkey) graphics[name] = img return graphics def loadzombieimagerect(): file_path = os.path.join('source', 'data', 'entity', 'zombie.json') f = open(file_path) data = json.load(f) f.close() return data[c.zombie_image_rect] def loadplantimagerect(): file_path = os.path.join('source', 'data', 'entity', 'plant.json') f = open(file_path) data = json.load(f) f.close() return data[c.plant_image_rect] pg.init() pg.display.set_caption(c.original_caption) screen = pg.display.set_mode(c.screen_size) gfx = load_all_gfx(os.path.join("resources","graphics")) zombie_rect = loadzombieimagerect() plant_rect = loadplantimagerect()
state/constants.py
start_level_num = 1 original_caption = 'plant vs zombies game' screen_width = 800 screen_height = 600 screen_size = (screen_width, screen_height) grid_x_len = 9 grid_y_len = 5 grid_x_size = 80 grid_y_size = 100 white = (255, 255, 255) navyblue = ( 60, 60, 100) sky_blue = ( 39, 145, 251) black = ( 0, 0, 0) lightyellow = (234, 233, 171) red = (255, 0, 0) purple = (255, 0, 255) gold = (255, 215, 0) green = ( 0, 255, 0) size_multiplier = 1.3 #game info dictionary keys current_time = 'current time' level_num = 'level num' #states for entire game main_menu = 'main menu' load_screen = 'load screen' game_lose = 'game los' game_victory = 'game victory' level = 'level' main_menu_image = 'mainmenu' option_adventure = 'adventure' game_loose_image = 'gameloose' game_victory_image = 'gamevictory' #map components background_name = 'background' background_type = 'background_type' init_sun_name = 'init_sun_value' zombie_list = 'zombie_list' map_empty = 0 map_exist = 1 background_offset_x = 220 map_offset_x = 35 map_offset_y = 100 #menubar choosebar_type = 'choosebar_type' choosebar_static = 0 choosebar_move = 1 chossebar_bowling = 2 menubar_background = 'chooserbackground' movebar_background = 'movebackground' panel_background = 'panelbackground' start_button = 'startbutton' card_pool = 'card_pool' movebar_card_fresh_time = 6000 card_move_time = 60 #plant info plant_image_rect = 'plant_image_rect' car = 'car' sun = 'sun' sunflower = 'sunflower' peashooter = 'peashooter' snowpeashooter = 'snowpea' wallnut = 'wallnut' cherrybomb = 'cherrybomb' threepeashooter = 'threepeater' repeaterpea = 'repeaterpea' chomper = 'chomper' cherry_boom_image = 'boom' puffshroom = 'puffshroom' potatomine = 'potatomine' squash = 'squash' spikeweed = 'spikeweed' jalapeno = 'jalapeno' scaredyshroom = 'scaredyshroom' sunshroom = 'sunshroom' iceshroom = 'iceshroom' hypnoshroom = 'hypnoshroom' wallnutbowling = 'wallnutbowling' redwallnutbowling = 'redwallnutbowling' plant_health = 5 wallnut_health = 30 wallnut_cracked1_health = 20 wallnut_cracked2_health = 10 wallnut_bowling_damage = 10 produce_sun_interval = 7000 flower_sun_interval = 22000 sun_live_time = 7000 sun_value = 25 ice_slow_time = 2000 freeze_time = 7500 icetrap = 'icetrap' #plant card info card_sunflower = 'card_sunflower' card_peashooter = 'card_peashooter' card_snowpeashooter = 'card_snowpea' card_wallnut = 'card_wallnut' card_cherrybomb = 'card_cherrybomb' card_threepeashooter = 'card_threepeashooter' card_repeaterpea = 'card_repeaterpea' card_chomper = 'card_chomper' card_puffshroom = 'card_puffshroom' card_potatomine = 'card_potatomine' card_squash = 'card_squash' card_spikeweed = 'card_spikeweed' card_jalapeno = 'card_jalapeno' card_scaredyshroom = 'card_scaredyshroom' card_sunshroom = 'card_sunshroom' card_iceshroom = 'card_iceshroom' card_hypnoshroom = 'card_hypnoshroom' card_redwallnut = 'card_redwallnut' #bullet info bullet_pea = 'peanormal' bullet_pea_ice = 'peaice' bullet_mushroom = 'bulletmushroom' bullet_damage_normal = 1 #zombie info zombie_image_rect = 'zombie_image_rect' zombie_head = 'zombiehead' normal_zombie = 'zombie' conehead_zombie = 'coneheadzombie' buckethead_zombie = 'bucketheadzombie' flag_zombie = 'flagzombie' newspaper_zombie = 'newspaperzombie' boomdie = 'boomdie' losthead_health = 5 normal_health = 10 flag_health = 15 conehead_health = 20 buckethead_health = 30 newspaper_health = 15 attack_interval = 1000 zombie_walk_interval = 70 zombie_start_x = screen_width + 50 #state idle = 'idle' fly = 'fly' explode = 'explode' attack = 'attack' attacked = 'attacked' digest = 'digest' walk = 'walk' die = 'die' cry = 'cry' freeze = 'freeze' sleep = 'sleep' #level state choose = 'choose' play = 'play' #background background_day = 0 background_night = 1
state/main.py
from . import tool from . import constants as c from .state import mainmenu, screen, level def main(): game = tool.control() state_dict = {c.main_menu: mainmenu.menu(), c.game_victory: screen.gamevictoryscreen(), c.game_lose: screen.gamelosescreen(), c.level: level.level()} game.setup_states(state_dict, c.main_menu) game.main()
主执行文件main.py
import pygame as pg from source.main import main if __name__=='__main__': main() pg.quit()
到此这篇关于基于python实现经典植物大战僵尸游戏的文章就介绍到这了,更多相关python植物大战僵尸内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!