├── data ├── __init__.py ├── states │ ├── __init__.py │ ├── load_screen.py │ └── main_menu.py ├── components │ ├── __init__.py │ ├── collider.py │ ├── checkpoint.py │ ├── castle_flag.py │ ├── flashing_coin.py │ ├── coin.py │ ├── score.py │ ├── flagpole.py │ ├── coin_box.py │ ├── enemies.py │ ├── bricks.py │ ├── powerups.py │ └── info.py ├── main.py ├── setup.py ├── game_sound.py ├── constants.py ├── tools.py └── env.py ├── resources ├── fonts │ ├── __init__.py │ └── Fixedsys500c.ttf ├── music │ ├── __init__.py │ ├── death.wav │ ├── flagpole.wav │ ├── game_over.ogg │ ├── invincible.ogg │ ├── main_theme.ogg │ ├── out_of_time.wav │ ├── stage_clear.wav │ ├── world_clear.wav │ └── main_theme_sped_up.ogg ├── sound │ ├── __init__.py │ ├── bump.ogg │ ├── coin.ogg │ ├── kick.ogg │ ├── pipe.ogg │ ├── one_up.ogg │ ├── stomp.ogg │ ├── big_jump.ogg │ ├── fireball.ogg │ ├── powerup.ogg │ ├── brick_smash.ogg │ ├── count_down.ogg │ ├── small_jump.ogg │ ├── powerup_appears.ogg │ └── main_theme_sped_up.ogg └── graphics │ ├── __init__.py │ ├── enemies.png │ ├── level_1.png │ ├── tile_set.png │ ├── mario_bros.png │ ├── text_images.png │ ├── item_objects.png │ ├── title_screen.png │ └── smb_enemies_sheet.png ├── README.md ├── gpu_monitor.sh ├── input_log └── input_100 ├── save └── checkpoint ├── .idea └── vcs.xml ├── mario_level_1.py ├── test.py ├── play.py ├── dqn.py ├── ttest.py ├── main.py ├── main_async.py └── LICENSE /data/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /data/states/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /data/components/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /resources/fonts/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /resources/music/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /resources/sound/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /resources/graphics/__init__.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tensorflow_dqn_supermario 2 | dqn autoplay mario bros 3 | -------------------------------------------------------------------------------- /gpu_monitor.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | while : 4 | do 5 | clear 6 | nvidia-smi 7 | done -------------------------------------------------------------------------------- /input_log/input_100: -------------------------------------------------------------------------------- 1 | [0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 3, 9, 9, 9] -------------------------------------------------------------------------------- /resources/sound/bump.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/bump.ogg -------------------------------------------------------------------------------- /resources/sound/coin.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/coin.ogg -------------------------------------------------------------------------------- /resources/sound/kick.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/kick.ogg -------------------------------------------------------------------------------- /resources/sound/pipe.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/pipe.ogg -------------------------------------------------------------------------------- /resources/music/death.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/death.wav -------------------------------------------------------------------------------- /resources/sound/one_up.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/one_up.ogg -------------------------------------------------------------------------------- /resources/sound/stomp.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/stomp.ogg -------------------------------------------------------------------------------- /resources/music/flagpole.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/flagpole.wav -------------------------------------------------------------------------------- /resources/music/game_over.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/game_over.ogg -------------------------------------------------------------------------------- /resources/sound/big_jump.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/big_jump.ogg -------------------------------------------------------------------------------- /resources/sound/fireball.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/fireball.ogg -------------------------------------------------------------------------------- /resources/sound/powerup.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/powerup.ogg -------------------------------------------------------------------------------- /save/checkpoint: -------------------------------------------------------------------------------- 1 | model_checkpoint_path: "save_model_targetckpt-0" 2 | all_model_checkpoint_paths: "save_model_targetckpt-0" 3 | -------------------------------------------------------------------------------- /resources/graphics/enemies.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/enemies.png -------------------------------------------------------------------------------- /resources/graphics/level_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/level_1.png -------------------------------------------------------------------------------- /resources/graphics/tile_set.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/tile_set.png -------------------------------------------------------------------------------- /resources/music/invincible.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/invincible.ogg -------------------------------------------------------------------------------- /resources/music/main_theme.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/main_theme.ogg -------------------------------------------------------------------------------- /resources/music/out_of_time.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/out_of_time.wav -------------------------------------------------------------------------------- /resources/music/stage_clear.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/stage_clear.wav -------------------------------------------------------------------------------- /resources/music/world_clear.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/world_clear.wav -------------------------------------------------------------------------------- /resources/sound/brick_smash.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/brick_smash.ogg -------------------------------------------------------------------------------- /resources/sound/count_down.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/count_down.ogg -------------------------------------------------------------------------------- /resources/sound/small_jump.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/small_jump.ogg -------------------------------------------------------------------------------- /resources/fonts/Fixedsys500c.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/fonts/Fixedsys500c.ttf -------------------------------------------------------------------------------- /resources/graphics/mario_bros.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/mario_bros.png -------------------------------------------------------------------------------- /resources/graphics/text_images.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/text_images.png -------------------------------------------------------------------------------- /resources/graphics/item_objects.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/item_objects.png -------------------------------------------------------------------------------- /resources/graphics/title_screen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/title_screen.png -------------------------------------------------------------------------------- /resources/sound/powerup_appears.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/powerup_appears.ogg -------------------------------------------------------------------------------- /resources/music/main_theme_sped_up.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/music/main_theme_sped_up.ogg -------------------------------------------------------------------------------- /resources/sound/main_theme_sped_up.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/sound/main_theme_sped_up.ogg -------------------------------------------------------------------------------- /resources/graphics/smb_enemies_sheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/joongsoo/tensorflow_dqn_supermario/HEAD/resources/graphics/smb_enemies_sheet.png -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /mario_level_1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | __author__ = 'justinarmstrong' 3 | 4 | """ 5 | This is an attempt to recreate the first level of 6 | Super Mario Bros for the NES. 7 | """ 8 | 9 | import sys 10 | import pygame as pg 11 | from data.main import main 12 | import cProfile 13 | 14 | 15 | if __name__=='__main__': 16 | main() 17 | pg.quit() 18 | sys.exit() -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import numpy as np 3 | import random 4 | import dqn 5 | from collections import deque 6 | from data import env 7 | 8 | 9 | env = env.Env() 10 | 11 | 12 | dis = 0.9 13 | REPLAY_MEMORY = 50000 14 | 15 | 16 | def main(): 17 | 18 | max_episodes = 1500 19 | for episode in range(max_episodes): 20 | done = False 21 | step_count = 0 22 | env.reset() 23 | 24 | while not done: 25 | state, reward, done = env.step(env.get_random_actions()[0]) 26 | 27 | step_count += 1 28 | 29 | 30 | 31 | if __name__ == "__main__": 32 | main() 33 | -------------------------------------------------------------------------------- /data/components/collider.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import constants as c 5 | 6 | class Collider(pg.sprite.Sprite): 7 | """Invisible sprites placed overtop background parts 8 | that can be collided with (pipes, steps, ground, etc.""" 9 | def __init__(self, x, y, width, height, name='collider'): 10 | pg.sprite.Sprite.__init__(self) 11 | self.image = pg.Surface((width, height)).convert() 12 | #self.image.fill(c.RED) 13 | self.rect = self.image.get_rect() 14 | self.rect.x = x 15 | self.rect.y = y 16 | self.state = None 17 | 18 | -------------------------------------------------------------------------------- /data/components/checkpoint.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import constants as c 5 | 6 | 7 | class Checkpoint(pg.sprite.Sprite): 8 | """Invisible sprite used to add enemies, special boxes 9 | and trigger sliding down the flag pole""" 10 | def __init__(self, x, name, y=0, width=10, height=600): 11 | super(Checkpoint, self).__init__() 12 | self.image = pg.Surface((width, height)) 13 | self.image.fill(c.BLACK) 14 | self.rect = self.image.get_rect() 15 | self.rect.x = x 16 | self.rect.y = y 17 | self.name = name 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /play.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import tensorflow as tf 3 | import numpy as np 4 | from data.env import Env 5 | from tensorflow.python.framework.errors_impl import NotFoundError 6 | 7 | class AIControl: 8 | def __init__(self, env): 9 | self.env = env 10 | 11 | self.input_size = self.env.state_n 12 | self.output_size = 12 13 | 14 | self.max_episodes = 1500 15 | self.val = 0 16 | self.save_path = "./save/save_model" 17 | 18 | def control_start(self): 19 | import dqn 20 | with tf.Session() as sess: 21 | mainDQN = dqn.DQN(sess, self.input_size, self.output_size, 22 | name="main", is_training=False) 23 | tf.global_variables_initializer().run() 24 | 25 | mainDQN.restore(100) 26 | 27 | for episode in range(self.max_episodes): 28 | done = False 29 | clear = False 30 | state = self.env.reset() 31 | 32 | while not done and not clear: 33 | action = np.argmax(mainDQN.predict(state)) 34 | print action 35 | next_state, reward, done, clear, max_x, _, _ = self.env.step(action) 36 | state = next_state 37 | 38 | def main(): 39 | env = Env() 40 | controller = AIControl(env) 41 | controller.control_start() 42 | 43 | if __name__ == "__main__": 44 | main() 45 | -------------------------------------------------------------------------------- /data/main.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | from . import setup,tools 4 | from .states import main_menu,load_screen,level1 5 | from . import constants as c 6 | import pygame as pg 7 | from pygame.surfarray import pixels3d 8 | 9 | def main(): 10 | """Add states to control here.""" 11 | run_it = tools.Control(setup.ORIGINAL_CAPTION) 12 | state_dict = {c.MAIN_MENU: main_menu.Menu(), 13 | c.LOAD_SCREEN: load_screen.LoadScreen(), 14 | c.TIME_OUT: load_screen.TimeOut(), 15 | c.GAME_OVER: load_screen.GameOver(), 16 | c.LEVEL1: level1.Level1()} 17 | 18 | run_it.setup_states(state_dict, c.LEVEL1) 19 | #state_dict[c.MAIN_MENU].startup() 20 | #run_it.main() 21 | while not run_it.done: 22 | run_it.event_loop(None) 23 | run_it.update() 24 | pg.display.update() 25 | if run_it.ml_done: 26 | run_it = tools.Control(setup.ORIGINAL_CAPTION) 27 | state_dict = {c.MAIN_MENU: main_menu.Menu(), 28 | c.LOAD_SCREEN: load_screen.LoadScreen(), 29 | c.TIME_OUT: load_screen.TimeOut(), 30 | c.GAME_OVER: load_screen.GameOver(), 31 | c.LEVEL1: level1.Level1()} 32 | 33 | run_it.setup_states(state_dict, c.LEVEL1) 34 | 35 | 36 | run_it.clock.tick(run_it.fps) 37 | if run_it.show_fps: 38 | fps = run_it.clock.get_fps() 39 | with_fps = "{} - {:.2f} FPS".format(run_it.caption, fps) 40 | pg.display.set_caption(with_fps) 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /data/components/castle_flag.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | 7 | 8 | class Flag(pg.sprite.Sprite): 9 | """Flag on the castle""" 10 | def __init__(self, x, y): 11 | """Initialize object""" 12 | super(Flag, self).__init__() 13 | self.sprite_sheet = setup.GFX['item_objects'] 14 | self.image = self.get_image(129, 2, 14, 14) 15 | self.rect = self.image.get_rect() 16 | self.rect.x = x 17 | self.rect.y = y 18 | self.state = 'rising' 19 | self.y_vel = -2 20 | self.target_height = y 21 | 22 | 23 | def get_image(self, x, y, width, height): 24 | """Extracts image from sprite sheet""" 25 | image = pg.Surface([width, height]) 26 | rect = image.get_rect() 27 | 28 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 29 | image.set_colorkey(c.BLACK) 30 | image = pg.transform.scale(image, 31 | (int(rect.width*c.SIZE_MULTIPLIER), 32 | int(rect.height*c.SIZE_MULTIPLIER))) 33 | return image 34 | 35 | def update(self, *args): 36 | """Updates flag position""" 37 | if self.state == 'rising': 38 | self.rising() 39 | elif self.state == 'resting': 40 | self.resting() 41 | 42 | def rising(self): 43 | """State when flag is rising to be on the castle""" 44 | self.rect.y += self.y_vel 45 | if self.rect.bottom <= self.target_height: 46 | self.state = 'resting' 47 | 48 | def resting(self): 49 | """State when the flag is stationary doing nothing""" 50 | pass 51 | -------------------------------------------------------------------------------- /data/components/flashing_coin.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | 7 | 8 | class Coin(pg.sprite.Sprite): 9 | """Flashing coin next to coin total info""" 10 | def __init__(self, x, y): 11 | super(Coin, self).__init__() 12 | self.sprite_sheet = setup.GFX['item_objects'] 13 | self.create_frames() 14 | self.image = self.frames[0] 15 | self.rect = self.image.get_rect() 16 | self.rect.x = x 17 | self.rect.y = y 18 | self.timer = 0 19 | self.first_half = True 20 | self.frame_index = 0 21 | 22 | 23 | def create_frames(self): 24 | """Extract coin images from sprite sheet and assign them to a list""" 25 | self.frames = [] 26 | self.frame_index = 0 27 | 28 | self.frames.append(self.get_image(1, 160, 5, 8)) 29 | self.frames.append(self.get_image(9, 160, 5, 8)) 30 | self.frames.append(self.get_image(17, 160, 5, 8)) 31 | 32 | 33 | def get_image(self, x, y, width, height): 34 | """Extracts image from sprite sheet""" 35 | image = pg.Surface([width, height]) 36 | rect = image.get_rect() 37 | 38 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 39 | image.set_colorkey(c.BLACK) 40 | image = pg.transform.scale(image, 41 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 42 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 43 | return image 44 | 45 | 46 | def update(self, current_time): 47 | """Animates flashing coin""" 48 | if self.first_half: 49 | if self.frame_index == 0: 50 | if (current_time - self.timer) > 375: 51 | self.frame_index += 1 52 | self.timer = current_time 53 | elif self.frame_index < 2: 54 | if (current_time - self.timer) > 125: 55 | self.frame_index += 1 56 | self.timer = current_time 57 | elif self.frame_index == 2: 58 | if (current_time - self.timer) > 125: 59 | self.frame_index -= 1 60 | self.first_half = False 61 | self.timer = current_time 62 | else: 63 | if self.frame_index == 1: 64 | if (current_time - self.timer) > 125: 65 | self.frame_index -= 1 66 | self.first_half = True 67 | self.timer = current_time 68 | 69 | self.image = self.frames[self.frame_index] -------------------------------------------------------------------------------- /data/setup.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | """ 4 | This module initializes the display and creates dictionaries of resources. 5 | """ 6 | 7 | import platform 8 | 9 | p_name = platform.system() 10 | print p_name 11 | 12 | import os 13 | import pygame as pg 14 | from . import tools 15 | from . import constants as c 16 | ORIGINAL_CAPTION = c.ORIGINAL_CAPTION 17 | 18 | current_dir = os.path.dirname(os.path.realpath(__file__)) 19 | ''' 20 | os.environ['SDL_VIDEO_CENTERED'] = '1' 21 | pg.init() 22 | pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT]) 23 | pg.display.set_caption(c.ORIGINAL_CAPTION) 24 | SCREEN = pg.display.set_mode(c.SCREEN_SIZE, 0, 32) 25 | SCREEN_RECT = SCREEN.get_rect() 26 | FONTS = tools.load_all_fonts(os.path.join("resources", "fonts")) 27 | MUSIC = tools.load_all_music(os.path.join("resources", "music")) 28 | GFX = tools.load_all_gfx(os.path.join("resources", "graphics")) 29 | SFX = tools.load_all_sfx(os.path.join("resources", "sound")) 30 | # dev env 31 | ''' 32 | if True:#p_name == "aaa": 33 | import os 34 | import pygame as pg 35 | from . import tools 36 | from . import constants as c 37 | ORIGINAL_CAPTION = c.ORIGINAL_CAPTION 38 | 39 | 40 | os.environ['SDL_VIDEO_CENTERED'] = '1' 41 | pg.init() 42 | pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT]) 43 | pg.display.set_caption(c.ORIGINAL_CAPTION) 44 | SCREEN = pg.display.set_mode(c.SCREEN_SIZE, 0, 32) 45 | SCREEN_RECT = SCREEN.get_rect() 46 | FONTS = tools.load_all_fonts(os.path.join("resources", "fonts")) 47 | MUSIC = tools.load_all_music(os.path.join("resources", "music")) 48 | GFX = tools.load_all_gfx(os.path.join("resources", "graphics")) 49 | SFX = tools.load_all_sfx(os.path.join("resources", "sound")) 50 | # aws 51 | else: 52 | import os 53 | # import pygame as pg 54 | from . import tools 55 | from . import constants as c 56 | 57 | ORIGINAL_CAPTION = c.ORIGINAL_CAPTION 58 | 59 | os.environ['SDL_VIDEO_CENTERED'] = '1' 60 | os.environ["SDL_VIDEODRIVER"] = "dummy" 61 | os.environ["SDL_AUDIODRIVER"] = "dummy" 62 | import pygame as pg 63 | 64 | pg.init() 65 | 66 | pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT]) 67 | pg.display.set_caption(c.ORIGINAL_CAPTION) 68 | SCREEN = pg.display.set_mode(c.SCREEN_SIZE, 0, 32) 69 | SCREEN_RECT = SCREEN.get_rect() 70 | FONTS = tools.load_all_fonts(os.path.join(current_dir, "..", "resources", "fonts")) 71 | MUSIC = tools.load_all_music(os.path.join(current_dir, "..", "resources", "music")) 72 | GFX = tools.load_all_gfx(os.path.join(current_dir, "..", "resources", "graphics")) 73 | SFX = tools.load_all_sfx(os.path.join(current_dir, "..", "resources", "sound")) 74 | 75 | 76 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /data/components/coin.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | from . import score 7 | 8 | 9 | class Coin(pg.sprite.Sprite): 10 | """Coins found in boxes and bricks""" 11 | def __init__(self, x, y, score_group): 12 | pg.sprite.Sprite.__init__(self) 13 | self.sprite_sheet = setup.GFX['item_objects'] 14 | self.frames = [] 15 | self.frame_index = 0 16 | self.animation_timer = 0 17 | self.state = c.SPIN 18 | self.setup_frames() 19 | self.image = self.frames[self.frame_index] 20 | self.rect = self.image.get_rect() 21 | self.rect.centerx = x 22 | self.rect.bottom = y - 5 23 | self.gravity = 1 24 | self.y_vel = -15 25 | self.initial_height = self.rect.bottom - 5 26 | self.score_group = score_group 27 | 28 | 29 | def get_image(self, x, y, width, height): 30 | """Get the image frames from the sprite sheet""" 31 | image = pg.Surface([width, height]).convert() 32 | rect = image.get_rect() 33 | 34 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 35 | image.set_colorkey(c.BLACK) 36 | 37 | 38 | image = pg.transform.scale(image, 39 | (int(rect.width*c.SIZE_MULTIPLIER), 40 | int(rect.height*c.SIZE_MULTIPLIER))) 41 | return image 42 | 43 | 44 | def setup_frames(self): 45 | """create the frame list""" 46 | self.frames.append(self.get_image(52, 113, 8, 14)) 47 | self.frames.append(self.get_image(4, 113, 8, 14)) 48 | self.frames.append(self.get_image(20, 113, 8, 14)) 49 | self.frames.append(self.get_image(36, 113, 8, 14)) 50 | 51 | 52 | def update(self, game_info, viewport): 53 | """Update the coin's behavior""" 54 | self.current_time = game_info[c.CURRENT_TIME] 55 | self.viewport = viewport 56 | if self.state == c.SPIN: 57 | self.spinning() 58 | 59 | 60 | def spinning(self): 61 | """Action when the coin is in the SPIN state""" 62 | self.image = self.frames[self.frame_index] 63 | self.rect.y += self.y_vel 64 | self.y_vel += self.gravity 65 | 66 | if (self.current_time - self.animation_timer) > 80: 67 | if self.frame_index < 3: 68 | self.frame_index += 1 69 | else: 70 | self.frame_index = 0 71 | 72 | self.animation_timer = self.current_time 73 | 74 | if self.rect.bottom > self.initial_height: 75 | self.kill() 76 | self.score_group.append(score.Score(self.rect.centerx - self.viewport.x, 77 | self.rect.y, 78 | 200)) 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /data/states/load_screen.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | from .. import setup, tools 4 | from .. import constants as c 5 | from .. import game_sound 6 | from ..components import info 7 | 8 | 9 | class LoadScreen(tools._State): 10 | def __init__(self): 11 | tools._State.__init__(self) 12 | 13 | def startup(self, current_time, persist): 14 | self.start_time = current_time 15 | self.persist = persist 16 | self.game_info = self.persist 17 | self.next = self.set_next_state() 18 | 19 | info_state = self.set_overhead_info_state() 20 | 21 | self.overhead_info = info.OverheadInfo(self.game_info, info_state) 22 | self.sound_manager = game_sound.Sound(self.overhead_info) 23 | 24 | 25 | def set_next_state(self): 26 | """Sets the next state""" 27 | return c.LEVEL1 28 | 29 | def set_overhead_info_state(self): 30 | """sets the state to send to the overhead info object""" 31 | return c.LOAD_SCREEN 32 | 33 | 34 | def update(self, surface, keys, current_time): 35 | """Updates the loading screen""" 36 | if (current_time - self.start_time) < 2400: 37 | surface.fill(c.BLACK) 38 | self.overhead_info.update(self.game_info) 39 | self.overhead_info.draw(surface) 40 | 41 | elif (current_time - self.start_time) < 2600: 42 | surface.fill(c.BLACK) 43 | 44 | elif (current_time - self.start_time) < 2635: 45 | surface.fill((106, 150, 252)) 46 | 47 | else: 48 | self.done = True 49 | 50 | 51 | 52 | 53 | class GameOver(LoadScreen): 54 | """A loading screen with Game Over""" 55 | def __init__(self): 56 | super(GameOver, self).__init__() 57 | 58 | 59 | def set_next_state(self): 60 | """Sets next state""" 61 | return c.MAIN_MENU 62 | 63 | def set_overhead_info_state(self): 64 | """sets the state to send to the overhead info object""" 65 | return c.GAME_OVER 66 | 67 | def update(self, surface, keys, current_time): 68 | self.current_time = current_time 69 | self.sound_manager.update(self.persist, None) 70 | 71 | if (self.current_time - self.start_time) < 7000: 72 | surface.fill(c.BLACK) 73 | self.overhead_info.update(self.game_info) 74 | self.overhead_info.draw(surface) 75 | elif (self.current_time - self.start_time) < 7200: 76 | surface.fill(c.BLACK) 77 | elif (self.current_time - self.start_time) < 7235: 78 | surface.fill((106, 150, 252)) 79 | else: 80 | self.done = True 81 | 82 | 83 | class TimeOut(LoadScreen): 84 | """Loading Screen with Time Out""" 85 | def __init__(self): 86 | super(TimeOut, self).__init__() 87 | 88 | def set_next_state(self): 89 | """Sets next state""" 90 | if self.persist[c.LIVES] == 0: 91 | return c.GAME_OVER 92 | else: 93 | return c.LOAD_SCREEN 94 | 95 | def set_overhead_info_state(self): 96 | """Sets the state to send to the overhead info object""" 97 | return c.TIME_OUT 98 | 99 | def update(self, surface, keys, current_time): 100 | self.current_time = current_time 101 | 102 | if (self.current_time - self.start_time) < 2400: 103 | surface.fill(c.BLACK) 104 | self.overhead_info.update(self.game_info) 105 | self.overhead_info.draw(surface) 106 | else: 107 | self.done = True 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /data/game_sound.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from . import setup 5 | from . import constants as c 6 | 7 | class Sound(object): 8 | """Handles all sound for the game""" 9 | def __init__(self, overhead_info): 10 | """Initialize the class""" 11 | self.sfx_dict = setup.SFX 12 | self.music_dict = setup.MUSIC 13 | self.overhead_info = overhead_info 14 | self.game_info = overhead_info.game_info 15 | self.set_music_mixer() 16 | 17 | 18 | 19 | def set_music_mixer(self): 20 | """Sets music for level""" 21 | if self.overhead_info.state == c.LEVEL: 22 | pg.mixer.music.load(self.music_dict['main_theme']) 23 | pg.mixer.music.play() 24 | self.state = c.NORMAL 25 | elif self.overhead_info.state == c.GAME_OVER: 26 | pg.mixer.music.load(self.music_dict['game_over']) 27 | pg.mixer.music.play() 28 | self.state = c.GAME_OVER 29 | 30 | 31 | def update(self, game_info, mario): 32 | """Updates sound object with game info""" 33 | self.game_info = game_info 34 | self.mario = mario 35 | self.handle_state() 36 | 37 | def handle_state(self): 38 | """Handles the state of the soundn object""" 39 | if self.state == c.NORMAL: 40 | if self.mario.dead: 41 | self.play_music('death', c.MARIO_DEAD) 42 | elif self.mario.invincible \ 43 | and self.mario.losing_invincibility == False: 44 | self.play_music('invincible', c.MARIO_INVINCIBLE) 45 | elif self.mario.state == c.FLAGPOLE: 46 | self.play_music('flagpole', c.FLAGPOLE) 47 | elif self.overhead_info.time == 100: 48 | self.play_music('out_of_time', c.TIME_WARNING) 49 | 50 | 51 | elif self.state == c.FLAGPOLE: 52 | if self.mario.state == c.WALKING_TO_CASTLE: 53 | self.play_music('stage_clear', c.STAGE_CLEAR) 54 | 55 | elif self.state == c.STAGE_CLEAR: 56 | if self.mario.in_castle: 57 | self.sfx_dict['count_down'].play() 58 | self.state = c.FAST_COUNT_DOWN 59 | 60 | elif self.state == c.FAST_COUNT_DOWN: 61 | if self.overhead_info.time == 0: 62 | self.sfx_dict['count_down'].stop() 63 | self.state = c.WORLD_CLEAR 64 | 65 | elif self.state == c. TIME_WARNING: 66 | if pg.mixer.music.get_busy() == 0: 67 | self.play_music('main_theme_sped_up', c.SPED_UP_NORMAL) 68 | elif self.mario.dead: 69 | self.play_music('death', c.MARIO_DEAD) 70 | 71 | elif self.state == c.SPED_UP_NORMAL: 72 | if self.mario.dead: 73 | self.play_music('death', c.MARIO_DEAD) 74 | elif self.mario.state == c.FLAGPOLE: 75 | self.play_music('flagpole', c.FLAGPOLE) 76 | 77 | elif self.state == c.MARIO_INVINCIBLE: 78 | if (self.mario.current_time - self.mario.invincible_start_timer) > 11000: 79 | self.play_music('main_theme', c.NORMAL) 80 | elif self.mario.dead: 81 | self.play_music('death', c.MARIO_DEAD) 82 | 83 | 84 | elif self.state == c.WORLD_CLEAR: 85 | pass 86 | elif self.state == c.MARIO_DEAD: 87 | pass 88 | elif self.state == c.GAME_OVER: 89 | pass 90 | 91 | def play_music(self, key, state): 92 | """Plays new music""" 93 | #pg.mixer.music.load(self.music_dict[key]) 94 | #pg.mixer.music.play() 95 | self.state = state 96 | 97 | def stop_music(self): 98 | """Stops playback""" 99 | pg.mixer.music.stop() 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /data/constants.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | SCREEN_HEIGHT = 600 4 | SCREEN_WIDTH = 800 5 | 6 | SCREEN_SIZE = (SCREEN_WIDTH,SCREEN_HEIGHT) 7 | 8 | ORIGINAL_CAPTION = "Super Mario Bros 1-1" 9 | 10 | ## COLORS ## 11 | 12 | # R G B 13 | GRAY = (100, 100, 100) 14 | NAVYBLUE = ( 60, 60, 100) 15 | WHITE = (255, 255, 255) 16 | RED = (255, 0, 0) 17 | GREEN = ( 0, 255, 0) 18 | FOREST_GREEN = ( 31, 162, 35) 19 | BLUE = ( 0, 0, 255) 20 | SKY_BLUE = ( 39, 145, 251) 21 | YELLOW = (255, 255, 0) 22 | ORANGE = (255, 128, 0) 23 | PURPLE = (255, 0, 255) 24 | CYAN = ( 0, 255, 255) 25 | BLACK = ( 0, 0, 0) 26 | NEAR_BLACK = ( 19, 15, 48) 27 | COMBLUE = (233, 232, 255) 28 | GOLD = (255, 215, 0) 29 | 30 | BGCOLOR = WHITE 31 | 32 | SIZE_MULTIPLIER = 2.5 33 | BRICK_SIZE_MULTIPLIER = 2.69 34 | BACKGROUND_MULTIPLER = 2.679 35 | GROUND_HEIGHT = SCREEN_HEIGHT - 62 36 | 37 | #MARIO FORCES 38 | WALK_ACCEL = .15 39 | RUN_ACCEL = 20 40 | SMALL_TURNAROUND = .35 41 | 42 | GRAVITY = 3 43 | JUMP_GRAVITY = 0.9 44 | JUMP_VEL = -19 45 | FAST_JUMP_VEL = -11 46 | MAX_Y_VEL = 10 47 | 48 | MAX_RUN_SPEED = 500 49 | MAX_WALK_SPEED = 6 50 | 51 | 52 | #Mario States 53 | 54 | STAND = 'standing' 55 | WALK = 'walk' 56 | JUMP = 'jump' 57 | FALL = 'fall' 58 | SMALL_TO_BIG = 'small to big' 59 | BIG_TO_FIRE = 'big to fire' 60 | BIG_TO_SMALL = 'big to small' 61 | FLAGPOLE = 'flag pole' 62 | WALKING_TO_CASTLE = 'walking to castle' 63 | END_OF_LEVEL_FALL = 'end of level fall' 64 | 65 | 66 | #GOOMBA Stuff 67 | 68 | LEFT = 'left' 69 | RIGHT = 'right' 70 | JUMPED_ON = 'jumped on' 71 | DEATH_JUMP = 'death jump' 72 | 73 | #KOOPA STUFF 74 | 75 | SHELL_SLIDE = 'shell slide' 76 | 77 | #BRICK STATES 78 | 79 | RESTING = 'resting' 80 | BUMPED = 'bumped' 81 | 82 | #COIN STATES 83 | OPENED = 'opened' 84 | 85 | #MUSHROOM STATES 86 | 87 | REVEAL = 'reveal' 88 | SLIDE = 'slide' 89 | 90 | #COIN STATES 91 | 92 | SPIN = 'spin' 93 | 94 | #STAR STATES 95 | 96 | BOUNCE = 'bounce' 97 | 98 | #FIRE STATES 99 | 100 | FLYING = 'flying' 101 | BOUNCING = 'bouncing' 102 | EXPLODING = 'exploding' 103 | 104 | #Brick and coin box contents 105 | 106 | MUSHROOM = 'mushroom' 107 | STAR = 'star' 108 | FIREFLOWER = 'fireflower' 109 | SIXCOINS = '6coins' 110 | COIN = 'coin' 111 | LIFE_MUSHROOM = '1up_mushroom' 112 | 113 | FIREBALL = 'fireball' 114 | 115 | #LIST of ENEMIES 116 | 117 | GOOMBA = 'goomba' 118 | KOOPA = 'koopa' 119 | 120 | #LEVEL STATES 121 | 122 | FROZEN = 'frozen' 123 | NOT_FROZEN = 'not frozen' 124 | IN_CASTLE = 'in castle' 125 | FLAG_AND_FIREWORKS = 'flag and fireworks' 126 | 127 | #FLAG STATE 128 | TOP_OF_POLE = 'top of pole' 129 | SLIDE_DOWN = 'slide down' 130 | BOTTOM_OF_POLE = 'bottom of pole' 131 | 132 | #1UP score 133 | ONEUP = '379' 134 | 135 | #MAIN MENU CURSOR STATES 136 | PLAYER1 = '1 player' 137 | PLAYER2 = '2 player' 138 | 139 | #OVERHEAD INFO STATES 140 | MAIN_MENU = 'main menu' 141 | LOAD_SCREEN = 'loading screen' 142 | LEVEL = 'level' 143 | GAME_OVER = 'game over' 144 | FAST_COUNT_DOWN = 'fast count down' 145 | END_OF_LEVEL = 'end of level' 146 | 147 | 148 | #GAME INFO DICTIONARY KEYS 149 | COIN_TOTAL = 'coin total' 150 | SCORE = 'score' 151 | TOP_SCORE = 'top score' 152 | LIVES = 'lives' 153 | CURRENT_TIME = 'current time' 154 | LEVEL_STATE = 'level state' 155 | CAMERA_START_X = 'camera start x' 156 | MARIO_DEAD = 'mario dead' 157 | 158 | #STATES FOR ENTIRE GAME 159 | MAIN_MENU = 'main menu' 160 | LOAD_SCREEN = 'load screen' 161 | TIME_OUT = 'time out' 162 | GAME_OVER = 'game over' 163 | LEVEL1 = 'level1' 164 | 165 | #SOUND STATEZ 166 | NORMAL = 'normal' 167 | STAGE_CLEAR = 'stage clear' 168 | WORLD_CLEAR = 'world clear' 169 | TIME_WARNING = 'time warning' 170 | SPED_UP_NORMAL = 'sped up normal' 171 | MARIO_INVINCIBLE = 'mario invincible' 172 | 173 | 174 | 175 | 176 | 177 | 178 | -------------------------------------------------------------------------------- /data/components/score.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | 7 | 8 | class Digit(pg.sprite.Sprite): 9 | """Individual digit for score""" 10 | def __init__(self, image): 11 | super(Digit, self).__init__() 12 | self.image = image 13 | self.rect = image.get_rect() 14 | 15 | 16 | class Score(object): 17 | """Scores that appear, float up, and disappear""" 18 | def __init__(self, x, y, score, flag_pole=False): 19 | self.x = x 20 | self.y = y 21 | if flag_pole: 22 | self.y_vel = -4 23 | else: 24 | self.y_vel = -3 25 | self.sprite_sheet = setup.GFX['item_objects'] 26 | self.create_image_dict() 27 | self.score_string = str(score) 28 | self.create_digit_list() 29 | self.flag_pole_score = flag_pole 30 | 31 | 32 | def create_image_dict(self): 33 | """Creates the dictionary for all the number images needed""" 34 | self.image_dict = {} 35 | 36 | image0 = self.get_image(1, 168, 3, 8) 37 | image1 = self.get_image(5, 168, 3, 8) 38 | image2 = self.get_image(8, 168, 4, 8) 39 | image4 = self.get_image(12, 168, 4, 8) 40 | image5 = self.get_image(16, 168, 5, 8) 41 | image8 = self.get_image(20, 168, 4, 8) 42 | image9 = self.get_image(32, 168, 5, 8) 43 | image10 = self.get_image(37, 168, 6, 8) 44 | image11 = self.get_image(43, 168, 5, 8) 45 | 46 | self.image_dict['0'] = image0 47 | self.image_dict['1'] = image1 48 | self.image_dict['2'] = image2 49 | self.image_dict['4'] = image4 50 | self.image_dict['5'] = image5 51 | self.image_dict['8'] = image8 52 | self.image_dict['3'] = image9 53 | self.image_dict['7'] = image10 54 | self.image_dict['9'] = image11 55 | 56 | 57 | def get_image(self, x, y, width, height): 58 | """Extracts image from sprite sheet""" 59 | image = pg.Surface([width, height]).convert() 60 | rect = image.get_rect() 61 | 62 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 63 | image.set_colorkey(c.BLACK) 64 | image = pg.transform.scale(image, 65 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 66 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 67 | return image 68 | 69 | 70 | def create_digit_list(self): 71 | """Creates the group of images based on score received""" 72 | self.digit_list = [] 73 | self.digit_group = pg.sprite.Group() 74 | 75 | for digit in self.score_string: 76 | self.digit_list.append(Digit(self.image_dict[digit])) 77 | 78 | self.set_rects_for_images() 79 | 80 | 81 | def set_rects_for_images(self): 82 | """Set the rect attributes for each image in self.image_list""" 83 | for i, digit in enumerate(self.digit_list): 84 | digit.rect = digit.image.get_rect() 85 | digit.rect.x = self.x + (i * 10) 86 | digit.rect.y = self.y 87 | 88 | 89 | def update(self, score_list, level_info): 90 | """Updates score movement""" 91 | for number in self.digit_list: 92 | number.rect.y += self.y_vel 93 | 94 | if score_list: 95 | self.check_to_delete_floating_scores(score_list, level_info) 96 | 97 | if self.flag_pole_score: 98 | if self.digit_list[0].rect.y <= 120: 99 | self.y_vel = 0 100 | 101 | 102 | def draw(self, screen): 103 | """Draws score numbers onto screen""" 104 | for digit in self.digit_list: 105 | screen.blit(digit.image, digit.rect) 106 | 107 | 108 | def check_to_delete_floating_scores(self, score_list, level_info): 109 | """Check if scores need to be deleted""" 110 | for i, score in enumerate(score_list): 111 | if int(score.score_string) == 1000: 112 | if (score.y - score.digit_list[0].rect.y) > 130: 113 | score_list.pop(i) 114 | 115 | else: 116 | if (score.y - score.digit_list[0].rect.y) > 75: 117 | score_list.pop(i) 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | -------------------------------------------------------------------------------- /data/components/flagpole.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | 7 | class Flag(pg.sprite.Sprite): 8 | """Flag on top of the flag pole at the end of the level""" 9 | def __init__(self, x, y): 10 | super(Flag, self).__init__() 11 | self.sprite_sheet = setup.GFX['item_objects'] 12 | self.setup_images() 13 | self.image = self.frames[0] 14 | self.rect = self.image.get_rect() 15 | self.rect.right = x 16 | self.rect.y = y 17 | self.state = c.TOP_OF_POLE 18 | 19 | 20 | def setup_images(self): 21 | """Sets up a list of image frames""" 22 | self.frames = [] 23 | 24 | self.frames.append( 25 | self.get_image(128, 32, 16, 16)) 26 | 27 | 28 | def get_image(self, x, y, width, height): 29 | """Extracts image from sprite sheet""" 30 | image = pg.Surface([width, height]) 31 | rect = image.get_rect() 32 | 33 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 34 | image.set_colorkey(c.BLACK) 35 | image = pg.transform.scale(image, 36 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 37 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 38 | return image 39 | 40 | 41 | def update(self, *args): 42 | """Updates behavior""" 43 | self.handle_state() 44 | 45 | 46 | def handle_state(self): 47 | """Determines behavior based on state""" 48 | if self.state == c.TOP_OF_POLE: 49 | self.image = self.frames[0] 50 | elif self.state == c.SLIDE_DOWN: 51 | self.sliding_down() 52 | elif self.state == c.BOTTOM_OF_POLE: 53 | self.image = self.frames[0] 54 | 55 | 56 | def sliding_down(self): 57 | """State when Mario reaches flag pole""" 58 | self.y_vel = 5 59 | self.rect.y += self.y_vel 60 | 61 | if self.rect.bottom >= 485: 62 | self.state = c.BOTTOM_OF_POLE 63 | 64 | 65 | class Pole(pg.sprite.Sprite): 66 | """Pole that the flag is on top of""" 67 | def __init__(self, x, y): 68 | super(Pole, self).__init__() 69 | self.sprite_sheet = setup.GFX['tile_set'] 70 | self.setup_frames() 71 | self.image = self.frames[0] 72 | self.rect = self.image.get_rect() 73 | self.rect.x = x 74 | self.rect.y = y 75 | 76 | 77 | def setup_frames(self): 78 | """Create the frame list""" 79 | self.frames = [] 80 | 81 | self.frames.append( 82 | self.get_image(263, 144, 2, 16)) 83 | 84 | 85 | def get_image(self, x, y, width, height): 86 | """Extracts image from sprite sheet""" 87 | image = pg.Surface([width, height]) 88 | rect = image.get_rect() 89 | 90 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 91 | image.set_colorkey(c.BLACK) 92 | image = pg.transform.scale(image, 93 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 94 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 95 | return image 96 | 97 | 98 | def update(self, *args): 99 | """Placeholder for update, since there is nothing to update""" 100 | pass 101 | 102 | 103 | class Finial(pg.sprite.Sprite): 104 | """The top of the flag pole""" 105 | def __init__(self, x, y): 106 | super(Finial, self).__init__() 107 | self.sprite_sheet = setup.GFX['tile_set'] 108 | self.setup_frames() 109 | self.image = self.frames[0] 110 | self.rect = self.image.get_rect() 111 | self.rect.centerx = x 112 | self.rect.bottom = y 113 | 114 | 115 | def setup_frames(self): 116 | """Creates the self.frames list""" 117 | self.frames = [] 118 | 119 | self.frames.append( 120 | self.get_image(228, 120, 8, 8)) 121 | 122 | 123 | def get_image(self, x, y, width, height): 124 | """Extracts image from sprite sheet""" 125 | image = pg.Surface([width, height]) 126 | rect = image.get_rect() 127 | 128 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 129 | image.set_colorkey(c.BLACK) 130 | image = pg.transform.scale(image, 131 | (int(rect.width*c.SIZE_MULTIPLIER), 132 | int(rect.height*c.SIZE_MULTIPLIER))) 133 | return image 134 | 135 | 136 | def update(self, *args): 137 | pass 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /dqn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import tensorflow as tf 3 | import numpy as np 4 | 5 | 6 | class DQN: 7 | def __init__(self, session, input_size, output_size, name="main", is_training=True): 8 | self.session = session 9 | self.input_size = input_size 10 | 11 | self.output_size = output_size 12 | 13 | self.net_name = name 14 | 15 | if is_training: 16 | self.keep_prob = 0.7 17 | else: 18 | self.keep_prob = 1.0 19 | 20 | self._build_network() 21 | self.saver = tf.train.Saver() 22 | self.save_path = "./save/save_model_" + self.net_name + ".ckpt" 23 | tf.logging.info(name + " - initialized") 24 | 25 | def _build_network(self, l_rate=0.3): 26 | with tf.variable_scope(self.net_name): 27 | keep_prob = self.keep_prob 28 | 29 | # input place holders 30 | self._X = tf.placeholder(tf.float32, [None, self.input_size], name="input_x") 31 | self._keep_prob = tf.placeholder(tf.float32, name="kp") 32 | self.X_img = tf.reshape(self._X, [-1, 90, 90, 1]) 33 | 34 | # Conv 35 | W1 = tf.Variable(tf.random_normal([8, 8, 1, 64], stddev=0.01)) 36 | L1 = tf.nn.conv2d(self.X_img, W1, strides=[1, 4, 4, 1], padding='SAME') 37 | L1 = tf.nn.relu(L1) 38 | L1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1], 39 | strides=[1, 2, 2, 1], padding='SAME') 40 | L1 = tf.nn.dropout(L1, keep_prob=keep_prob) 41 | 42 | W2 = tf.Variable(tf.random_normal([4, 4, 64, 128], stddev=0.01)) 43 | L2 = tf.nn.conv2d(L1, W2, strides=[1, 2, 2, 1], padding='SAME') 44 | L2 = tf.nn.relu(L2) 45 | L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], 46 | strides=[1, 2, 2, 1], padding='SAME') 47 | L2 = tf.nn.dropout(L2, keep_prob=keep_prob) 48 | 49 | # L3 ImgIn shape=(?, 7, 7, 64) 50 | W3 = tf.Variable(tf.random_normal([3, 3, 128, 256], stddev=0.01)) 51 | L3 = tf.nn.conv2d(L2, W3, strides=[1, 1, 1, 1], padding='SAME') 52 | L3 = tf.nn.relu(L3) 53 | L3 = tf.nn.max_pool(L3, ksize=[1, 2, 2, 1], strides=[ 54 | 1, 2, 2, 1], padding='SAME') 55 | L3 = tf.nn.dropout(L3, keep_prob=keep_prob) 56 | 57 | print L3 58 | 59 | L3 = tf.reshape(L3, [-1, 256 * 2 * 2]) 60 | 61 | W4 = tf.get_variable("W4", shape=[256 * 2 * 2, 2048], 62 | initializer=tf.contrib.layers.xavier_initializer()) 63 | b4 = tf.Variable(tf.random_normal([2048])) 64 | L4 = tf.nn.relu(tf.matmul(L3, W4) + b4) 65 | L4 = tf.nn.dropout(L4, keep_prob=keep_prob) 66 | 67 | # L5 Final FC 625 inputs -> 10 outputs 68 | W5 = tf.get_variable("W5", shape=[2048, self.output_size], 69 | initializer=tf.contrib.layers.xavier_initializer()) 70 | b5 = tf.Variable(tf.random_normal([self.output_size])) 71 | 72 | hypothesis = tf.matmul(L4, W5) + b5 73 | 74 | # cost/loss function 75 | # cost = tf.reduce_mean(tf.square(Y - hypothesis)) 76 | #net = tf.layers.dense(net, self.output_size) 77 | self._Qpred = hypothesis 78 | 79 | self._Y = tf.placeholder(shape=[None, self.output_size], dtype=tf.float32) 80 | 81 | self._loss = tf.reduce_mean(tf.square(self._Y - self._Qpred)) 82 | 83 | self._train = tf.train.AdamOptimizer(learning_rate=l_rate).minimize(self._loss) 84 | 85 | #self._train = tf.train.RMSPropOptimizer( 86 | # l_rate, momentum=0.95, epsilon=0.01).minimize(self._loss) 87 | 88 | 89 | correct_prediction = tf.equal(tf.argmax(self._Qpred, 1), tf.argmax(self._Y, 1)) 90 | self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 91 | 92 | def save(self, episode=0): 93 | self.saver.save(self.session, self.save_path+ "-" + str(episode)) 94 | 95 | def restore(self, episode=0): 96 | load_path = self.save_path + "-" + str(episode) 97 | self.saver.restore(self.session, load_path) 98 | 99 | def predict(self, state): 100 | x = np.reshape(state, [1, self.input_size]) 101 | predict = self.session.run(self._Qpred, feed_dict={self._X: x, self._keep_prob: 1.0}) 102 | return predict 103 | 104 | def val_test(self, x_stack, y_stack): 105 | return self.session.run([self._Qpred, self._Y], feed_dict={ 106 | self._X: x_stack, 107 | self._Y: y_stack, 108 | self._keep_prob: 0.7 109 | }) 110 | 111 | def update(self, x_stack, y_stack): 112 | return self.session.run([self._loss, self._train, self.accuracy], feed_dict={ 113 | self._X: x_stack, 114 | self._Y: y_stack, 115 | self._keep_prob: 0.7 116 | }) 117 | -------------------------------------------------------------------------------- /data/components/coin_box.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | from . import powerups 7 | from . import coin 8 | 9 | 10 | 11 | class Coin_box(pg.sprite.Sprite): 12 | """Coin box sprite""" 13 | def __init__(self, x, y, contents='coin', group=None): 14 | pg.sprite.Sprite.__init__(self) 15 | self.sprite_sheet = setup.GFX['tile_set'] 16 | self.frames = [] 17 | self.setup_frames() 18 | self.frame_index = 0 19 | self.image = self.frames[self.frame_index] 20 | self.rect = self.image.get_rect() 21 | self.rect.x = x 22 | self.rect.y = y 23 | self.mask = pg.mask.from_surface(self.image) 24 | self.animation_timer = 0 25 | self.first_half = True # First half of animation cycle 26 | self.state = c.RESTING 27 | self.rest_height = y 28 | self.gravity = 1.2 29 | self.y_vel = 0 30 | self.contents = contents 31 | self.group = group 32 | 33 | 34 | def get_image(self, x, y, width, height): 35 | """Extract image from sprite sheet""" 36 | image = pg.Surface([width, height]).convert() 37 | rect = image.get_rect() 38 | 39 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 40 | image.set_colorkey(c.BLACK) 41 | 42 | image = pg.transform.scale(image, 43 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 44 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 45 | return image 46 | 47 | 48 | def setup_frames(self): 49 | """Create frame list""" 50 | self.frames.append( 51 | self.get_image(384, 0, 16, 16)) 52 | self.frames.append( 53 | self.get_image(400, 0, 16, 16)) 54 | self.frames.append( 55 | self.get_image(416, 0, 16, 16)) 56 | self.frames.append( 57 | self.get_image(432, 0, 16, 16)) 58 | 59 | 60 | def update(self, game_info): 61 | """Update coin box behavior""" 62 | self.current_time = game_info[c.CURRENT_TIME] 63 | self.handle_states() 64 | 65 | 66 | def handle_states(self): 67 | """Determine action based on RESTING, BUMPED or OPENED 68 | state""" 69 | if self.state == c.RESTING: 70 | self.resting() 71 | elif self.state == c.BUMPED: 72 | self.bumped() 73 | elif self.state == c.OPENED: 74 | self.opened() 75 | 76 | 77 | def resting(self): 78 | """Action when in the RESTING state""" 79 | if self.first_half: 80 | if self.frame_index == 0: 81 | if (self.current_time - self.animation_timer) > 375: 82 | self.frame_index += 1 83 | self.animation_timer = self.current_time 84 | elif self.frame_index < 2: 85 | if (self.current_time - self.animation_timer) > 125: 86 | self.frame_index += 1 87 | self.animation_timer = self.current_time 88 | elif self.frame_index == 2: 89 | if (self.current_time - self.animation_timer) > 125: 90 | self.frame_index -= 1 91 | self.first_half = False 92 | self.animation_timer = self.current_time 93 | else: 94 | if self.frame_index == 1: 95 | if (self.current_time - self.animation_timer) > 125: 96 | self.frame_index -= 1 97 | self.first_half = True 98 | self.animation_timer = self.current_time 99 | 100 | self.image = self.frames[self.frame_index] 101 | 102 | 103 | def bumped(self): 104 | """Action after Mario has bumped the box from below""" 105 | self.rect.y += self.y_vel 106 | self.y_vel += self.gravity 107 | 108 | if self.rect.y > self.rest_height + 5: 109 | self.rect.y = self.rest_height 110 | self.state = c.OPENED 111 | if self.contents == 'mushroom': 112 | self.group.add(powerups.Mushroom(self.rect.centerx, self.rect.y)) 113 | elif self.contents == 'fireflower': 114 | self.group.add(powerups.FireFlower(self.rect.centerx, self.rect.y)) 115 | elif self.contents == '1up_mushroom': 116 | self.group.add(powerups.LifeMushroom(self.rect.centerx, self.rect.y)) 117 | 118 | 119 | self.frame_index = 3 120 | self.image = self.frames[self.frame_index] 121 | 122 | 123 | def start_bump(self, score_group): 124 | """Transitions box into BUMPED state""" 125 | self.y_vel = -6 126 | self.state = c.BUMPED 127 | 128 | if self.contents == 'coin': 129 | self.group.add(coin.Coin(self.rect.centerx, 130 | self.rect.y, 131 | score_group)) 132 | setup.SFX['coin'].play() 133 | else: 134 | setup.SFX['powerup_appears'].play() 135 | 136 | 137 | def opened(self): 138 | """Placeholder for OPENED state""" 139 | pass 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | -------------------------------------------------------------------------------- /data/states/main_menu.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup, tools 5 | from .. import constants as c 6 | from .. components import info, mario 7 | 8 | 9 | class Menu(tools._State): 10 | def __init__(self): 11 | """Initializes the state""" 12 | tools._State.__init__(self) 13 | persist = {c.COIN_TOTAL: 0, 14 | c.SCORE: 0, 15 | c.LIVES: 3, 16 | c.TOP_SCORE: 0, 17 | c.CURRENT_TIME: 0.0, 18 | c.LEVEL_STATE: None, 19 | c.CAMERA_START_X: 0, 20 | c.MARIO_DEAD: False} 21 | self.startup(0.0, persist) 22 | 23 | def startup(self, current_time, persist): 24 | """Called every time the game's state becomes this one. Initializes 25 | certain values""" 26 | self.next = c.LOAD_SCREEN 27 | self.persist = persist 28 | self.game_info = persist 29 | self.overhead_info = info.OverheadInfo(self.game_info, c.MAIN_MENU) 30 | 31 | self.sprite_sheet = setup.GFX['title_screen'] 32 | self.setup_background() 33 | self.setup_mario() 34 | self.setup_cursor() 35 | 36 | 37 | def setup_cursor(self): 38 | """Creates the mushroom cursor to select 1 or 2 player game""" 39 | self.cursor = pg.sprite.Sprite() 40 | dest = (220, 358) 41 | self.cursor.image, self.cursor.rect = self.get_image( 42 | 24, 160, 8, 8, dest, setup.GFX['item_objects']) 43 | self.cursor.state = c.PLAYER1 44 | 45 | 46 | def setup_mario(self): 47 | """Places Mario at the beginning of the level""" 48 | self.mario = mario.Mario() 49 | self.mario.rect.x = 110 50 | self.mario.rect.bottom = c.GROUND_HEIGHT 51 | 52 | 53 | def setup_background(self): 54 | """Setup the background image to blit""" 55 | self.background = setup.GFX['level_1'] 56 | self.background_rect = self.background.get_rect() 57 | self.background = pg.transform.scale(self.background, 58 | (int(self.background_rect.width*c.BACKGROUND_MULTIPLER), 59 | int(self.background_rect.height*c.BACKGROUND_MULTIPLER))) 60 | self.viewport = setup.SCREEN.get_rect(bottom=setup.SCREEN_RECT.bottom) 61 | 62 | self.image_dict = {} 63 | self.image_dict['GAME_NAME_BOX'] = self.get_image( 64 | 1, 60, 176, 88, (170, 100), setup.GFX['title_screen']) 65 | 66 | 67 | 68 | def get_image(self, x, y, width, height, dest, sprite_sheet): 69 | """Returns images and rects to blit onto the screen""" 70 | image = pg.Surface([width, height]) 71 | rect = image.get_rect() 72 | 73 | image.blit(sprite_sheet, (0, 0), (x, y, width, height)) 74 | if sprite_sheet == setup.GFX['title_screen']: 75 | image.set_colorkey((255, 0, 220)) 76 | image = pg.transform.scale(image, 77 | (int(rect.width*c.SIZE_MULTIPLIER), 78 | int(rect.height*c.SIZE_MULTIPLIER))) 79 | else: 80 | image.set_colorkey(c.BLACK) 81 | image = pg.transform.scale(image, 82 | (int(rect.width*3), 83 | int(rect.height*3))) 84 | 85 | rect = image.get_rect() 86 | rect.x = dest[0] 87 | rect.y = dest[1] 88 | return (image, rect) 89 | 90 | 91 | def update(self, surface, keys, current_time): 92 | """Updates the state every refresh""" 93 | self.current_time = current_time 94 | self.game_info[c.CURRENT_TIME] = self.current_time 95 | self.update_cursor(keys) 96 | self.overhead_info.update(self.game_info) 97 | 98 | surface.blit(self.background, self.viewport, self.viewport) 99 | surface.blit(self.image_dict['GAME_NAME_BOX'][0], 100 | self.image_dict['GAME_NAME_BOX'][1]) 101 | surface.blit(self.mario.image, self.mario.rect) 102 | surface.blit(self.cursor.image, self.cursor.rect) 103 | self.overhead_info.draw(surface) 104 | 105 | 106 | def update_cursor(self, keys): 107 | """Update the position of the cursor""" 108 | input_list = [pg.K_RETURN, pg.K_a, pg.K_s] 109 | 110 | if self.cursor.state == c.PLAYER1: 111 | self.cursor.rect.y = 358 112 | if keys[pg.K_DOWN]: 113 | self.cursor.state = c.PLAYER2 114 | for input in input_list: 115 | if keys[input]: 116 | self.reset_game_info() 117 | self.done = True 118 | elif self.cursor.state == c.PLAYER2: 119 | self.cursor.rect.y = 403 120 | if keys[pg.K_UP]: 121 | self.cursor.state = c.PLAYER1 122 | 123 | 124 | def reset_game_info(self): 125 | """Resets the game info in case of a Game Over and restart""" 126 | self.game_info[c.COIN_TOTAL] = 0 127 | self.game_info[c.SCORE] = 0 128 | self.game_info[c.LIVES] = 3 129 | self.game_info[c.CURRENT_TIME] = 0.0 130 | self.game_info[c.LEVEL_STATE] = None 131 | 132 | self.persist = self.game_info 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | -------------------------------------------------------------------------------- /data/components/enemies.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | 4 | import pygame as pg 5 | from .. import setup 6 | from .. import constants as c 7 | 8 | 9 | class Enemy(pg.sprite.Sprite): 10 | """Base class for all enemies (Goombas, Koopas, etc.)""" 11 | def __init__(self): 12 | pg.sprite.Sprite.__init__(self) 13 | 14 | 15 | def setup_enemy(self, x, y, direction, name, setup_frames): 16 | """Sets up various values for enemy""" 17 | self.sprite_sheet = setup.GFX['smb_enemies_sheet'] 18 | self.frames = [] 19 | self.frame_index = 0 20 | self.animate_timer = 0 21 | self.death_timer = 0 22 | self.gravity = 1.5 23 | self.state = c.WALK 24 | 25 | self.name = name 26 | self.direction = direction 27 | setup_frames() 28 | 29 | self.image = self.frames[self.frame_index] 30 | self.rect = self.image.get_rect() 31 | self.rect.x = x 32 | self.rect.bottom = y 33 | self.set_velocity() 34 | 35 | 36 | def set_velocity(self): 37 | """Sets velocity vector based on direction""" 38 | if self.direction == c.LEFT: 39 | self.x_vel = -2 40 | else: 41 | self.x_vel = 2 42 | 43 | self.y_vel = 0 44 | 45 | 46 | def get_image(self, x, y, width, height): 47 | """Get the image frames from the sprite sheet""" 48 | image = pg.Surface([width, height]).convert() 49 | rect = image.get_rect() 50 | 51 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 52 | image.set_colorkey(c.BLACK) 53 | 54 | 55 | image = pg.transform.scale(image, 56 | (int(rect.width*c.SIZE_MULTIPLIER), 57 | int(rect.height*c.SIZE_MULTIPLIER))) 58 | return image 59 | 60 | 61 | def handle_state(self): 62 | """Enemy behavior based on state""" 63 | if self.state == c.WALK: 64 | self.walking() 65 | elif self.state == c.FALL: 66 | self.falling() 67 | elif self.state == c.JUMPED_ON: 68 | self.jumped_on() 69 | elif self.state == c.SHELL_SLIDE: 70 | self.shell_sliding() 71 | elif self.state == c.DEATH_JUMP: 72 | self.death_jumping() 73 | 74 | 75 | def walking(self): 76 | """Default state of moving sideways""" 77 | if (self.current_time - self.animate_timer) > 125: 78 | if self.frame_index == 0: 79 | self.frame_index += 1 80 | elif self.frame_index == 1: 81 | self.frame_index = 0 82 | 83 | self.animate_timer = self.current_time 84 | 85 | 86 | def falling(self): 87 | """For when it falls off a ledge""" 88 | if self.y_vel < 10: 89 | self.y_vel += self.gravity 90 | 91 | 92 | def jumped_on(self): 93 | """Placeholder for when the enemy is stomped on""" 94 | pass 95 | 96 | 97 | def death_jumping(self): 98 | """Death animation""" 99 | self.rect.y += self.y_vel 100 | self.rect.x += self.x_vel 101 | self.y_vel += self.gravity 102 | 103 | if self.rect.y > 600: 104 | self.kill() 105 | 106 | 107 | def start_death_jump(self, direction): 108 | """Transitions enemy into a DEATH JUMP state""" 109 | self.y_vel = -8 110 | if direction == c.RIGHT: 111 | self.x_vel = 2 112 | else: 113 | self.x_vel = -2 114 | self.gravity = .5 115 | self.frame_index = 3 116 | self.image = self.frames[self.frame_index] 117 | self.state = c.DEATH_JUMP 118 | 119 | 120 | def animation(self): 121 | """Basic animation, switching between two frames""" 122 | self.image = self.frames[self.frame_index] 123 | 124 | 125 | def update(self, game_info, *args): 126 | """Updates enemy behavior""" 127 | self.current_time = game_info[c.CURRENT_TIME] 128 | self.handle_state() 129 | self.animation() 130 | 131 | 132 | 133 | 134 | class Goomba(Enemy): 135 | 136 | def __init__(self, y=c.GROUND_HEIGHT, x=0, direction=c.LEFT, name='goomba'): 137 | Enemy.__init__(self) 138 | self.setup_enemy(x, y, direction, name, self.setup_frames) 139 | 140 | 141 | def setup_frames(self): 142 | """Put the image frames in a list to be animated""" 143 | 144 | self.frames.append( 145 | self.get_image(0, 4, 16, 16)) 146 | self.frames.append( 147 | self.get_image(30, 4, 16, 16)) 148 | self.frames.append( 149 | self.get_image(61, 0, 16, 16)) 150 | self.frames.append(pg.transform.flip(self.frames[1], False, True)) 151 | 152 | 153 | def jumped_on(self): 154 | """When Mario squishes him""" 155 | self.frame_index = 2 156 | 157 | if (self.current_time - self.death_timer) > 500: 158 | self.kill() 159 | 160 | 161 | 162 | class Koopa(Enemy): 163 | 164 | def __init__(self, y=c.GROUND_HEIGHT, x=0, direction=c.LEFT, name='koopa'): 165 | Enemy.__init__(self) 166 | self.setup_enemy(x, y, direction, name, self.setup_frames) 167 | 168 | 169 | def setup_frames(self): 170 | """Sets frame list""" 171 | self.frames.append( 172 | self.get_image(150, 0, 16, 24)) 173 | self.frames.append( 174 | self.get_image(180, 0, 16, 24)) 175 | self.frames.append( 176 | self.get_image(360, 5, 16, 15)) 177 | self.frames.append(pg.transform.flip(self.frames[2], False, True)) 178 | 179 | 180 | def jumped_on(self): 181 | """When Mario jumps on the Koopa and puts him in his shell""" 182 | self.x_vel = 0 183 | self.frame_index = 2 184 | shell_y = self.rect.bottom 185 | shell_x = self.rect.x 186 | self.rect = self.frames[self.frame_index].get_rect() 187 | self.rect.x = shell_x 188 | self.rect.bottom = shell_y 189 | 190 | 191 | def shell_sliding(self): 192 | """When the koopa is sliding along the ground in his shell""" 193 | if self.direction == c.RIGHT: 194 | self.x_vel = 10 195 | elif self.direction == c.LEFT: 196 | self.x_vel = -10 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | -------------------------------------------------------------------------------- /data/components/bricks.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | from . import powerups 7 | from . import coin 8 | 9 | 10 | class Brick(pg.sprite.Sprite): 11 | """Bricks that can be destroyed""" 12 | def __init__(self, x, y, contents=None, powerup_group=None, name='brick'): 13 | """Initialize the object""" 14 | pg.sprite.Sprite.__init__(self) 15 | self.sprite_sheet = setup.GFX['tile_set'] 16 | 17 | self.frames = [] 18 | self.frame_index = 0 19 | self.setup_frames() 20 | self.image = self.frames[self.frame_index] 21 | self.rect = self.image.get_rect() 22 | self.rect.x = x 23 | self.rect.y = y 24 | self.mask = pg.mask.from_surface(self.image) 25 | self.bumped_up = False 26 | self.rest_height = y 27 | self.state = c.RESTING 28 | self.y_vel = 0 29 | self.gravity = 1.2 30 | self.name = name 31 | self.contents = contents 32 | self.setup_contents() 33 | self.group = powerup_group 34 | self.powerup_in_box = True 35 | 36 | 37 | def get_image(self, x, y, width, height): 38 | """Extracts the image from the sprite sheet""" 39 | image = pg.Surface([width, height]).convert() 40 | rect = image.get_rect() 41 | 42 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 43 | image.set_colorkey(c.BLACK) 44 | image = pg.transform.scale(image, 45 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 46 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 47 | return image 48 | 49 | 50 | def setup_frames(self): 51 | """Set the frames to a list""" 52 | self.frames.append(self.get_image(16, 0, 16, 16)) 53 | self.frames.append(self.get_image(432, 0, 16, 16)) 54 | 55 | 56 | def setup_contents(self): 57 | """Put 6 coins in contents if needed""" 58 | if self.contents == '6coins': 59 | self.coin_total = 6 60 | else: 61 | self.coin_total = 0 62 | 63 | 64 | def update(self): 65 | """Updates the brick""" 66 | self.handle_states() 67 | 68 | 69 | def handle_states(self): 70 | """Determines brick behavior based on state""" 71 | if self.state == c.RESTING: 72 | self.resting() 73 | elif self.state == c.BUMPED: 74 | self.bumped() 75 | elif self.state == c.OPENED: 76 | self.opened() 77 | 78 | 79 | def resting(self): 80 | """State when not moving""" 81 | if self.contents == '6coins': 82 | if self.coin_total == 0: 83 | self.state == c.OPENED 84 | 85 | 86 | def bumped(self): 87 | """Action during a BUMPED state""" 88 | self.rect.y += self.y_vel 89 | self.y_vel += self.gravity 90 | 91 | if self.rect.y >= (self.rest_height + 5): 92 | self.rect.y = self.rest_height 93 | if self.contents == 'star': 94 | self.state = c.OPENED 95 | elif self.contents == '6coins': 96 | if self.coin_total == 0: 97 | self.state = c.OPENED 98 | else: 99 | self.state = c.RESTING 100 | else: 101 | self.state = c.RESTING 102 | 103 | 104 | def start_bump(self, score_group): 105 | """Transitions brick into BUMPED state""" 106 | self.y_vel = -6 107 | 108 | if self.contents == '6coins': 109 | setup.SFX['coin'].play() 110 | 111 | if self.coin_total > 0: 112 | self.group.add(coin.Coin(self.rect.centerx, self.rect.y, score_group)) 113 | self.coin_total -= 1 114 | if self.coin_total == 0: 115 | self.frame_index = 1 116 | self.image = self.frames[self.frame_index] 117 | elif self.contents == 'star': 118 | setup.SFX['powerup_appears'].play() 119 | self.frame_index = 1 120 | self.image = self.frames[self.frame_index] 121 | 122 | self.state = c.BUMPED 123 | 124 | 125 | def opened(self): 126 | """Action during OPENED state""" 127 | self.frame_index = 1 128 | self.image = self.frames[self.frame_index] 129 | 130 | if self.contents == 'star' and self.powerup_in_box: 131 | self.group.add(powerups.Star(self.rect.centerx, self.rest_height)) 132 | self.powerup_in_box = False 133 | 134 | 135 | class BrickPiece(pg.sprite.Sprite): 136 | """Pieces that appear when bricks are broken""" 137 | def __init__(self, x, y, xvel, yvel): 138 | super(BrickPiece, self).__init__() 139 | self.sprite_sheet = setup.GFX['item_objects'] 140 | self.setup_frames() 141 | self.frame_index = 0 142 | self.image = self.frames[self.frame_index] 143 | self.rect = self.image.get_rect() 144 | self.rect.x = x 145 | self.rect.y = y 146 | self.x_vel = xvel 147 | self.y_vel = yvel 148 | self.gravity = .8 149 | 150 | 151 | def setup_frames(self): 152 | """create the frame list""" 153 | self.frames = [] 154 | 155 | image = self.get_image(68, 20, 8, 8) 156 | reversed_image = pg.transform.flip(image, True, False) 157 | 158 | self.frames.append(image) 159 | self.frames.append(reversed_image) 160 | 161 | 162 | def get_image(self, x, y, width, height): 163 | """Extract image from sprite sheet""" 164 | image = pg.Surface([width, height]).convert() 165 | rect = image.get_rect() 166 | 167 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 168 | image.set_colorkey(c.BLACK) 169 | image = pg.transform.scale(image, 170 | (int(rect.width*c.BRICK_SIZE_MULTIPLIER), 171 | int(rect.height*c.BRICK_SIZE_MULTIPLIER))) 172 | return image 173 | 174 | 175 | def update(self): 176 | """Update brick piece""" 177 | self.rect.x += self.x_vel 178 | self.rect.y += self.y_vel 179 | self.y_vel += self.gravity 180 | self.check_if_off_screen() 181 | 182 | def check_if_off_screen(self): 183 | """Remove from sprite groups if off screen""" 184 | if self.rect.y > c.SCREEN_HEIGHT: 185 | self.kill() 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | -------------------------------------------------------------------------------- /data/tools.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import os 4 | import pygame as pg 5 | from pygame.surfarray import pixels3d, array3d 6 | from . import constants as c 7 | import platform 8 | import setup 9 | from collections import deque 10 | 11 | 12 | p_name = platform.system() 13 | 14 | keybinding = { 15 | 'action':pg.K_s, 16 | 'jump':pg.K_a, 17 | 'left':pg.K_LEFT, 18 | 'right':pg.K_RIGHT, 19 | 'down':pg.K_DOWN 20 | } 21 | 22 | class Control(object): 23 | """Control class for entire project. Contains the game loop, and contains 24 | the event_loop which passes events to States as needed. Logic for flipping 25 | states is also found here.""" 26 | def __init__(self, caption, env): 27 | self.screen = pg.display.get_surface() 28 | self.done = False 29 | self.clock = pg.time.Clock() 30 | self.caption = caption 31 | #self.fps = 60 32 | self.fps = 100000 33 | self.show_fps = False 34 | self.current_time = 0.0 35 | self.keys = pg.key.get_pressed() 36 | self.state_dict = {} 37 | self.state_name = None 38 | self.state = None 39 | self.ml_done = False 40 | self.max_posision_x = 200 41 | self.correct_x = 80 42 | self.before_x = 200 43 | 44 | def setup_states(self, state_dict, start_state): 45 | self.state_dict = state_dict 46 | self.state_name = start_state 47 | self.state = self.state_dict[self.state_name] 48 | 49 | def update(self): 50 | self.current_time = pg.time.get_ticks() 51 | if self.state.quit: 52 | self.done = True 53 | elif self.state.done: 54 | self.flip_state() 55 | self.state.update(self.screen, self.keys, self.current_time) 56 | 57 | # position start = 200 / end=8519 58 | if self.state.mario.dead: 59 | self.ml_done = True 60 | 61 | 62 | 63 | def flip_state(self): 64 | previous, self.state_name = self.state_name, self.state.next 65 | persist = self.state.cleanup() 66 | self.state = self.state_dict[self.state_name] 67 | self.state.startup(self.current_time, persist) 68 | self.state.previous = previous 69 | 70 | 71 | def get_step(self): 72 | if p_name == "Darwin": 73 | next_state = pixels3d(self.screen) 74 | else: 75 | next_state = array3d(setup.SCREEN) 76 | 77 | reward = 0 78 | score = self.state.get_score() 79 | position_x = self.state.last_x_position 80 | if position_x > self.max_posision_x: 81 | reward += (position_x - self.max_posision_x)*2 82 | self.max_posision_x = position_x 83 | else: 84 | reward = 0 85 | 86 | reward = reward + score 87 | 88 | # time penalty 89 | #reward -= 0.1 90 | #if self.keys[275] == 1: 91 | # reward += 1 92 | ''' 93 | if self.keys[276] == 1: 94 | reward -= 1 95 | elif self.keys[275] == 1: 96 | reward += 1 97 | ''' 98 | 99 | if self.keys[275] == 1: 100 | reward += 1 101 | else: 102 | reward -= 5 103 | 104 | ''' 105 | if self.before_x < position_x: 106 | reward += position_x - self.before_x 107 | self.before_x = position_x 108 | ''' 109 | 110 | #if position_x < 70 and position_x != 0: 111 | # self.ml_done = True 112 | 113 | return (next_state, reward, self.ml_done, self.state.clear, 114 | self.max_posision_x, self.state.timeout, position_x) 115 | 116 | 117 | 118 | def event_loop(self, key): 119 | if key != None and self.keys != key: 120 | self.keys = key 121 | 122 | else: 123 | for event in pg.event.get(): 124 | if event.type == pg.QUIT: 125 | self.done = True 126 | elif event.type == pg.KEYDOWN: 127 | self.keys = pg.key.get_pressed() 128 | self.toggle_show_fps(event.key) 129 | elif event.type == pg.KEYUP: 130 | self.keys = pg.key.get_pressed() 131 | self.state.get_event(event) 132 | 133 | def toggle_show_fps(self, key): 134 | if key == pg.K_F5: 135 | self.show_fps = not self.show_fps 136 | if not self.show_fps: 137 | pg.display.set_caption(self.caption) 138 | 139 | 140 | def main(self): 141 | """Main loop for entire program""" 142 | while not self.done: 143 | self.event_loop() 144 | self.update() 145 | pg.display.update() 146 | self.clock.tick(self.fps) 147 | if self.show_fps: 148 | fps = self.clock.get_fps() 149 | with_fps = "{} - {:.2f} FPS".format(self.caption, fps) 150 | pg.display.set_caption(with_fps) 151 | 152 | 153 | class _State(object): 154 | def __init__(self): 155 | self.start_time = 0.0 156 | self.current_time = 0.0 157 | self.done = False 158 | self.quit = False 159 | self.next = None 160 | self.previous = None 161 | self.persist = {} 162 | self.score = 0 163 | self.last_x_position = 0 164 | 165 | def get_score(self): 166 | tmp = self.score 167 | self.score = 0 168 | return tmp 169 | 170 | def get_event(self, event): 171 | pass 172 | 173 | def startup(self, current_time, persistant): 174 | self.persist = persistant 175 | self.start_time = current_time 176 | 177 | def cleanup(self): 178 | self.done = False 179 | return self.persist 180 | 181 | def update(self, surface, keys, current_time): 182 | pass 183 | 184 | 185 | 186 | def load_all_gfx(directory, colorkey=(255,0,255), accept=('.png', 'jpg', 'bmp')): 187 | graphics = {} 188 | for pic in os.listdir(directory): 189 | name, ext = os.path.splitext(pic) 190 | if ext.lower() in accept: 191 | img = pg.image.load(os.path.join(directory, pic)) 192 | if img.get_alpha(): 193 | img = img.convert_alpha() 194 | else: 195 | img = img.convert() 196 | img.set_colorkey(colorkey) 197 | graphics[name]=img 198 | return graphics 199 | 200 | 201 | def load_all_music(directory, accept=('.wav', '.mp3', '.ogg', '.mdi')): 202 | songs = {} 203 | for song in os.listdir(directory): 204 | name,ext = os.path.splitext(song) 205 | if ext.lower() in accept: 206 | songs[name] = os.path.join(directory, song) 207 | return songs 208 | 209 | 210 | def load_all_fonts(directory, accept=('.ttf')): 211 | return load_all_music(directory, accept) 212 | 213 | 214 | def load_all_sfx(directory, accept=('.wav','.mpe','.ogg','.mdi')): 215 | effects = {} 216 | for fx in os.listdir(directory): 217 | name, ext = os.path.splitext(fx) 218 | if ext.lower() in accept: 219 | effects[name] = pg.mixer.Sound(os.path.join(directory, fx)) 220 | return effects 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | -------------------------------------------------------------------------------- /ttest.py: -------------------------------------------------------------------------------- 1 | 2 | import random 3 | import numpy as np 4 | import math 5 | actions = { 6 | 0: ( 7 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 75 | 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) 76 | } 77 | 78 | a = 1e-2 79 | 80 | from collections import deque 81 | 82 | q = deque() 83 | for i in range(10): 84 | q.append(i) 85 | 86 | print q[-1] 87 | print q -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import tensorflow as tf 3 | import numpy as np 4 | import random 5 | 6 | from collections import deque 7 | from data.env import Env 8 | from tensorflow.python.framework.errors_impl import NotFoundError 9 | import time 10 | import threading 11 | import png 12 | 13 | 14 | 15 | class AIControl: 16 | def __init__(self, env): 17 | self.env = env 18 | 19 | self.input_size = self.env.state_n 20 | self.output_size = 14 21 | 22 | #self.dis = 0.9 23 | self.dis = 0.9 24 | self.val = 0 25 | self.save_path = "./save/save_model" 26 | 27 | self.max_episodes = 20000001 28 | 29 | self.replay_buffer = deque() 30 | self.episode_buffer = deque() 31 | 32 | self.MAX_BUFFER_SIZE = 40000 33 | 34 | self.frame_action = 3 35 | self.training = True 36 | self.step = 8351 37 | 38 | 39 | def async_training(self, sess, ops): 40 | epoch = 100 41 | batch_size = 200 42 | while self.training: 43 | if len(self.replay_buffer) > self.MAX_BUFFER_SIZE/10: 44 | #replay_buffer, episode, step_count, max_x, reward_sum = self.episode_buffer.popleft() 45 | replay_buffer = list(self.replay_buffer) 46 | for idx in range(epoch): 47 | batch = random.sample(replay_buffer, batch_size) 48 | loss = self.replay_train(self.mainDQN, self.targetDQN, batch) 49 | print("Step: {}-{} Loss: {}".format(self.step, idx, loss)) 50 | sess.run(ops) 51 | #sess.run(ops_temp) 52 | 53 | # 50 에피소드마다 저장한다 54 | if self.step % 50 == 0: 55 | self.mainDQN.save(episode=self.step) 56 | self.targetDQN.save(episode=self.step) 57 | self.step += 1 58 | else: 59 | time.sleep(1) 60 | 61 | 62 | 63 | def replay_train(self, mainDQN, targetDQN, train_batch): 64 | x_stack = np.empty(0).reshape(0, self.input_size) 65 | y_stack = np.empty(0).reshape(0, self.output_size) 66 | 67 | for state, action, reward, next_state, done in train_batch: 68 | Q = mainDQN.predict(state) 69 | 70 | if done: 71 | Q[0, action] = reward 72 | else: 73 | Q[0, action] = reward + self.dis * \ 74 | targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))] 75 | 76 | state = np.reshape(state, [self.input_size]) 77 | 78 | y_stack = np.vstack([y_stack, Q]) 79 | x_stack = np.vstack([x_stack, state]) 80 | 81 | return mainDQN.update(x_stack, y_stack) 82 | 83 | def get_copy_var_ops(self, dest_scope_name="target", src_scope_name="main"): 84 | op_holder = [] 85 | 86 | src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name) 87 | dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name) 88 | 89 | for src_var, dest_var in zip(src_vars, dest_vars): 90 | op_holder.append(dest_var.assign(src_var.value())) 91 | 92 | return op_holder 93 | 94 | def control_start(self): 95 | import dqn 96 | with tf.Session() as sess: 97 | self.mainDQN = dqn.DQN(sess, self.input_size, self.output_size, name="main") 98 | self.targetDQN = dqn.DQN(sess, self.input_size, self.output_size, name="target") 99 | #self.tempDQN = dqn.DQN(sess, self.input_size, self.output_size, name="temp") 100 | tf.global_variables_initializer().run() 101 | 102 | episode = 8350 103 | best_x = 0 104 | try: 105 | self.mainDQN.restore(episode) 106 | self.targetDQN.restore(episode) 107 | #self.tempDQN.restore(episode) 108 | except NotFoundError: 109 | print "save file not found" 110 | 111 | copy_ops = self.get_copy_var_ops() 112 | copy_ops_temp = self.get_copy_var_ops(dest_scope_name="main", src_scope_name="temp") 113 | #copy_ops_temp2 = self.get_copy_var_ops(dest_scope_name="temp", src_scope_name="main") 114 | sess.run(copy_ops) 115 | #sess.run(copy_ops_temp2) 116 | 117 | training_thread = threading.Thread(target=self.async_training, args=(sess, copy_ops)) 118 | training_thread.start() 119 | 120 | start_position = 500 121 | 122 | episode = 141500 123 | while episode < self.max_episodes: 124 | e = 0.2#max(0.05, min(0.75, 1 / ((self.step / 1000) + 0.2))) 125 | #max(0.05, min(0.3, 1. / ((episode / 5000) + 1))) 126 | 127 | done = False 128 | clear = False 129 | step_count = 0 130 | state = self.env.reset(start_position=start_position) 131 | max_x = 0 132 | now_x = 0 133 | reward_sum = 0 134 | before_action = [0, 0, 0, 0, 0, 0] 135 | 136 | input_list = [] 137 | 138 | hold_frame = 0 139 | before_max_x = 200 140 | 141 | step_reward = 0 142 | 143 | action_state = state 144 | while not done and not clear: 145 | 146 | if step_count % self.frame_action == 0: 147 | if np.random.rand(1) < e: 148 | action = self.env.get_random_actions() 149 | else: 150 | action = np.argmax(self.targetDQN.predict(state)) 151 | input_list.append(action) 152 | action_state = state 153 | else: 154 | action = before_action 155 | 156 | next_state, reward, done, clear, max_x, timeout, now_x = self.env.step(action) 157 | #print state 158 | step_reward += reward 159 | 160 | # 앞으로 나아가지 못하는 상황이 2000프레임 이상이면 종료하고 학습한다. 161 | if now_x <= before_max_x: 162 | hold_frame += 1 163 | if hold_frame > 2000: 164 | break 165 | else: 166 | hold_frame = 0 167 | before_max_x = max_x 168 | 169 | 170 | if step_count % self.frame_action == self.frame_action-1 \ 171 | or done or timeout or clear: 172 | if done and not clear: 173 | step_reward = -10000 174 | if clear: 175 | step_reward += 10000 176 | done = True 177 | 178 | self.replay_buffer.append((action_state, action, step_reward, next_state, done)) 179 | if len(self.replay_buffer) > self.MAX_BUFFER_SIZE: 180 | self.replay_buffer.popleft() 181 | step_reward = 0 182 | 183 | state = next_state 184 | step_count += 1 185 | 186 | reward_sum += reward 187 | before_action = action 188 | 189 | #png.from_array(next_state, 'L').save('capture/' + str(step_count) + '.png') 190 | 191 | with open('input_log/input', 'w') as fp: 192 | fp.write(str(episode) + ' - ' + str(input_list)) 193 | 194 | episode += 1 195 | ''' 196 | if len(self.replay_buffer) == self.MAX_BUFFER_SIZE: 197 | self.episode_buffer.append((self.replay_buffer, episode, step_count, max_x, reward_sum)) 198 | if len(self.episode_buffer) > 0: 199 | print 'buffer flush... plz wait...' 200 | while len(self.episode_buffer) != 0: 201 | time.sleep(1) 202 | self.replay_buffer = deque() 203 | 204 | 205 | epoch = 100 206 | batch_size = 200 207 | if episode % 20 == 0: 208 | # replay_buffer, episode, step_count, max_x, reward_sum = self.episode_buffer.popleft() 209 | replay_buffer = list(self.replay_buffer) 210 | for idx in range(epoch): 211 | batch = random.sample(replay_buffer, batch_size) 212 | loss = self.replay_train(self.mainDQN, self.targetDQN, batch) 213 | print("Step: {}-{} Loss: {}".format(step, idx, loss)) 214 | sess.run(copy_ops) 215 | 216 | # 50 에피소드마다 저장한다 217 | if step % 50 == 0: 218 | self.mainDQN.save(episode=step) 219 | self.targetDQN.save(episode=step) 220 | #self.tempDQN.save(episode=step) 221 | step += 1 222 | else: 223 | time.sleep(1) 224 | episode += 1 225 | ''' 226 | 227 | # 죽은 경우 죽은 지점의 600픽셀 이전에서 살아나서 다시 시도한다 228 | ''' 229 | if done and not timeout: 230 | start_position = now_x - 800 231 | else: 232 | start_position = 0 233 | ''' 234 | 235 | # 에피소드가 끝나면 종료하지말고 버퍼에있는 트레이닝을 마친다 236 | self.training = False 237 | training_thread.join() 238 | 239 | 240 | 241 | def main(): 242 | env = Env() 243 | controller = AIControl(env) 244 | controller.control_start() 245 | 246 | 247 | if __name__ == "__main__": 248 | main() 249 | 250 | #lightdm -------------------------------------------------------------------------------- /main_async.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import tensorflow as tf 3 | import numpy as np 4 | import random 5 | 6 | from collections import deque 7 | from data.env import Env 8 | from tensorflow.python.framework.errors_impl import NotFoundError 9 | import time 10 | import threading 11 | import png 12 | from multiprocessing import Process, Queue, Pipe, Value 13 | 14 | 15 | class DQNManager(Process): 16 | def __init__(self, input_size, output_size, train_q, pipe, is_training): 17 | Process.__init__(self) 18 | self.train_q = train_q 19 | self.pipe = pipe 20 | 21 | self.input_size = input_size 22 | self.output_size = 12 23 | 24 | self.dis = 0.9 25 | 26 | self.save_path = "./save/save_model" 27 | self.training = is_training 28 | 29 | def run(self): 30 | import dqn 31 | with tf.Session() as sess: 32 | self.sess = sess 33 | self.mainDQN = dqn.DQN(sess, self.input_size, self.output_size, name="main") 34 | self.targetDQN = dqn.DQN(sess, self.input_size, self.output_size, name="target") 35 | self.tempDQN = dqn.DQN(sess, self.input_size, self.output_size, name="temp") 36 | tf.global_variables_initializer().run() 37 | 38 | episode = 5100 39 | try: 40 | self.mainDQN.restore(episode) 41 | self.targetDQN.restore(episode) 42 | self.tempDQN.restore(episode) 43 | except NotFoundError: 44 | print "save file not found" 45 | 46 | self.copy_ops = self.get_copy_var_ops() 47 | self.copy_ops_temp = self.get_copy_var_ops(dest_scope_name="main", src_scope_name="temp") 48 | self.copy_ops_temp2 = self.get_copy_var_ops(dest_scope_name="temp", src_scope_name="main") 49 | sess.run(self.copy_ops) 50 | sess.run(self.copy_ops_temp2) 51 | 52 | predict_thread = threading.Thread(target=self.predict) 53 | train_thread = threading.Thread(target=self.train) 54 | predict_thread.start() 55 | train_thread.start() 56 | train_thread.join() 57 | predict_thread.join() 58 | 59 | def predict(self): 60 | while self.training.value: 61 | state = self.pipe.recv() 62 | self.pipe.send(np.argmax(self.mainDQN.predict(state))) 63 | 64 | def train(self): 65 | while True: 66 | replay_buffer, episode, step_count, max_x, reward_sum = self.train_q.recv() 67 | print "received" 68 | self.sess.run(self.copy_ops_temp2) 69 | for idx in range(4): 70 | # minibatch = random.sample(replay_buffer, int(len(replay_buffer) * 0.8)) 71 | minibatch = replay_buffer 72 | loss = self.replay_train(self.tempDQN, self.targetDQN, minibatch) 73 | print("Episode: {} Loss: {} Accuracy: {}".format(episode, loss[0], loss[2])) 74 | 75 | self.sess.run(self.copy_ops) 76 | self.sess.run(self.copy_ops_temp) 77 | 78 | # 100 에피소드마다 저장한다 79 | if episode % 100 == 0: 80 | self.mainDQN.save(episode=episode) 81 | self.targetDQN.save(episode=episode) 82 | self.tempDQN.save(episode=episode) 83 | 84 | if not self.training.value: 85 | break 86 | 87 | def replay_train(self, mainDQN, targetDQN, train_batch): 88 | x_stack = np.empty(0).reshape(0, self.input_size) 89 | y_stack = np.empty(0).reshape(0, self.output_size) 90 | step = 0 91 | for state, action, reward, next_state, done in train_batch: 92 | Q = mainDQN.predict(state) 93 | #png.from_array(next_state, 'L').save('capture/' + str(step) + '.png') 94 | 95 | if done: 96 | Q[0, action] = reward 97 | else: 98 | Q[0, action] = reward + self.dis * targetDQN.predict(next_state)[0, np.argmax(mainDQN.predict(next_state))] 99 | 100 | 101 | state = np.reshape(state, [self.input_size]) 102 | y_stack = np.vstack([y_stack, Q]) 103 | x_stack = np.vstack([x_stack, state]) 104 | step += 1 105 | 106 | return mainDQN.update(x_stack, y_stack) 107 | 108 | def get_copy_var_ops(self, dest_scope_name="target", src_scope_name="main"): 109 | op_holder = [] 110 | 111 | src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name) 112 | dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name) 113 | 114 | for src_var, dest_var in zip(src_vars, dest_vars): 115 | op_holder.append(dest_var.assign(src_var.value())) 116 | 117 | return op_holder 118 | 119 | 120 | class AIControl: 121 | def __init__(self, env, train_q, play_pipe, is_training): 122 | self.env = env 123 | 124 | self.input_size = self.env.state_n 125 | self.output_size = 12 126 | 127 | #self.dis = 0.9 128 | self.dis = 0.9 129 | self.val = 0 130 | self.save_path = "./save/save_model" 131 | 132 | self.max_episodes = 2000001 133 | 134 | self.replay_buffer = deque() 135 | self.episode_buffer = train_q 136 | self.play_pipe = play_pipe 137 | 138 | self.MAX_BUFFER_SIZE = 20000 139 | 140 | self.frame_action = 3 141 | self.training = is_training 142 | 143 | 144 | def control_start(self): 145 | start_position = 0 146 | episode = 200 147 | 148 | while episode < self.max_episodes: 149 | e = max(0.05, 1. / ((episode / 30) + 1))#min(0.8, 1. / ((episode / 30) + 1))) 150 | done = False 151 | clear = False 152 | step_count = 0 153 | state = self.env.reset(start_position=start_position) 154 | max_x = 0 155 | reward_sum = 0 156 | before_action = [0, 0, 0, 0, 0, 0] 157 | 158 | input_list = [] 159 | 160 | hold_frame = 0 161 | before_max_x = 200 162 | 163 | step_reward = 0 164 | 165 | while not done and not clear: 166 | 167 | if step_count % self.frame_action == 0: 168 | if np.random.rand(1) < e: 169 | action = self.env.get_random_actions() 170 | else: 171 | self.play_pipe.send(state) 172 | action = self.play_pipe.recv() 173 | input_list.append(action) 174 | else: 175 | action = before_action 176 | 177 | next_state, reward, done, clear, max_x, timeout, now_x = self.env.step(action) 178 | #print state 179 | step_reward += reward 180 | 181 | 182 | if step_count % self.frame_action == self.frame_action-1 \ 183 | or done or timeout or clear: 184 | if done and not timeout: 185 | reward = -10000 186 | if clear: 187 | reward += 10000 188 | done = True 189 | 190 | self.replay_buffer.append((state, action, step_reward, next_state, done)) 191 | if len(self.replay_buffer) > self.MAX_BUFFER_SIZE: 192 | self.replay_buffer.popleft() 193 | step_reward = 0 194 | 195 | 196 | 197 | 198 | state = next_state 199 | step_count += 1 200 | 201 | reward_sum += reward 202 | before_action = action 203 | 204 | # 앞으로 나아가지 못하는 상황이 1000프레임 이상이면 종료하고 학습한다. 205 | if now_x <= before_max_x: 206 | hold_frame += 1 207 | if hold_frame > 1000: 208 | timeout = True 209 | break 210 | else: 211 | hold_frame = 0 212 | before_max_x = max_x 213 | #print next_state 214 | #png.from_array(next_state, 'RGB').save('capture/' + str(step_count) + '.png') 215 | 216 | print("Episode: {} steps: {} max_x: {} reward: {}".format(episode, step_count, max_x, 217 | reward_sum)) 218 | 219 | with open('input_log/input_' + str(episode), 'w') as fp: 220 | fp.write(str(input_list)) 221 | 222 | # 샘플링 하기에 작은 사이즈는 트레이닝 시키지 않는다 223 | if episode % 5 == 0 and len(self.replay_buffer) > 50: 224 | self.episode_buffer.send((self.replay_buffer, episode, step_count, max_x, reward_sum)) 225 | #if not self.episode_buffer.empty(): 226 | # print 'buffer flush... plz wait...' 227 | # while self.episode_buffer.empty(): 228 | # time.sleep(1) 229 | self.replay_buffer = deque() 230 | 231 | episode += 1 232 | 233 | # 죽은 경우 죽은 지점의 600픽셀 이전에서 살아나서 다시 시도한다 234 | ''' 235 | if done and not timeout: 236 | start_position = now_x - 800 237 | else: 238 | start_position = 0 239 | ''' 240 | 241 | self.training.value = False 242 | 243 | 244 | 245 | def main(): 246 | env = Env() 247 | 248 | play_pipe, predict_pipe = Pipe() 249 | train_pipe1, train_pipe2 = Pipe() 250 | 251 | is_training = Value("b", True) 252 | 253 | manager = DQNManager(env.state_n, env.action_n, train_pipe1, predict_pipe, is_training) 254 | controller = AIControl(env, train_pipe2, play_pipe, is_training) 255 | manager.start() 256 | controller.control_start() 257 | manager.join() 258 | 259 | 260 | if __name__ == "__main__": 261 | main() 262 | 263 | #lightdm -------------------------------------------------------------------------------- /data/components/powerups.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import constants as c 5 | from .. import setup 6 | 7 | 8 | class Powerup(pg.sprite.Sprite): 9 | """Base class for all powerup_group""" 10 | def __init__(self, x, y): 11 | super(Powerup, self).__init__() 12 | 13 | 14 | def setup_powerup(self, x, y, name, setup_frames): 15 | """This separate setup function allows me to pass a different 16 | setup_frames method depending on what the powerup is""" 17 | self.sprite_sheet = setup.GFX['item_objects'] 18 | self.frames = [] 19 | self.frame_index = 0 20 | setup_frames() 21 | self.image = self.frames[self.frame_index] 22 | self.rect = self.image.get_rect() 23 | self.rect.centerx = x 24 | self.rect.y = y 25 | self.state = c.REVEAL 26 | self.y_vel = -1 27 | self.x_vel = 0 28 | self.direction = c.RIGHT 29 | self.box_height = y 30 | self.gravity = 1 31 | self.max_y_vel = 8 32 | self.animate_timer = 0 33 | self.name = name 34 | 35 | 36 | def get_image(self, x, y, width, height): 37 | """Get the image frames from the sprite sheet""" 38 | 39 | image = pg.Surface([width, height]).convert() 40 | rect = image.get_rect() 41 | 42 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 43 | image.set_colorkey(c.BLACK) 44 | 45 | 46 | image = pg.transform.scale(image, 47 | (int(rect.width*c.SIZE_MULTIPLIER), 48 | int(rect.height*c.SIZE_MULTIPLIER))) 49 | return image 50 | 51 | 52 | def update(self, game_info, *args): 53 | """Updates powerup behavior""" 54 | self.current_time = game_info[c.CURRENT_TIME] 55 | self.handle_state() 56 | 57 | 58 | def handle_state(self): 59 | pass 60 | 61 | 62 | def revealing(self, *args): 63 | """Action when powerup leaves the coin box or brick""" 64 | self.rect.y += self.y_vel 65 | 66 | if self.rect.bottom <= self.box_height: 67 | self.rect.bottom = self.box_height 68 | self.y_vel = 0 69 | self.state = c.SLIDE 70 | 71 | 72 | def sliding(self): 73 | """Action for when powerup slides along the ground""" 74 | if self.direction == c.RIGHT: 75 | self.x_vel = 3 76 | else: 77 | self.x_vel = -3 78 | 79 | 80 | def falling(self): 81 | """When powerups fall of a ledge""" 82 | if self.y_vel < self.max_y_vel: 83 | self.y_vel += self.gravity 84 | 85 | 86 | class Mushroom(Powerup): 87 | """Powerup that makes Mario become bigger""" 88 | def __init__(self, x, y, name='mushroom'): 89 | super(Mushroom, self).__init__(x, y) 90 | self.setup_powerup(x, y, name, self.setup_frames) 91 | 92 | 93 | def setup_frames(self): 94 | """Sets up frame list""" 95 | self.frames.append(self.get_image(0, 0, 16, 16)) 96 | 97 | 98 | def handle_state(self): 99 | """Handles behavior based on state""" 100 | if self.state == c.REVEAL: 101 | self.revealing() 102 | elif self.state == c.SLIDE: 103 | self.sliding() 104 | elif self.state == c.FALL: 105 | self.falling() 106 | 107 | 108 | class LifeMushroom(Mushroom): 109 | """1up mushroom""" 110 | def __init__(self, x, y, name='1up_mushroom'): 111 | super(LifeMushroom, self).__init__(x, y) 112 | self.setup_powerup(x, y, name, self.setup_frames) 113 | 114 | def setup_frames(self): 115 | self.frames.append(self.get_image(16, 0, 16, 16)) 116 | 117 | 118 | class FireFlower(Powerup): 119 | """Powerup that allows Mario to throw fire balls""" 120 | def __init__(self, x, y, name=c.FIREFLOWER): 121 | super(FireFlower, self).__init__(x, y) 122 | self.setup_powerup(x, y, name, self.setup_frames) 123 | 124 | 125 | def setup_frames(self): 126 | """Sets up frame list""" 127 | self.frames.append( 128 | self.get_image(0, 32, 16, 16)) 129 | self.frames.append( 130 | self.get_image(16, 32, 16, 16)) 131 | self.frames.append( 132 | self.get_image(32, 32, 16, 16)) 133 | self.frames.append( 134 | self.get_image(48, 32, 16, 16)) 135 | 136 | 137 | def handle_state(self): 138 | """Handle behavior based on state""" 139 | if self.state == c.REVEAL: 140 | self.revealing() 141 | elif self.state == c.RESTING: 142 | self.resting() 143 | 144 | 145 | def revealing(self): 146 | """Animation of flower coming out of box""" 147 | self.rect.y += self.y_vel 148 | 149 | if self.rect.bottom <= self.box_height: 150 | self.rect.bottom = self.box_height 151 | self.state = c.RESTING 152 | 153 | self.animation() 154 | 155 | 156 | def resting(self): 157 | """Fire Flower staying still on opened box""" 158 | self.animation() 159 | 160 | 161 | def animation(self): 162 | """Method to make the Fire Flower blink""" 163 | if (self.current_time - self.animate_timer) > 30: 164 | if self.frame_index < 3: 165 | self.frame_index += 1 166 | else: 167 | self.frame_index = 0 168 | 169 | self.image = self.frames[self.frame_index] 170 | self.animate_timer = self.current_time 171 | 172 | 173 | class Star(Powerup): 174 | """A powerup that gives mario invincibility""" 175 | def __init__(self, x, y, name='star'): 176 | super(Star, self).__init__(x, y) 177 | self.setup_powerup(x, y, name, self.setup_frames) 178 | self.animate_timer = 0 179 | self.rect.y += 1 #looks more centered offset one pixel 180 | self.gravity = .4 181 | 182 | 183 | def setup_frames(self): 184 | """Creating the self.frames list where the images for the animation 185 | are stored""" 186 | self.frames.append(self.get_image(1, 48, 15, 16)) 187 | self.frames.append(self.get_image(17, 48, 15, 16)) 188 | self.frames.append(self.get_image(33, 48, 15, 16)) 189 | self.frames.append(self.get_image(49, 48, 15, 16)) 190 | 191 | 192 | def handle_state(self): 193 | """Handles behavior based on state""" 194 | if self.state == c.REVEAL: 195 | self.revealing() 196 | elif self.state == c.BOUNCE: 197 | self.bouncing() 198 | 199 | 200 | def revealing(self): 201 | """When the star comes out of the box""" 202 | self.rect.y += self.y_vel 203 | 204 | if self.rect.bottom <= self.box_height: 205 | self.rect.bottom = self.box_height 206 | self.start_bounce(-2) 207 | self.state = c.BOUNCE 208 | 209 | self.animation() 210 | 211 | 212 | def animation(self): 213 | """sets image for animation""" 214 | if (self.current_time - self.animate_timer) > 30: 215 | if self.frame_index < 3: 216 | self.frame_index += 1 217 | else: 218 | self.frame_index = 0 219 | self.animate_timer = self.current_time 220 | self.image = self.frames[self.frame_index] 221 | 222 | 223 | def start_bounce(self, vel): 224 | """Transitions into bouncing state""" 225 | self.y_vel = vel 226 | 227 | 228 | def bouncing(self): 229 | """Action when the star is bouncing around""" 230 | self.animation() 231 | 232 | if self.direction == c.LEFT: 233 | self.x_vel = -5 234 | else: 235 | self.x_vel = 5 236 | 237 | 238 | 239 | class FireBall(pg.sprite.Sprite): 240 | """Shot from Fire Mario""" 241 | def __init__(self, x, y, facing_right, name=c.FIREBALL): 242 | super(FireBall, self).__init__() 243 | self.sprite_sheet = setup.GFX['item_objects'] 244 | self.setup_frames() 245 | if facing_right: 246 | self.direction = c.RIGHT 247 | self.x_vel = 12 248 | else: 249 | self.direction = c.LEFT 250 | self.x_vel = -12 251 | self.y_vel = 10 252 | self.gravity = .9 253 | self.frame_index = 0 254 | self.animation_timer = 0 255 | self.state = c.FLYING 256 | self.image = self.frames[self.frame_index] 257 | self.rect = self.image.get_rect() 258 | self.rect.right = x 259 | self.rect.y = y 260 | self.name = name 261 | 262 | 263 | def setup_frames(self): 264 | """Sets up animation frames""" 265 | self.frames = [] 266 | 267 | self.frames.append( 268 | self.get_image(96, 144, 8, 8)) #Frame 1 of flying 269 | self.frames.append( 270 | self.get_image(104, 144, 8, 8)) #Frame 2 of Flying 271 | self.frames.append( 272 | self.get_image(96, 152, 8, 8)) #Frame 3 of Flying 273 | self.frames.append( 274 | self.get_image(104, 152, 8, 8)) #Frame 4 of flying 275 | self.frames.append( 276 | self.get_image(112, 144, 16, 16)) #frame 1 of exploding 277 | self.frames.append( 278 | self.get_image(112, 160, 16, 16)) #frame 2 of exploding 279 | self.frames.append( 280 | self.get_image(112, 176, 16, 16)) #frame 3 of exploding 281 | 282 | 283 | def get_image(self, x, y, width, height): 284 | """Get the image frames from the sprite sheet""" 285 | 286 | image = pg.Surface([width, height]).convert() 287 | rect = image.get_rect() 288 | 289 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 290 | image.set_colorkey(c.BLACK) 291 | 292 | 293 | image = pg.transform.scale(image, 294 | (int(rect.width*c.SIZE_MULTIPLIER), 295 | int(rect.height*c.SIZE_MULTIPLIER))) 296 | return image 297 | 298 | 299 | def update(self, game_info, viewport): 300 | """Updates fireball behavior""" 301 | self.current_time = game_info[c.CURRENT_TIME] 302 | self.handle_state() 303 | self.check_if_off_screen(viewport) 304 | 305 | 306 | def handle_state(self): 307 | """Handles behavior based on state""" 308 | if self.state == c.FLYING: 309 | self.animation() 310 | elif self.state == c.BOUNCING: 311 | self.animation() 312 | elif self.state == c.EXPLODING: 313 | self.animation() 314 | 315 | 316 | def animation(self): 317 | """adjusts frame for animation""" 318 | if self.state == c.FLYING or self.state == c.BOUNCING: 319 | if (self.current_time - self.animation_timer) > 200: 320 | if self.frame_index < 3: 321 | self.frame_index += 1 322 | else: 323 | self.frame_index = 0 324 | self.animation_timer = self.current_time 325 | self.image = self.frames[self.frame_index] 326 | 327 | 328 | elif self.state == c.EXPLODING: 329 | if (self.current_time - self.animation_timer) > 50: 330 | if self.frame_index < 6: 331 | self.frame_index += 1 332 | self.image = self.frames[self.frame_index] 333 | self.animation_timer = self.current_time 334 | else: 335 | self.kill() 336 | 337 | 338 | def explode_transition(self): 339 | """Transitions fireball to EXPLODING state""" 340 | self.frame_index = 4 341 | centerx = self.rect.centerx 342 | self.image = self.frames[self.frame_index] 343 | self.rect.centerx = centerx 344 | self.state = c.EXPLODING 345 | 346 | 347 | def check_if_off_screen(self, viewport): 348 | """Removes from sprite group if off screen""" 349 | if (self.rect.x > viewport.right) or (self.rect.y > viewport.bottom) \ 350 | or (self.rect.right < viewport.x): 351 | self.kill() 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | -------------------------------------------------------------------------------- /data/env.py: -------------------------------------------------------------------------------- 1 | from . import setup, tools 2 | from .states import main_menu, load_screen, level1 3 | from . import constants as c 4 | import pygame as pg 5 | import numpy as np 6 | import scipy.misc 7 | import random 8 | 9 | class Env: 10 | action_idx = { 11 | 0: 273, 12 | 1: 274, 13 | 2: 276, 14 | 3: 275, # right 15 | 4: 97, 16 | 5: 115 17 | } 18 | 19 | mapping = { 20 | 0: [0, 0, 0, 0, 0, 0], # NO 21 | 1: [1, 0, 0, 0, 0, 0], # Up 22 | 2: [0, 1, 0, 0, 0, 0], # Down 23 | 3: [0, 0, 1, 0, 0, 0], # Left 24 | 4: [0, 0, 1, 0, 1, 0], # Left + A 25 | 5: [0, 0, 1, 0, 0, 1], # Left + B 26 | 6: [0, 0, 1, 0, 1, 1], # Left + A + B 27 | 7: [0, 0, 0, 1, 0, 0], # Right 28 | 8: [0, 0, 0, 1, 1, 0], # Right + A 29 | 9: [0, 0, 0, 1, 0, 1], # Right + B 30 | 10: [0, 0, 0, 1, 1, 1], # Right + A + B 31 | 11: [0, 0, 0, 0, 1, 0], # A 32 | 12: [0, 0, 0, 0, 0, 1], # B 33 | 13: [0, 0, 0, 0, 1, 1], # A + B 34 | } 35 | 36 | controller = None 37 | 38 | action_n = len(mapping.keys()) 39 | 40 | resize_x = 90 41 | resize_y = 90 42 | color_chanel = 1 43 | state_n = resize_x * resize_y * color_chanel 44 | 45 | def __init__(self): 46 | 47 | 48 | #self.resize_x = 120 49 | #self.resize_y = 120 50 | #self.color_chanel = 1 51 | #self.state_n = self.resize_x * self.resize_y * self.color_chanel 52 | 53 | self.run_it = tools.Control(setup.ORIGINAL_CAPTION, self) 54 | self.state_dict = { 55 | c.MAIN_MENU: main_menu.Menu(), 56 | c.LOAD_SCREEN: load_screen.LoadScreen(), 57 | c.TIME_OUT: load_screen.TimeOut(), 58 | c.GAME_OVER: load_screen.GameOver(), 59 | c.LEVEL1: level1.Level1() 60 | } 61 | self.run_it.ml_done = False 62 | self.run_it.setup_states(self.state_dict, c.LEVEL1) 63 | 64 | 65 | def get_random_actions(self): 66 | return random.randint(0, 13) 67 | 68 | def rgb2gray(self, image): 69 | return np.dot(image[..., :3], [0.299, 0.587, 0.114]) 70 | 71 | def reset(self, start_position=0): 72 | self.state_dict = { 73 | c.MAIN_MENU: main_menu.Menu(), 74 | c.LOAD_SCREEN: load_screen.LoadScreen(), 75 | c.TIME_OUT: load_screen.TimeOut(), 76 | c.GAME_OVER: load_screen.GameOver(), 77 | c.LEVEL1: level1.Level1() 78 | } 79 | self.run_it.ml_done = False 80 | self.run_it.setup_states(self.state_dict, c.LEVEL1) 81 | self.run_it.max_posision_x = 200 82 | #if start_position < 0: 83 | # start_position = 0 84 | #self.run_it.max_posision_x = start_position 85 | #self.run_it.state.viewport.x = start_position 86 | 87 | state, _, _, _, _, _, _ = self.run_it.get_step() 88 | state = scipy.misc.imresize(state, (self.resize_x, self.resize_y)) 89 | state = self.rgb2gray(state) / 255. 90 | state = scipy.misc.imresize(state, (self.resize_x, self.resize_y)) 91 | #state = scipy.misc.imresize(state, (self.resize_x, self.resize_y)) 92 | 93 | #state = scipy.misc.imresize(state, (self.resize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0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 110 | action = self.mapping[action] 111 | for idx in range(len(action)): 112 | if action[idx] == 1: 113 | input_action[self.action_idx[idx]] = 1 114 | self.run_it.event_loop(tuple(input_action)) 115 | self.run_it.update() 116 | pg.display.update() 117 | next_state, reward, gameover, clear, max_x, timeout, now_x = self.run_it.get_step() 118 | 119 | #self.run_it.clock.tick(self.run_it.fps) 120 | #fps = self.run_it.clock.get_fps() 121 | #with_fps = "{} - {:.2f} FPS".format(self.run_it.caption, fps) 122 | #pg.display.set_caption(with_fps) 123 | 124 | 125 | next_state = scipy.misc.imresize(next_state, (self.resize_x, self.resize_y)) 126 | next_state = self.rgb2gray(next_state) / 255. 127 | next_state = scipy.misc.imresize(next_state, (self.resize_x, self.resize_y)) 128 | #next_state = scipy.misc.imresize(next_state, (self.resize_x, self.resize_y)) 129 | 130 | #next_state = scipy.misc.imrotate(next_state, -90.) 131 | 132 | return (next_state, reward, gameover, clear, max_x, timeout, now_x) 133 | 134 | 135 | ''' 136 | keys = { 137 | 'up': (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) 144 | } 145 | ''' -------------------------------------------------------------------------------- /data/components/info.py: -------------------------------------------------------------------------------- 1 | __author__ = 'justinarmstrong' 2 | 3 | import pygame as pg 4 | from .. import setup 5 | from .. import constants as c 6 | from . import flashing_coin 7 | 8 | 9 | class Character(pg.sprite.Sprite): 10 | """Parent class for all characters used for the overhead level info""" 11 | def __init__(self, image): 12 | super(Character, self).__init__() 13 | self.image = image 14 | self.rect = self.image.get_rect() 15 | 16 | 17 | class OverheadInfo(object): 18 | """Class for level information like score, coin total, 19 | and time remaining""" 20 | def __init__(self, game_info, state): 21 | self.sprite_sheet = setup.GFX['text_images'] 22 | self.coin_total = game_info[c.COIN_TOTAL] 23 | self.time = 401 24 | self.current_time = 0 25 | self.total_lives = game_info[c.LIVES] 26 | self.top_score = game_info[c.TOP_SCORE] 27 | self.state = state 28 | self.special_state = None 29 | self.game_info = game_info 30 | 31 | self.create_image_dict() 32 | self.create_score_group() 33 | self.create_info_labels() 34 | self.create_load_screen_labels() 35 | self.create_countdown_clock() 36 | self.create_coin_counter() 37 | self.create_flashing_coin() 38 | self.create_mario_image() 39 | self.create_game_over_label() 40 | self.create_time_out_label() 41 | self.create_main_menu_labels() 42 | 43 | 44 | def create_image_dict(self): 45 | """Creates the initial images for the score""" 46 | self.image_dict = {} 47 | image_list = [] 48 | 49 | image_list.append(self.get_image(3, 230, 7, 7)) 50 | image_list.append(self.get_image(12, 230, 7, 7)) 51 | image_list.append(self.get_image(19, 230, 7, 7)) 52 | image_list.append(self.get_image(27, 230, 7, 7)) 53 | image_list.append(self.get_image(35, 230, 7, 7)) 54 | image_list.append(self.get_image(43, 230, 7, 7)) 55 | image_list.append(self.get_image(51, 230, 7, 7)) 56 | image_list.append(self.get_image(59, 230, 7, 7)) 57 | image_list.append(self.get_image(67, 230, 7, 7)) 58 | image_list.append(self.get_image(75, 230, 7, 7)) 59 | 60 | image_list.append(self.get_image(83, 230, 7, 7)) 61 | image_list.append(self.get_image(91, 230, 7, 7)) 62 | image_list.append(self.get_image(99, 230, 7, 7)) 63 | image_list.append(self.get_image(107, 230, 7, 7)) 64 | image_list.append(self.get_image(115, 230, 7, 7)) 65 | image_list.append(self.get_image(123, 230, 7, 7)) 66 | image_list.append(self.get_image(3, 238, 7, 7)) 67 | image_list.append(self.get_image(11, 238, 7, 7)) 68 | image_list.append(self.get_image(20, 238, 7, 7)) 69 | image_list.append(self.get_image(27, 238, 7, 7)) 70 | image_list.append(self.get_image(35, 238, 7, 7)) 71 | image_list.append(self.get_image(44, 238, 7, 7)) 72 | image_list.append(self.get_image(51, 238, 7, 7)) 73 | image_list.append(self.get_image(59, 238, 7, 7)) 74 | image_list.append(self.get_image(67, 238, 7, 7)) 75 | image_list.append(self.get_image(75, 238, 7, 7)) 76 | image_list.append(self.get_image(83, 238, 7, 7)) 77 | image_list.append(self.get_image(91, 238, 7, 7)) 78 | image_list.append(self.get_image(99, 238, 7, 7)) 79 | image_list.append(self.get_image(108, 238, 7, 7)) 80 | image_list.append(self.get_image(115, 238, 7, 7)) 81 | image_list.append(self.get_image(123, 238, 7, 7)) 82 | image_list.append(self.get_image(3, 246, 7, 7)) 83 | image_list.append(self.get_image(11, 246, 7, 7)) 84 | image_list.append(self.get_image(20, 246, 7, 7)) 85 | image_list.append(self.get_image(27, 246, 7, 7)) 86 | image_list.append(self.get_image(48, 248, 7, 7)) 87 | 88 | image_list.append(self.get_image(68, 249, 6, 2)) 89 | image_list.append(self.get_image(75, 247, 6, 6)) 90 | 91 | 92 | 93 | character_string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -*' 94 | 95 | for character, image in zip(character_string, image_list): 96 | self.image_dict[character] = image 97 | 98 | 99 | def get_image(self, x, y, width, height): 100 | """Extracts image from sprite sheet""" 101 | image = pg.Surface([width, height]) 102 | rect = image.get_rect() 103 | 104 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 105 | image.set_colorkey((92, 148, 252)) 106 | image = pg.transform.scale(image, 107 | (int(rect.width*2.9), 108 | int(rect.height*2.9))) 109 | return image 110 | 111 | 112 | def create_score_group(self): 113 | """Creates the initial empty score (000000)""" 114 | self.score_images = [] 115 | self.create_label(self.score_images, '000000', 75, 55) 116 | 117 | 118 | def create_info_labels(self): 119 | """Creates the labels that describe each info""" 120 | self.mario_label = [] 121 | self.world_label = [] 122 | self.time_label = [] 123 | self.stage_label = [] 124 | 125 | 126 | self.create_label(self.mario_label, 'MARIO', 75, 30) 127 | self.create_label(self.world_label, 'WORLD', 450, 30) 128 | self.create_label(self.time_label, 'TIME', 625, 30) 129 | self.create_label(self.stage_label, '1-1', 472, 55) 130 | 131 | self.label_list = [self.mario_label, 132 | self.world_label, 133 | self.time_label, 134 | self.stage_label] 135 | 136 | 137 | def create_load_screen_labels(self): 138 | """Creates labels for the center info of a load screen""" 139 | world_label = [] 140 | number_label = [] 141 | 142 | self.create_label(world_label, 'WORLD', 280, 200) 143 | self.create_label(number_label, '1-1', 430, 200) 144 | 145 | self.center_labels = [world_label, number_label] 146 | 147 | 148 | def create_countdown_clock(self): 149 | """Creates the count down clock for the level""" 150 | self.count_down_images = [] 151 | self.create_label(self.count_down_images, str(self.time), 645, 55) 152 | 153 | 154 | def create_label(self, label_list, string, x, y): 155 | """Creates a label (WORLD, TIME, MARIO)""" 156 | for letter in string: 157 | label_list.append(Character(self.image_dict[letter])) 158 | 159 | self.set_label_rects(label_list, x, y) 160 | 161 | 162 | def set_label_rects(self, label_list, x, y): 163 | """Set the location of each individual character""" 164 | for i, letter in enumerate(label_list): 165 | letter.rect.x = x + ((letter.rect.width + 3) * i) 166 | letter.rect.y = y 167 | if letter.image == self.image_dict['-']: 168 | letter.rect.y += 7 169 | letter.rect.x += 2 170 | 171 | 172 | def create_coin_counter(self): 173 | """Creates the info that tracks the number of coins Mario collects""" 174 | self.coin_count_images = [] 175 | self.create_label(self.coin_count_images, '*00', 300, 55) 176 | 177 | 178 | def create_flashing_coin(self): 179 | """Creates the flashing coin next to the coin total""" 180 | self.flashing_coin = flashing_coin.Coin(280, 53) 181 | 182 | 183 | def create_mario_image(self): 184 | """Get the mario image""" 185 | self.life_times_image = self.get_image(75, 247, 6, 6) 186 | self.life_times_rect = self.life_times_image.get_rect(center=(378, 295)) 187 | self.life_total_label = [] 188 | self.create_label(self.life_total_label, str(self.total_lives), 189 | 450, 285) 190 | 191 | self.sprite_sheet = setup.GFX['mario_bros'] 192 | self.mario_image = self.get_image(178, 32, 12, 16) 193 | self.mario_rect = self.mario_image.get_rect(center=(320, 290)) 194 | 195 | 196 | def create_game_over_label(self): 197 | """Create the label for the GAME OVER screen""" 198 | game_label = [] 199 | over_label = [] 200 | 201 | self.create_label(game_label, 'GAME', 280, 300) 202 | self.create_label(over_label, 'OVER', 400, 300) 203 | 204 | self.game_over_label = [game_label, over_label] 205 | 206 | 207 | def create_time_out_label(self): 208 | """Create the label for the time out screen""" 209 | time_out_label = [] 210 | 211 | self.create_label(time_out_label, 'TIME OUT', 290, 310) 212 | self.time_out_label = [time_out_label] 213 | 214 | 215 | def create_main_menu_labels(self): 216 | """Create labels for the MAIN MENU screen""" 217 | player_one_game = [] 218 | player_two_game = [] 219 | top = [] 220 | top_score = [] 221 | 222 | self.create_label(player_one_game, '1 PLAYER GAME', 272, 360) 223 | self.create_label(player_two_game, '2 PLAYER GAME', 272, 405) 224 | self.create_label(top, 'TOP - ', 290, 465) 225 | self.create_label(top_score, '000000', 400, 465) 226 | 227 | self.main_menu_labels = [player_one_game, player_two_game, 228 | top, top_score] 229 | 230 | 231 | def update(self, level_info, mario=None): 232 | """Updates all overhead info""" 233 | self.mario = mario 234 | self.handle_level_state(level_info) 235 | 236 | 237 | def handle_level_state(self, level_info): 238 | """Updates info based on what state the game is in""" 239 | if self.state == c.MAIN_MENU: 240 | self.score = level_info[c.SCORE] 241 | self.update_score_images(self.score_images, self.score) 242 | self.update_score_images(self.main_menu_labels[3], self.top_score) 243 | self.update_coin_total(level_info) 244 | self.flashing_coin.update(level_info[c.CURRENT_TIME]) 245 | 246 | elif self.state == c.LOAD_SCREEN: 247 | self.score = level_info[c.SCORE] 248 | self.update_score_images(self.score_images, self.score) 249 | self.update_coin_total(level_info) 250 | 251 | elif self.state == c.LEVEL: 252 | self.score = level_info[c.SCORE] 253 | self.update_score_images(self.score_images, self.score) 254 | if level_info[c.LEVEL_STATE] != c.FROZEN \ 255 | and self.mario.state != c.WALKING_TO_CASTLE \ 256 | and self.mario.state != c.END_OF_LEVEL_FALL \ 257 | and not self.mario.dead: 258 | self.update_count_down_clock(level_info) 259 | self.update_coin_total(level_info) 260 | self.flashing_coin.update(level_info[c.CURRENT_TIME]) 261 | 262 | elif self.state == c.TIME_OUT: 263 | self.score = level_info[c.SCORE] 264 | self.update_score_images(self.score_images, self.score) 265 | self.update_coin_total(level_info) 266 | 267 | elif self.state == c.GAME_OVER: 268 | self.score = level_info[c.SCORE] 269 | self.update_score_images(self.score_images, self.score) 270 | self.update_coin_total(level_info) 271 | 272 | elif self.state == c.FAST_COUNT_DOWN: 273 | level_info[c.SCORE] += 50 274 | self.score = level_info[c.SCORE] 275 | self.update_count_down_clock(level_info) 276 | self.update_score_images(self.score_images, self.score) 277 | self.update_coin_total(level_info) 278 | self.flashing_coin.update(level_info[c.CURRENT_TIME]) 279 | if self.time == 0: 280 | self.state = c.END_OF_LEVEL 281 | 282 | elif self.state == c.END_OF_LEVEL: 283 | self.flashing_coin.update(level_info[c.CURRENT_TIME]) 284 | 285 | 286 | def update_score_images(self, images, score): 287 | """Updates what numbers are to be blitted for the score""" 288 | index = len(images) - 1 289 | 290 | for digit in reversed(str(score)): 291 | rect = images[index].rect 292 | images[index] = Character(self.image_dict[digit]) 293 | images[index].rect = rect 294 | index -= 1 295 | 296 | 297 | def update_count_down_clock(self, level_info): 298 | """Updates current time""" 299 | if self.state == c.FAST_COUNT_DOWN: 300 | self.time -= 1 301 | 302 | elif (level_info[c.CURRENT_TIME] - self.current_time) > 400: 303 | self.current_time = level_info[c.CURRENT_TIME] 304 | self.time -= 1 305 | self.count_down_images = [] 306 | self.create_label(self.count_down_images, str(self.time), 645, 55) 307 | if len(self.count_down_images) < 2: 308 | for i in range(2): 309 | self.count_down_images.insert(0, Character(self.image_dict['0'])) 310 | self.set_label_rects(self.count_down_images, 645, 55) 311 | elif len(self.count_down_images) < 3: 312 | self.count_down_images.insert(0, Character(self.image_dict['0'])) 313 | self.set_label_rects(self.count_down_images, 645, 55) 314 | 315 | 316 | def update_coin_total(self, level_info): 317 | """Updates the coin total and adjusts label accordingly""" 318 | self.coin_total = level_info[c.COIN_TOTAL] 319 | 320 | coin_string = str(self.coin_total) 321 | if len(coin_string) < 2: 322 | coin_string = '*0' + coin_string 323 | elif len(coin_string) > 2: 324 | coin_string = '*00' 325 | else: 326 | coin_string = '*' + coin_string 327 | 328 | x = self.coin_count_images[0].rect.x 329 | y = self.coin_count_images[0].rect.y 330 | 331 | self.coin_count_images = [] 332 | 333 | self.create_label(self.coin_count_images, coin_string, x, y) 334 | 335 | 336 | def draw(self, surface): 337 | """Draws overhead info based on state""" 338 | if self.state == c.MAIN_MENU: 339 | self.draw_main_menu_info(surface) 340 | elif self.state == c.LOAD_SCREEN: 341 | self.draw_loading_screen_info(surface) 342 | elif self.state == c.LEVEL: 343 | self.draw_level_screen_info(surface) 344 | elif self.state == c.GAME_OVER: 345 | self.draw_game_over_screen_info(surface) 346 | elif self.state == c.FAST_COUNT_DOWN: 347 | self.draw_level_screen_info(surface) 348 | elif self.state == c.END_OF_LEVEL: 349 | self.draw_level_screen_info(surface) 350 | elif self.state == c.TIME_OUT: 351 | self.draw_time_out_screen_info(surface) 352 | else: 353 | pass 354 | 355 | 356 | 357 | def draw_main_menu_info(self, surface): 358 | """Draws info for main menu""" 359 | for info in self.score_images: 360 | surface.blit(info.image, info.rect) 361 | 362 | for label in self.main_menu_labels: 363 | for letter in label: 364 | surface.blit(letter.image, letter.rect) 365 | 366 | for character in self.coin_count_images: 367 | surface.blit(character.image, character.rect) 368 | 369 | for label in self.label_list: 370 | for letter in label: 371 | surface.blit(letter.image, letter.rect) 372 | 373 | surface.blit(self.flashing_coin.image, self.flashing_coin.rect) 374 | 375 | 376 | def draw_loading_screen_info(self, surface): 377 | """Draws info for loading screen""" 378 | for info in self.score_images: 379 | surface.blit(info.image, info.rect) 380 | 381 | for word in self.center_labels: 382 | for letter in word: 383 | surface.blit(letter.image, letter.rect) 384 | 385 | for word in self.life_total_label: 386 | surface.blit(word.image, word.rect) 387 | 388 | surface.blit(self.mario_image, self.mario_rect) 389 | surface.blit(self.life_times_image, self.life_times_rect) 390 | 391 | for character in self.coin_count_images: 392 | surface.blit(character.image, character.rect) 393 | 394 | for label in self.label_list: 395 | for letter in label: 396 | surface.blit(letter.image, letter.rect) 397 | 398 | surface.blit(self.flashing_coin.image, self.flashing_coin.rect) 399 | 400 | 401 | def draw_level_screen_info(self, surface): 402 | """Draws info during regular game play""" 403 | for info in self.score_images: 404 | surface.blit(info.image, info.rect) 405 | 406 | for digit in self.count_down_images: 407 | surface.blit(digit.image, digit.rect) 408 | 409 | for character in self.coin_count_images: 410 | surface.blit(character.image, character.rect) 411 | 412 | for label in self.label_list: 413 | for letter in label: 414 | surface.blit(letter.image, letter.rect) 415 | 416 | surface.blit(self.flashing_coin.image, self.flashing_coin.rect) 417 | 418 | 419 | def draw_game_over_screen_info(self, surface): 420 | """Draws info when game over""" 421 | for info in self.score_images: 422 | surface.blit(info.image, info.rect) 423 | 424 | for word in self.game_over_label: 425 | for letter in word: 426 | surface.blit(letter.image, letter.rect) 427 | 428 | for character in self.coin_count_images: 429 | surface.blit(character.image, character.rect) 430 | 431 | for label in self.label_list: 432 | for letter in label: 433 | surface.blit(letter.image, letter.rect) 434 | 435 | surface.blit(self.flashing_coin.image, self.flashing_coin.rect) 436 | 437 | 438 | def draw_time_out_screen_info(self, surface): 439 | """Draws info when on the time out screen""" 440 | for info in self.score_images: 441 | surface.blit(info.image, info.rect) 442 | 443 | for word in self.time_out_label: 444 | for letter in word: 445 | surface.blit(letter.image, letter.rect) 446 | 447 | for character in self.coin_count_images: 448 | surface.blit(character.image, character.rect) 449 | 450 | for label in self.label_list: 451 | for letter in label: 452 | surface.blit(letter.image, letter.rect) 453 | 454 | surface.blit(self.flashing_coin.image, self.flashing_coin.rect) 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------