import pygame, sys, json from enemy import Enemy from world import World from turret import Turret from button import Button import constants as c # setup pygame.init() clock = pygame.time.Clock() # game window screen = pygame.display.set_mode((c.SCREEN_WIDTH + c.SIDE_PANEL, c.SCREEN_HEIGHT)) pygame.display.set_caption("Tower Defence") placing_turrets = False # load images enemy_image = pygame.image.load("assets/images/enemies/enemy_1.png").convert_alpha() map_image = pygame.image.load("levels/level.png").convert_alpha() turret_sheet = pygame.image.load("assets/images/turrets/turret_1.png") cursor_turret = pygame.image.load("assets/images/turrets/cursor_turret.png").convert_alpha() buy_turret_image = pygame.image.load("assets/images/buttons/buy_turret.png").convert_alpha() cancel_image = pygame.image.load("assets/images/buttons/cancel.png").convert_alpha() # load json data for level with open("levels/level.tmj") as file: world_data = json.load(file) def create_turret(mouse_pos): mouse_tile_x = mouse_pos[0] // c.TILE_SIZE mouse_tile_y = mouse_pos[1] // c.TILE_SIZE # calculate the sequential number of the tile mouse_tile_num = (mouse_tile_y * c.COLS) + mouse_tile_x # check if that tile is grass if world.tile_map[mouse_tile_num] == 7: # check that there isn't already a turret there space_is_free = True for turret in turret_group: if (mouse_tile_x, mouse_tile_y) == (turret.tile_x, turret.tile_y): space_is_free = False if space_is_free == True: new_turret = Turret(cursor_turret, mouse_tile_x, mouse_tile_y) turret_group.add(new_turret)- # create world world = World(world_data, map_image) world.process_data() # create groups enemy_group = pygame.sprite.Group() turret_group = pygame.sprite.Group() enemy = Enemy(world.waypoints, enemy_image) enemy_group.add(enemy) # create buttons turret_button = Button(c.SCREEN_WIDTH + 30, 120, buy_turret_image, True) cancel_button = Button(c.SCREEN_WIDTH + 50, 180, cancel_image, True) run = True while run: clock.tick(c.FPS) # UPDATING SECTION enemy_group.update() # DRAWING SECTION screen.fill((255, 255, 255)) world.draw(screen) enemy_group.draw(screen) turret_group.draw(screen) if turret_button.draw(screen): placing_turrets = True if placing_turrets == True: # show cursor turret cursor_rect = cursor_turret.get_rect() cursor_pos = pygame.mouse.get_pos() cursor_rect.center = cursor_pos if cursor_pos[0] <= c.SCREEN_WIDTH: screen.blit(cursor_turret, cursor_rect) if cancel_button.draw(screen): placing_turrets = False # event handler for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: mouse_pos = pygame.mouse.get_pos() # check if mouse on game area if mouse_pos[0] < c.SCREEN_WIDTH and mouse_pos[1] < c.SCREEN_HEIGHT: if placing_turrets == True: create_turret(mouse_pos) pygame.display.flip() pygame.quit() sys.exit()