def game_loop(): contestants = [ Player('Rick', 100), Player('Morty', 10), Player('Summer', 25), Player('Beth', 50), Player('Jerry', 3), Alien('Amish Cyborg', 40, 2) ] print('The contestants are {}'.format(contestants)) print('The battle begins...') while len(contestants) > 1: p1 = random.choice(contestants) p2 = random.choice(contestants) print('{} attacks {}'.format(p1, p2)) if p1.attack() > p2.defense(): print('{} is defeated'.format(p2)) contestants.remove(p2) else: print('{} blocks'.format(p2)) winner = contestants[0] print('{} wins the battle'.format(winner))
def __init__(self, win, net, username): self.menu = False self.grid = False self.win = win self.net = net #generate and save map # new_map = Map() # new_map.generate_map('random', False) self.bg = pygame.image.load('sprites/background.jpg').convert() #load first shuffled map from server self.current_map = 0 Map.load(self.net.maps[self.current_map]) #create client player object and assign colour based on ID, username from input, map from server self.ash = Player( RandomNode(Map.nodes).node, self.net.playerID, username, self.current_map) #other player objects p2, p3, p4, p5 = None, None, None, None self.players = [p2, p3, p4, p5] self.bikes = [Bike() for i in range(config.bikes)] self.mushrooms = [Mushroom() for i in range(config.mushrooms)] WeaponStatus.set_locations(self.bikes, self.mushrooms) music = pygame.mixer.music.load(config.theme) pygame.mixer.music.set_volume(0.5) pygame.mixer.music.play(-1) self.ash.ID = self.net.playerID
def play(): skeleton = Monster('Skeleton', 50, 10, 0) player = Player() skeleton.attack(player) player.attack(skeleton) player.attack(skeleton) player.attack(skeleton) player.attack(skeleton)
def create_player(): # create player decision = input("Create a new player? YES/NO").lower() if decision == 'yes': new_player = Player.Player() new_player.generate_character() # player.type_name() new_player.generate_name() new_player.generate_equipment() print(new_player) return new_player elif decision == 'no': print("No player, no game!") return False else: create_player()
def get_player_data(ash, net, players, bikes, mushrooms): '''get player data from server and map data to local player objects''' attrs = net.send(ash.attributes()) #return attributes of other players for i in range(len(players)): '''ith player should map to ith attribute on server as players are added in order which clients connect. If client DCs and reconnects, they are issued the same player id''' a = attrs[i] #create new player instance if: #1) we haven't already created an instance #2) they have an ID (they are connected to server) if not players[i] and a['ID'] != None: print(f'{a["username"]} connected.') players[i] = Player((a['x'], a['y']), a['ID']) #update (in place) the ith player from server elif players[i]: players[i].x, players[i].y = a['x'], a['y'] players[i].left, players[i].right, players[i].up, players[ i].down = a['L'], a['R'], a['U'], a['D'] players[i].standing, players[i].walk_count = a['standing'], a[ 'walk count'] players[i].hit_slow, players[i].bike, players[i].mushroom = a[ 'hit slow'], a['bike'], a['mushroom'] players[i].inventory = a['inventory'] players[i].stats = a['stats'] players[i].killed = a['killed'] players[i].dead = a['dead'] players[i].ID = a['ID'] players[i].username = a['username'] players[i].map = a['map'] #change local map if the host has changed the map if players[i].ID == 0 and players[i].map != ash.map: ash.map = players[i].map Map.load(net.maps[players[i].map]) WeaponStatus.set_locations(bikes, mushrooms)
# json1_str = json1_file.read() # json1_data = json.loads(json1_str) data_file = open("testmap.py") data_str = data_file.read() # game_manager = Manager() # list of vars filled by exec data = None start = None exec(data_str) game_manager.hack_map(data, start) game_manager.player = Player() # only use this when not hacking # game_manager.make_map(json1_data) print( """You wake up, badly bruised, freezing and with barely enough energy to move. Getting up, you inspect your surroundings...""") # debug # print(game_manager.location.name) last_command = None while True: # enemies only attack after a non-inspect action if not (last_command is None or last_command.root == "inspect"):
fpsClock = pygame.time.Clock() # programIcon = pygame.image.load(icon_img) background = pygame.transform.scale(pygame.image.load(background_img), (990, 660)) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Zoe Town") # pygame.display.set_icon(programIcon) # loot_sound = pygame.mixer.Sound("crash.wav") # score base_font = pygame.font.Font(None, 32) color = pygame.Color("orange") # Initializing sprites and loot player = Player(player_img) gem1 = Gem(gems[0], screen) gem2 = Gem(gems[1], screen) villain = Villain(monster_img) # Initializing joystick try: joystick = pygame.joystick.Joystick(0) joystick.init() except: print("no joystick") # setting up game loop running = True while running:
import random from card_book import Card, Deck from characters import Player from actions import deal, game_on, dealer_on from actions import bank # GAME LOGIC STARTS HERE Player1 = Player(input("Enter you Name:\n")) Dealer1 = Player('Dealer') champ = True # player_turn = game_on(Player1) # dealer_turn = Dealer1.current_hand[0].value + Dealer1.current_hand[1].value game_turns = 0 while True: if game_turns == 0: Current_Bank = bank( int(input("How much would you like to play with? \n"))) print(f"{Player1.name} is entering the game with ${Current_Bank}\n") while True: print(deal(Player1, Dealer1)) bet = int(input("What is your bet for this hand?\n")) if bet > Current_Bank: print("Insufficient Amount, Please enter new amount to bet!") bet = int(input("What is your bet for this hand?\n")) player_turn = game_on(Player1, Dealer1) dealer_hand = Dealer1.current_hand[0].value + Dealer1.current_hand[ 1].value
def setup(self): if G.SINGLEPLAYER: try: # TODO: create world menu G.SAVE_FILENAME = "world" start_server(internal=True) sock = socket.socket() time.sleep(2) sock.connect(("localhost", 1486)) except socket.error as e: #Otherwise back to the main menu we go return False except Exception as e: import traceback traceback.print_exc() return False else: try: #Make sure the address they want to connect to works ipport = G.IP_ADDRESS.split(":") if len(ipport) == 1: ipport.append(1486) sock = socket.socket() sock.connect((tuple(ipport))) except socket.error as e: #Otherwise back to the main menu we go return False self.init_gl() self.debug_text = TextWidget(self.window, 'Loading information...', 0, self.window.height - 300, 500, 300, visible=True, multi_line=True, readonly=True, font_name='Arial', font_size=8, text_color=(255, 255, 255, 255), background_color=(0, 0, 0, 0)) self.debug_text.write_escape("$$r") sky_rotation = -20.0 # -20.0 # TERRAIN_CHOICE = self.biome_generator.get_biome_type(sector[0], sector[2]) default_skybox = 'skydome.jpg' # if TERRAIN_CHOICE == G.NETHER: # default_skybox = 'skydome_nether.jpg' # else: # default_skybox = 'skybox.jpg' self.skydome = Skydome( 'resources/' + default_skybox, #'resources/skydome.jpg', 0.7, 100.0, sky_rotation, ) self.player_ids = {} # Dict of all players this session, indexes are their ID's [0: first Player on server,] self.focus_block = Block(width=1.05, height=1.05) self.earth = vec(0.8, 0.8, 0.8, 1.0) self.white = vec(1.0, 1.0, 1.0, 1.0) self.polished = GLfloat(100.0) self.crack_batch = pyglet.graphics.Batch() # if G.DISABLE_SAVE and world_exists(G.game_dir, G.SAVE_FILENAME): # open_world(self, G.game_dir, G.SAVE_FILENAME) self.world = World() self.packetreceiver = PacketReceiver(self.world, self, sock) self.world.packetreceiver = self.packetreceiver G.CLIENT = self.packetreceiver self.packetreceiver.start() #Get our position from the server self.packetreceiver.request_spawnpos() #Since we don't know it yet, lets disable self.update, or we'll load the wrong chunks and fall self.update_disabled = self.update self.update = lambda dt: None #We'll re-enable it when the server tells us where we should be self.player = Player(game_mode=G.GAME_MODE) self.item_list = ItemSelector(self, self.player, self.world) self.inventory_list = InventorySelector(self, self.player, self.world) self.item_list.on_resize(self.window.width, self.window.height) self.inventory_list.on_resize(self.window.width, self.window.height) self.text_input = TextWidget(self.window, '', 0, 0, self.window.width, visible=False, font_name=G.CHAT_FONT) self.text_input.push_handlers(on_toggled=self.on_text_input_toggled, key_released=self.text_input_callback) self.chat_box = TextWidget(self.window, '', 0, self.text_input.y + self.text_input.height + 50, self.window.width // 2, height=min(300, self.window.height // 3), visible=False, multi_line=True, readonly=True, font_name=G.CHAT_FONT, text_color=(255, 255, 255, 255), background_color=(0, 0, 0, 100), enable_escape=True) self.camera = Camera3D(target=self.player) if G.HUD_ENABLED: self.label = pyglet.text.Label( '', font_name='Arial', font_size=8, x=10, y=self.window.height - 10, anchor_x='left', anchor_y='top', color=(255, 255, 255, 255)) self.debug_text.write_escape("$$D") pyglet.clock.schedule_interval_soft(self.world.process_queue, 1.0 / G.MAX_FPS) pyglet.clock.schedule_interval_soft(self.world.hide_sectors, 10.0, self.player) return True
def _create_player(name, curr_pos): """Generates a Player object for the user to move around """ return Player(name=name, curr_pos=curr_pos)
# initialize pygame pygame.init() # initialize game window screen = pygame.display.set_mode(size=(PAGE_WIDTH, PAGE_HEIGHT)) # set caption of game window pygame.display.set_caption('Space Invaders') # load icon for game icon = pygame.image.load('./images/ufo.png') # set icon for the game pygame.display.set_icon(icon) # player - p1 = Player(x=PLAYER_X, y=PLAYER_Y, screen=screen, image_path="./images/space-invaders.png") # list of enemies - enemies = list() # make 2 rows for j in range(2): # of 10 enemies each for i in range(10): enemy = Enemy(x=((PAGE_WIDTH - 2 * PAGE_BORDER) // 11) * (i + 1), y=ENEMY_Y + j * ENEMY_START_HEIGHT, screen=screen, image_path="./images/spaceship.png", respawn_status=False) enemies.append(enemy)
def main(): pygame.init() pygame.running = True running = True routes = None # window for drawing on window_width = config.window_width window_height = config.window_height grid_spacing = config.grid_spacing win = pygame.display.set_mode( (window_width, window_height)) #width and height of window pygame.display.set_caption("Pokémon Crisis") bg = pygame.image.load('sprites/background.jpg').convert() oak = pygame.image.load('sprites/oak.png') new_map = Map() #use all objects, set specific number of grass tree and water objects new_map.generate_map(grass=20, trees=20, water=2) clock = pygame.time.Clock() ash = Player(choice(tuple(new_map.nodes))) font = pygame.font.SysFont('verdana', 10, False, True) path = Pathfinding(new_map.nodes, new_map.movement_cost_area) def redraw_gamewindow(): win.blit(bg, (0, 0)) #put picutre on screen (background) pygame.draw.rect(win, (200, 200, 200), (0, 0, window_width, window_height)) # # draw grid # for x in range(0,window_width,grid_spacing): #col # for y in range(0,window_height,grid_spacing): #row # pygame.draw.rect(win, (125,125,125), (x,y,grid_spacing,grid_spacing),1) Map.draw(win) if routes: # draw bfs route for x, y in routes['BFS']: pygame.draw.rect(win, (0, 0, 255), (x, y, grid_spacing, grid_spacing)) #draw dfs route for x, y in routes['DFS']: pygame.draw.rect(win, (0, 0, 100), (x, y, grid_spacing, grid_spacing)) # draw dijkstra route for x, y in routes['GBFS']: pygame.draw.rect(win, (255, 0, 0), (x, y, grid_spacing, grid_spacing)) #draw DA route for x, y in routes['DA']: pygame.draw.rect(win, (0, 255, 0), (x, y, grid_spacing, grid_spacing)) # draw A* route for x, y in routes['A*']: pygame.draw.rect(win, (100, 100, 100), (x, y, grid_spacing, grid_spacing)) # re-position oak if oob oak_x = target_x oak_y = target_y if oak_x > window_width - oak.get_width(): oak_x -= grid_spacing elif oak_y > window_height - oak.get_height(): oak_y -= grid_spacing win.blit(oak, (oak_x, oak_y)) ash.draw(win) pygame.display.update() #main event loop while running: clock.tick(9) #9 FPS for event in pygame.event.get( ): #get mouse positions, keyboard clicks etc if event.type == pygame.QUIT: #we pressed the exit button running = False if event.type == pygame.MOUSEBUTTONDOWN: target_x, target_y = event.pos[0], event.pos[1] routes = path.compute_all_paths(ash.x, ash.y, target_x, target_y) #move amongst available nodes #(no movement out of bounds and in object coordinates) #movement cost in grass / water ash.move(new_map.objs_area, new_map.movement_cost_area) redraw_gamewindow() pygame.quit()
from Magic import Spell from Map import * from Menu import Menu from characters import Player from inventory import * def gen_spells(): # generates the spells from txt file and put them in list, to be used by player filepath = 'spells.txt' file = open(filepath, "r") for line in file: split = line.split(";") spellss.append(Spell(split[0], split[1], split[2], int(split[3]))) player = Player() map = Map() # the map for the game mobkilled = 0 menu = Menu() # the menu game_on = False spellss = [] # contains all the spells gen_spells() inv = Inventory() inv.god_inventory() # player.inventory = inv #cheat, gives player all items in the game # player.equiped[2] = inv.items[len(inv.items -1 )] # gives player the cheat item for i in range(len(spellss)): # for now, the player starts with all the spellss player.spells.append(spellss[i])
self.name = "Where are we now" # Position of Where are we now tile super().__init__(x, y) class Hooligan(MapTile): """Lake location containing easy difficutly fish""" def __init__(self, x, y): self.name = "Hooligan" # Position of Hooligan tile super().__init__(x, y) class Residential(MapTile): """Lake containing trader to obtain items""" def __init__(self, x, y): self.name = "Residential" # Position of Residential tile super().__init__(x, y) # The map world_map = [[None, None, Ethereal(2, 0), None, None], [None, None, None, None, None], [Juliot(0, 2), None, None, None, Kytersize(4, 2)], [None, None, None, None, None], [None, Where(1, 4), None, Hooligan(3, 4), None], [None, None, Residential(2, 5), None, None], [None, None, None, Player(3, 6), None]]
for pig, skill in choice_dict.items(): result += f"-- {pig} with a skill: {skill.name}\n" else: for pig, skill in choice_dict.items(): result += f"-- {pig}: {skill}\n" return result player_name = input("What is your name? \n>> ") print(f"Yo {player_name}! \n") chosen_skills = player_type_choice() # Create player player = Player(name=player_name, hp=[30, 30], dmg=[5, 15], skills=chosen_skills) # Play game while True: play_or_stats = input("If you want check your stats type 'stats'. \ Otherwise type 'play'\n>> ") if play_or_stats.lower() == "stats": player.get_stats() print(MONSTERS_DICT) elif play_or_stats.lower() == "play": event = create_random_event(player, BATTLE_DESCRIPTS, MONSTERS_DICT, OTHER_EVENTS) if not event: player.get_stats() exit("You won the game!") # Futureproofing
### Let's Game to be started ### ################################ pg.init() pg.display.set_caption('Hello pygame') mainScreen = pg.display.set_mode((WIDTH, HEIGHT)) clock = pg.time.Clock() imge = pg.image.load(os.path.join(IMG_FOLDER, 'colored_packed.png')).convert_alpha() imgKit = [] for i in range(22): for j in range(48): imgKit.append(imge.subsurface(j * 16, i * 16, 16, 16)) player1 = Player(16, 16, imgKit[25]) brickRectsList = [] bricksList = [] wallGroup, prixGroup, enemyGroup = worldCreate(levels[0]) # Цикл игры game = True while game: # Keep tempo clock.tick(FPS) # check for events for e in pg.event.get(): # check for closing window if e.type == pg.QUIT or (e.type == pg.KEYDOWN and e.key == pg.K_ESCAPE):
def __init__(self, screen): self.screen = screen self.objects = [] self.game_messages = [] self.game_state = Game_States.none self.map = [] self.characters = [] self.text_background = pygame.Surface((config.screen_width, 180)) self.scene_surface = pygame.Surface((config.screen_width, config.screen_height)) self.message_count = 0 self.grid_index_X = int(config.screen_width / config.scale) - 1 self.grid_index_Y = int(config.screen_height / config.scale) self.main_map = pygame.Surface((config.screen_width, config.screen_height)) self.game_map = [[Map_Tile(True, False) for y in range(0, config.screen_height)] for x in range(0, config.screen_width)] for x in range(5, 12): for y in range(5, 7): self.game_map[x][y].movement = False self.game_map[x][y].movement = False self.player = Player(self.screen, self.game_map) # initialise player # initialise first tester npc self.tester_npc = CharacterController("NPC1", 7, 8, self.screen, config.NPC01IDLE, self.game_map, config.NPC01LEFT, config.NPC01RIGHT, config.NPC01BACK, config.NPC01FRONT, config.NPC01IDLE) self.message1 = self.tester_npc.text_to_speak(self.screen, "Hi there! How are you doing?", config.game_messages, (1 * config.scale, 9 * config.scale), config.black) self.message2 = self.tester_npc.text_to_speak(self.screen, "I like you very much!", config.game_messages, (1 * config.scale, 9 * config.scale), config.black) self.my_creatures = [creature.charmander] # initialise the route creatures self.route1 = [creature.bulbasaur, creature.squirtle, creature.charmander] # TODO: find out a better way to do this # sets the tree objects # self.tester_npc2 = CharacterController("NPC2", 3, 3, self.screen, config.NPC02, self.game_map) self.treesXb = [Obstacles(config.tree01, x, 11, self.player.group) for x in range(self.grid_index_X)] self.treesXt = [Obstacles(config.tree01, x, 0, self.player.group) for x in range(self.grid_index_X)] self.treesYl = [Obstacles(config.tree01, 0, y, self.player.group) for y in range(self.grid_index_Y)] self.treesYr = [Obstacles(config.tree01, self.grid_index_X, y, self.player.group) for y in range(self.grid_index_Y)] self.tall_grass = [[Non_Obstacle_Tiles(config.tallgrass01, x, y, self.player) for x in range(9, self.grid_index_X)] for y in range(1, 4)] self.trees = [self.treesXb, self.treesXt, self.treesYl, self.treesYr] # adds the tree border to the game for x in range(self.grid_index_X): self.game_map[x][self.grid_index_Y - 1].blocked = True self.game_map[x][0].blocked = True for y in range(self.grid_index_Y): self.game_map[0][y].blocked = True self.game_map[self.grid_index_X][y].blocked = True # scene mechanics self.scene = Scene(self.scene_surface) self.scene.set_background(config.battle_background, self.scene_surface)
def dequeue_packet(self): with self.lock: packetid, packet = self.world.sector_packets.popleft() if packetid == 1: # Entire Sector blocks, sectors = self.world, self.world.sectors secpos = struct.unpack("iii", packet[:12]) sector = sectors[secpos] cx, cy, cz = sector_to_blockpos(secpos) fpos = 12 exposed_pos = fpos + 1024 for x in range(cx, cx+8): for y in range(cy, cy+8): for z in range(cz, cz+8): read = packet[fpos:fpos+2] fpos += 2 unpacked = structuchar2.unpack(read) if read != null2 and unpacked in BLOCKS_DIR: position = x,y,z try: blocks[position] = BLOCKS_DIR[unpacked] if blocks[position].sub_id_as_metadata: blocks[position] = type(BLOCKS_DIR[unpacked])() blocks[position].set_metadata(0) except KeyError: main_blk = BLOCKS_DIR[(unpacked[0], 0)] if main_blk.sub_id_as_metadata: # sub id is metadata blocks[position] = type(main_blk)() blocks[position].set_metadata(unpacked[-1]) sector.append(position) if packet[exposed_pos:exposed_pos+1] == b"1": blocks.show_block(position) exposed_pos += 1 if secpos in self.world.sector_queue: del self.world.sector_queue[secpos] #Delete any hide sector orders elif packetid == 2: # Blank Sector self.world.sectors[struct.unpack("iii", packet)] = [] elif packetid == 3: # Add Block self.world._add_block(struct.unpack("iii", packet[:12]), BLOCKS_DIR[struct.unpack("BB", packet[12:])]) elif packetid == 4: # Remove Block self.world._remove_block(struct.unpack("iii", packet)) elif packetid == 5: # Chat Print self.controller.write_line(packet[:-4].decode('utf-8'), color=struct.unpack("BBBB", packet[-4:])) if not self.controller.text_input.visible: self.controller.chat_box.visible = True pyglet.clock.unschedule(self.controller.hide_chat_box) pyglet.clock.schedule_once(self.controller.hide_chat_box, G.CHAT_FADE_TIME) elif packetid == 6: # Inventory player = self.controller.player caret = 0 for inventory in (player.quick_slots.slots, player.inventory.slots, player.armor.slots): for i in range(len(inventory)): id_main, id_sub, amount = struct.unpack("HBB", packet[caret:caret+4]) caret += 4 if id_main == 0: continue durability = -1 if id_main >= G.ITEM_ID_MIN and (id_main, id_sub) not in G.ITEMS_DIR: #The subid must be durability durability = id_sub * G.ITEMS_DIR[(id_main, 0)].durability // 255 id_sub = 0 inventory[i] = ItemStack(type=BlockID(id_main, id_sub), amount=amount, durability=durability) self.controller.item_list.update_items() self.controller.inventory_list.update_items() elif packetid == 7: # New player connected plyid, name = struct.unpack("H", packet[:2])[0], packet[2:].decode('utf-8') if plyid not in self.controller.player_ids: self.controller.player_ids[plyid] = Player(username=name, local_player=False) elif name == '\0': del self.controller.player_ids[plyid] elif packetid == 8: # Player Movement ply = self.controller.player_ids[struct.unpack("H", packet[:2])[0]] ply.momentum = struct.unpack("fff", packet[2:14]) ply.position = struct.unpack("ddd", packet[14:]) elif packetid == 9: # Player Jump self.controller.player_ids[struct.unpack("H", packet)[0]].dy = 0.016 elif packetid == 10: # Update Tile Entity try: self.world[struct.unpack("iii", packet[:12])].update_tile_entity(packet[12:]) except Exception as e: warn(str(e)) elif packetid == 255: # Spawn Position self.controller.player.position = struct.unpack("iii", packet[:12]) packet = packet[12:] packet, seed = extract_string_packet(packet) self.world.biome_generator = BiomeGenerator(seed) #Now that we know where the player should be, we can enable .update again self.controller.update = self.controller.update_disabled else: warn("Received unknown packetid %s, there's probably a version mismatch between client and server!" % packetid)
from characters import Player from obstacles import Stone import os import pygame ###Resources### resources = "resources" background_path = os.path.join(resources, "background.jpg") ###Backgrounds### background = pygame.image.load(background_path) ###Characters### #alucard_path = os.path.join(resources, "images.png") #img = pygame.image.load(alucard_path) img = pygame.Surface((32, 48)) img.fill((255, 0, 0)) alucard = Player(image=img, pos=(20, 200), walk=10, jump_height=10) ###Obstacles### stones = [] for i in range(10): s = Stone() stones.append(s)
# CS 30 # Period 4 # Date : 12/9/2019 # Krutik Rana # Program description : Players inventory and command to heal player from characters import Player # Creates and instance of player to be used player = Player(None, None) def inventory(): """Commands to access the characters inventory""" # While loop to continously play while True: # Print statement detailing how to go to the last menu print('\ntype q to go back to previous menu') # Aquiring user input for what they want to access of the inventory user = input('action: ') # Making the user input all lower case to match if and elif statements user = user.lower() # Checks to see if the user typed weapon if user == 'backpack': # Prints the current inventory of the player player.print_inventory() # Checks to see if user typed heal elif user == 'heal': # Bring up the heal menu player.heal() # Checks to see if user typed q elif user == 'q':
class Game: """ Class used to play the game. """ # We start Pygame pygame.init() pygame.font.init() # We prepare the font of our caption to indicate how many items we picked # up myfont = pygame.font.SysFont(None, 40) # We display the window square_window = pygame.display.set_mode(WINDOW_DIMENSIONS) # We make the labyrinth labyrinth = Labyrinth(FLOOR_IMAGE, WALL_IMAGE, LEVEL_FILE) labyrinth.initialize_labyrinth(square_window) # We initialize McGyver and the gatekeeper mac = Player(PLAYER_PIC, labyrinth.PLAYER_COORDINATES) gatekeeper = Boss(BOSS_PIC, labyrinth.BOSS_COORDINATES) # We initialize the three components of the serynge needle = Items(NEEDLE_PIC, labyrinth) tube = Items(TUBE_PIC, labyrinth) ether = Items(ETHER_PIC, labyrinth) # Displays Items def display_items(self, item): self.square_window.blit(item.image, item.coordinates) # Display characters def display_character(self, character): self.square_window.blit(character.head, character.coordinates) def main(self): """ Function that runs the game """ is_running = True # Loop of the game while is_running: # Displays the game self.labyrinth.display_labyrinth(self.square_window) self.display_character(self.mac) self.display_character(self.gatekeeper) for item in Items.LIST_OF_ITEMS: self.display_items(item) pygame.display.flip() # What happens when we meet the gatekeeper if self.mac.coordinates in self.labyrinth.FIGHT_POSITION: if self.mac.count == 3: self.mac.neutralize( self.labyrinth, self.gatekeeper, self.labyrinth.EXIT_POSITION) else: self.gatekeeper.lose(self.mac, CARCASS) self.square_window.blit( self.mac.head, self.mac.coordinates) is_running = False # Reaching the exit position if self.mac.coordinates == self.labyrinth.EXIT_POSITION: self.mac.victorious = True is_running = False # Events detection for event in pygame.event.get(): if event.type == QUIT: is_running = False if event.type == KEYDOWN: x, y = self.mac.move(event) # Square where we can walk, or with a serynge component, or # wall so we can't use it if (x, y) in [ item.coordinates for item in Items.LIST_OF_ITEMS]: self.mac.count += 1 Items.LIST_OF_ITEMS = [ item for item in Items.LIST_OF_ITEMS if item.coordinates != ( x, y)] moving = True print(self.mac.count) else: moving = False if self.labyrinth.reachable((x / 40, y / 40)): moving = True # Moving means replace the position of Mac by en empty square # Moving also means replacing an empty square by the # position of Mac if moving: self.labyrinth.void.append(self.mac.coordinates) self.mac.coordinates = (x, y) txt = self.myfont.render( str(self.mac.count) + "items picked up!", False, (255, 255, 255)) self.square_window.blit(txt, (0, 0)) pygame.display.flip() # Outcome of the game if self.mac.victorious: path = VICTORY else: path = FAILURE # Showing the outcome notification notification = pygame.image.load(path).convert() self.square_window.blit(notification, (100, 300)) pygame.display.flip() # Waiting 1 seconds before closing the window sleep(1)
def main(self): """ Main Program """ pygame.init() # Create the player player = Player(SpriteSheet('catman.png')) # Create all the levels level_list = [] level_list.append(levels.Level_01(player)) level_list.append(levels.Level_02(player)) # Set the current level & player position current_level_no = 0 current_level = level_list[current_level_no] active_sprite_list = pygame.sprite.Group() player.level = current_level player.rect.x = 340 player.rect.y = constants.SCREEN_HEIGHT - player.rect.height - 500 active_sprite_list.add(player) # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() start_ticks = pygame.time.get_ticks() #starter tick # -------- Main Program Loop ----------- while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == None: player.idle() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_a or event.key == pygame.K_LEFT: player.go_left() elif event.key == pygame.K_d or event.key == pygame.K_RIGHT: player.go_right() elif event.key == pygame.K_w or event.key == pygame.K_UP: player.jump() elif event.key == pygame.K_SPACE: if len(player.bullet_list) < 4: # Fire a bullet if the user clicks the mouse button bullet = Bullet(player) # Set the bullet so it is where the player is bullet.rect.x = player.rect.x + 10 bullet.rect.y = player.rect.y + 10 # Add the bullet to the lists player.bullet_list.add(bullet) # set what happens when player lets the key up elif event.type == pygame.KEYUP: if event.key == pygame.K_a or event.key == pygame.K_LEFT and player.change_x < 0: player.stop() elif event.key == pygame.K_d or event.key == pygame.K_RIGHT and player.change_x > 0: player.stop() # Update the player. active_sprite_list.update() player.bullet_list.update() # Update items in the level current_level.update() ydiff = 0 diff = 0 # if the player gets near the top, shift the world up (ydiff) if player.rect.top <= 20: ydiff = player.rect.top - 20 player.rect.top = 20 current_level.shift_world_y(ydiff) # if the player gets near the bottom, shift the world down (ydiff) if player.rect.bottom >= 550: ydiff = player.rect.bottom - 550 player.rect.bottom = 550 current_level.shift_world_y(ydiff) # If the player gets near the right side, shift the world left (-x) if player.rect.right >= 500: diff = player.rect.right - 500 player.rect.right = 500 current_level.shift_world(-diff) # If the player gets near the left side, shift the world right (+x) if player.rect.left <= 120: diff = 120 - player.rect.left player.rect.left = 120 current_level.shift_world(diff) # If the player gets to the end of the level, go to the next level current_position = player.rect.x + current_level.world_shift if current_position < current_level.level_limit: player.rect.x = 150 if current_level_no < len(level_list) - 1: current_level_no += 1 current_level = level_list[current_level_no] player.level = current_level player.stop() # IF the player falls, game done if player.rect.y + player.level.world_shift_y + 75 > constants.SCREEN_HEIGHT: done = True seconds = (pygame.time.get_ticks() - start_ticks) / 1000 #calculate how many seconds # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT current_level.draw(screen) active_sprite_list.draw(screen) player.bullet_list.draw(screen) font = pygame.font.SysFont(None, 25) showscore = font.render(f"Score: {player.score}", True, constants.BLACK) showclock = font.render(f"Time: {round(seconds,2)}", True, constants.BLACK) screen.blit(showscore, (10, 10)) screen.blit(showclock, (constants.SCREEN_WIDTH / 2, 10)) for crony in player.level.enemy_list: crony.draw(screen) for platform in player.level.platform_list: try: platform.draw(screen) except: pass # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.update() print(player.rect.x - player.level.world_shift, player.rect.y) # Be IDLE friendly. If you forget this line, the program will 'hang' # on exit. pygame.quit()