def __init__(self): logg.info("Init: Bot")
### # LOGGING ### from log import logg # ready to go! # logging convention: # logg.debug('') for variable passing # logg.info('') for standard initialization messages # logg.warn('') for known errors and caught exceptions # logg.error('') for something that shouldn't happen # logg.critical('') for breakage errors logg.info('Logging initialized.') ### # IMPORTS ### logg.info('Start imports.') # import sfml as sf # logg.info('SFML imported') from sfml import Clock, View, FloatRect, RenderWindow, VideoMode, Event, Texture, Color logg.info('SFML imported') from constants import PP_WIDTH, PP_HEIGHT, GAME_TITLE, GAME_VERSION, SCALE, BAR_HEIGHT
def main(): logg.info('Starting the main function') #Instancing, etc. main_view = View().from_rect( FloatRect(0, 0, PP_WIDTH, PP_HEIGHT + BAR_HEIGHT)) window = RenderWindow( VideoMode(PP_WIDTH * SCALE, (PP_HEIGHT + BAR_HEIGHT) * SCALE), GAME_TITLE + ' v.' + GAME_VERSION) window.framerate_limit = 61 window.view = main_view # INITIALIZE TEXTURES HERE OR AFTER \o/ TEXTURE_WALL = Texture.load_from_file('main/walls.png') TEXTURE_BAR = Texture.load_from_file('main/bar.png') TEXTURE_HUDWEAPONS = Texture.load_from_file('main/hud_weapons.png') TEXTURE_FACES = Texture.load_from_file('main/faces.png') TEXTURE_NUMBERS = Texture.load_from_file('main/numbers.png') TEXTURE_WEAPONS = Texture.load_from_file('main/weapons.png') TEXTURE_ENEMIES = Texture.load_from_file('main/test.png') #Create an instance for all game variables and loop functions # and set the level to TESTLEVEL game = Gameworld(TEXTURE_ENEMIES) game.create_dict_map() game.player.gamemap = game.current_level game.init_physics() game.physics.mob_bodies(game.entities) #prepare the hud hud = Hud(player=game.player, background=TEXTURE_BAR, faces=TEXTURE_FACES, hudweapons=TEXTURE_HUDWEAPONS, weapons=TEXTURE_WEAPONS, numbers=TEXTURE_NUMBERS) #prepare the wall textures wall_sprites = game.create_wall_sprite_list(TEXTURE_WALL) rays = Raycaster(player=game.player, sprites=wall_sprites, gamemap=game.current_level) #prepare other stuff player_action = '' running = True nofocus = False ## # MAIN LOOP ## logg.info('Main loop starting...') while running: #iterate events for event in window.iter_events(): if event.type == Event.CLOSED or player_action == 'quit': running = False if event.type == Event.LOST_FOCUS: nofocus = True elif event.type == Event.GAINED_FOCUS: nofocus = False if event.type == Event.KEY_RELEASED: if game.player.bob > 0: #level the headbobbing game.player.bob -= .5 elif game.player.bob < 0: game.player.bob += .5 game.player.strafing = False #disable speed limiter for moving in 2 axii window.clear(Color(235, 235, 235, 255)) #clear the window of everything for sprite in wall_sprites: #draw walls window.draw(sprite) #draw entities here for entity in game.entities: if entity.visible == True: for sprite_slice in entity.sprite: window.draw(sprite_slice) hud.display(window) #draw the hud debug_txt = text('[' + str(draw_fps(frame)) + '] ' + str("{0:.2f}".format(game.player.ux)) + '(' + str(game.player.x) + '),' + str("{0:.2f}".format(game.player.uy)) + '(' + str(game.player.y) + '):' + str(game.player.heading), style=1) window.draw(debug_txt) wall_sprites = rays.texture_slices( rays.cast_rays(), wall_sprites, game.player.bob) #determine which walls to display #determine wich entities to display and prepare for entity in game.entities: #calculate the distance of entities to the player entity.distance_to_player(game.player) # print(str(round(entity.distance, 2)) + " " + str(entity.x) + "," + str(entity.y)) game.entities.sort(key=lambda x: x.distance, reverse=True) #sort entities based on the distance for entity in game.entities: entity.set_sprite_for_display(game.player, rays.distances) ### # TIMERS ### if game.player.attack_delay > 0 and game.player.attack == True: game.player.attack_delay -= 1 elif game.player.attack == True and game.player.attack_delay == 0: game.player.attack = False game.player.attack_delay = 2 elif game.player.attack == False and game.player.attack_delay > 0: game.player.attack_delay -= 1 if len(game.doors) != 0: # print('lol doors') for door in game.doors: # print(door.openess) state = door.open_close() # print(state) if state == 'done': # print('removing doors') game.doors.remove(door) game.physics.world.ClearForces() if not nofocus: player_action = game.handle_keys() #player input game.physics.world.Step(1.0 / 60.0, 10, 8) game.player.update_position() for entity in game.entities: entity.update_position() window.display() #blit to window window.close() logg.info('Terminating. Have a nice day.') logg.info('Average FPS: %s', round(average_fps / all_frames, 2))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Gameworld initialized.') import math from tile import Tile from door import Door from player import Player from weapons import Weapons from physics import Physics from entity import Entity from constants import PLAYER_SPEED, TURN_SPEED, PP_HEIGHT, PP_WIDTH, HEAD_BOB # from __main__ import TEXTURE_ENEMIES from sfml import Keyboard, IntRect, Sprite, Event TESTLEVEL = [['#', ']', '[', '=', ']', '#', '#', '#', '#', '#', '#'], [']', '.', '.', '.', '.', '#', '.', '.', '$', '.', '#'], ['#', '.', '$', '.', '.', '$', '.', '.', '$', '.', '#'], ['#', '.', '.', '.', '.', '#', '.', '.', '.', '.', '#'],
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Player initialized.') from math import sin, cos, radians, degrees import Box2D as b2 class Player(object): """The player. Should be ok to reuse for the main thing """ def __init__(self, gamemap, weapon, x=4, y=4, heading=180, deck=1, hp=100, score=0): self.x = x #x and y are the grid coordinates self.y = y self.ux = x + .5 #ux and uy are the unit coordinates self.uy = y + .5 self.heading = heading self.gamemap = gamemap self.deck = deck
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info("Player initialized.") from math import sin, cos, radians, degrees import Box2D as b2 class Player(object): """The player. Should be ok to reuse for the main thing """ def __init__(self, gamemap, weapon, x=4, y=4, heading=180, deck=1, hp=100, score=0): self.x = x # x and y are the grid coordinates self.y = y self.ux = x + 0.5 # ux and uy are the unit coordinates self.uy = y + 0.5 self.heading = heading self.gamemap = gamemap self.deck = deck self.hp = hp self.weapon = weapon self.score = score self.attack = False self.attack_delay = 0 self.body = None self.bob = 0
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Entity class initialized.') from sfml import IntRect, Sprite, Color from math import sqrt, atan2, degrees, cos, radians from constants import PP_HEIGHT, PP_WIDTH, PP_DISTANCE, FOV, ANGLE_SHIFT class Entity(object): """Any and all entities that are displayed in the world. Barrels, enemies, goodies... """ def __init__(self, x, y, texture, sprite_x, sprite_y): self.x = x self.y = y self.ux = x + .5 self.uy = y + .5 self.sprite = gen_sprite_slices(texture, sprite_x, sprite_y) self.distance = 0 self.visible = False self.body = None def distance_to_player(self, player): self.distance = sqrt((player.ux - self.ux)**2 + (player.uy - self.uy)**2)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Physics initialized.') import Box2D as b2 from math import radians class Physics(object): """Class containing all the physics calculations.""" def __init__(self, player, level, level_width, level_height): worldAABB = b2.b2AABB() worldAABB.upperBound = (.5, .5) worldAABB.lowerBound = (level_width, level_height) gravity = (0, 0) doSleep = True self.world = b2.b2World(gravity, doSleep) wall_shape = b2.b2PolygonShape() wall_shape.SetAsBox(.5, .5) wall_fixture = b2.b2FixtureDef() wall_fixture.shape = wall_shape wall_fixture.density = 5.0 wall_fixture.friction = 0.5
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('HUD controller initialized.') from sfml import Sprite, IntRect from constants import PP_HEIGHT class Hud(object): """HUD controller.""" def __init__(self, player, background, faces, hudweapons, weapons, numbers): self.player = player self.background = Sprite(background) self.background.position = 0, PP_HEIGHT + 1 self.face = Sprite(faces) self.face.position = 116, 205 self.face.scale = 2 / 3, 2 / 3 self.hudweapon = Sprite(hudweapons) self.hudweapon.position = 251, 205 self.weapon = Sprite(weapons) # self.weapon.position = 112, 105 #for x1.5 # self.weapon.position = 96, 73 #for x2
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Weapons initialized.') class Weapons(object): """Weapons to be used by the player.""" def __init__(self, ident, ammo = 0, enabled = 0): self.ident = ident self.ammo = ammo self.enabled = enabled
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info("Gameworld initialized.") import math from tile import Tile from door import Door from player import Player from weapons import Weapons from physics import Physics from entity import Entity from constants import PLAYER_SPEED, TURN_SPEED, PP_HEIGHT, PP_WIDTH, HEAD_BOB # from __main__ import TEXTURE_ENEMIES from sfml import Keyboard, IntRect, Sprite, Event TESTLEVEL = [ ["#", "]", "[", "=", "]", "#", "#", "#", "#", "#", "#"], ["]", ".", ".", ".", ".", "#", ".", ".", "$", ".", "#"], ["#", ".", "$", ".", ".", "$", ".", ".", "$", ".", "#"],
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('HUD controller initialized.') from sfml import Sprite, IntRect from constants import PP_HEIGHT class Hud(object): """HUD controller.""" def __init__(self, player, background, faces, hudweapons, weapons, numbers): self.player = player self.background = Sprite(background) self.background.position = 0, PP_HEIGHT+1 self.face = Sprite(faces) self.face.position = 116, 205 self.face.scale = 2/3, 2/3 self.hudweapon = Sprite(hudweapons) self.hudweapon.position = 251, 205 self.weapon = Sprite(weapons) # self.weapon.position = 112, 105 #for x1.5 # self.weapon.position = 96, 73 #for x2 self.weapon.position = 104, 89
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Raycaster initialized.') from math import cos, sin, radians from sfml import IntRect, Color from constants import PP_DISTANCE, ANGLE_SHIFT, FOV, PP_WIDTH, PP_HEIGHT class Raycaster(object): """The main raycasting class. Instance with a list of sprites, map and the player instance""" def __init__(self, player, sprites, gamemap): self.player = player self.sprites = sprites self.gamemap = gamemap self.distances = [] def cast_rays(self): alpha = self.player.heading - FOV/2 if alpha < 0: alpha += 360 columns = [] self.distances = [] for index in range(PP_WIDTH): #figure out the vector from the angle
def main(): logg.info("Starting the main function") # Instancing, etc. main_view = View().from_rect(FloatRect(0, 0, PP_WIDTH, PP_HEIGHT + BAR_HEIGHT)) window = RenderWindow( VideoMode(PP_WIDTH * SCALE, (PP_HEIGHT + BAR_HEIGHT) * SCALE), GAME_TITLE + " v." + GAME_VERSION ) window.framerate_limit = 61 window.view = main_view # INITIALIZE TEXTURES HERE OR AFTER \o/ TEXTURE_WALL = Texture.load_from_file("main/walls.png") TEXTURE_BAR = Texture.load_from_file("main/bar.png") TEXTURE_HUDWEAPONS = Texture.load_from_file("main/hud_weapons.png") TEXTURE_FACES = Texture.load_from_file("main/faces.png") TEXTURE_NUMBERS = Texture.load_from_file("main/numbers.png") TEXTURE_WEAPONS = Texture.load_from_file("main/weapons.png") TEXTURE_ENEMIES = Texture.load_from_file("main/test.png") # Create an instance for all game variables and loop functions # and set the level to TESTLEVEL game = Gameworld(TEXTURE_ENEMIES) game.create_dict_map() game.player.gamemap = game.current_level game.init_physics() game.physics.mob_bodies(game.entities) # prepare the hud hud = Hud( player=game.player, background=TEXTURE_BAR, faces=TEXTURE_FACES, hudweapons=TEXTURE_HUDWEAPONS, weapons=TEXTURE_WEAPONS, numbers=TEXTURE_NUMBERS, ) # prepare the wall textures wall_sprites = game.create_wall_sprite_list(TEXTURE_WALL) rays = Raycaster(player=game.player, sprites=wall_sprites, gamemap=game.current_level) # prepare other stuff player_action = "" running = True nofocus = False ## # MAIN LOOP ## logg.info("Main loop starting...") while running: # iterate events for event in window.iter_events(): if event.type == Event.CLOSED or player_action == "quit": running = False if event.type == Event.LOST_FOCUS: nofocus = True elif event.type == Event.GAINED_FOCUS: nofocus = False if event.type == Event.KEY_RELEASED: if game.player.bob > 0: # level the headbobbing game.player.bob -= 0.5 elif game.player.bob < 0: game.player.bob += 0.5 game.player.strafing = False # disable speed limiter for moving in 2 axii window.clear(Color(235, 235, 235, 255)) # clear the window of everything for sprite in wall_sprites: # draw walls window.draw(sprite) # draw entities here for entity in game.entities: if entity.visible == True: for sprite_slice in entity.sprite: window.draw(sprite_slice) hud.display(window) # draw the hud debug_txt = text( "[" + str(draw_fps(frame)) + "] " + str("{0:.2f}".format(game.player.ux)) + "(" + str(game.player.x) + ")," + str("{0:.2f}".format(game.player.uy)) + "(" + str(game.player.y) + "):" + str(game.player.heading), style=1, ) window.draw(debug_txt) wall_sprites = rays.texture_slices( rays.cast_rays(), wall_sprites, game.player.bob ) # determine which walls to display # determine wich entities to display and prepare for entity in game.entities: # calculate the distance of entities to the player entity.distance_to_player(game.player) # print(str(round(entity.distance, 2)) + " " + str(entity.x) + "," + str(entity.y)) game.entities.sort(key=lambda x: x.distance, reverse=True) # sort entities based on the distance for entity in game.entities: entity.set_sprite_for_display(game.player, rays.distances) ### # TIMERS ### if game.player.attack_delay > 0 and game.player.attack == True: game.player.attack_delay -= 1 elif game.player.attack == True and game.player.attack_delay == 0: game.player.attack = False game.player.attack_delay = 2 elif game.player.attack == False and game.player.attack_delay > 0: game.player.attack_delay -= 1 if len(game.doors) != 0: # print('lol doors') for door in game.doors: # print(door.openess) state = door.open_close() # print(state) if state == "done": # print('removing doors') game.doors.remove(door) game.physics.world.ClearForces() if not nofocus: player_action = game.handle_keys() # player input game.physics.world.Step(1.0 / 60.0, 10, 8) game.player.update_position() for entity in game.entities: entity.update_position() window.display() # blit to window window.close() logg.info("Terminating. Have a nice day.") logg.info("Average FPS: %s", round(average_fps / all_frames, 2))
### # LOGGING ### from log import logg # ready to go! # logging convention: # logg.debug('') for variable passing # logg.info('') for standard initialization messages # logg.warn('') for known errors and caught exceptions # logg.error('') for something that shouldn't happen # logg.critical('') for breakage errors logg.info("Logging initialized.") ### # IMPORTS ### logg.info("Start imports.") # import sfml as sf # logg.info('SFML imported') from sfml import Clock, View, FloatRect, RenderWindow, VideoMode, Event, Texture, Color logg.info("SFML imported") from constants import PP_WIDTH, PP_HEIGHT, GAME_TITLE, GAME_VERSION, SCALE, BAR_HEIGHT
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from log import logg logg.info('Weapons initialized.') class Weapons(object): """Weapons to be used by the player.""" def __init__(self, ident, ammo=0, enabled=0): self.ident = ident self.ammo = ammo self.enabled = enabled