Advertisement
Guest User

Untitled

a guest
Feb 27th, 2019
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.68 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import pygame, os
  3. from pygame.locals import *
  4. from pygame.compat import geterror
  5. import player
  6. import platform
  7. import random
  8. import sys
  9.  
  10. import neat
  11. import pickle
  12.  
  13. # core_path = os.path.dirname(os.path.realpath(__file__))
  14.  
  15. if getattr(sys, 'frozen', False):
  16.     # frozen
  17.     core_path = os.path.dirname(sys.executable)
  18. else:
  19.     # unfrozen
  20.     core_path = os.path.dirname(os.path.realpath(__file__))
  21.  
  22.  
  23. folders_path = os.path.normpath(core_path + os.sep + os.pardir )
  24. resources_dir = os.path.join(folders_path, "resources")
  25. core_dir = os.path.join(folders_path, "core")
  26.  
  27.  
  28. GENERATION = 0
  29. MAX_FITNESS = 0
  30. BEST_GENOME = 0
  31. FPS = 60
  32.  
  33.  
  34.  
  35. class Game:
  36.  
  37.     WIDTH, HEIGHT = 0, 0
  38.  
  39.     def __init__(self, width, height):
  40.        pass
  41.  
  42.  
  43.     def init(self, width, height):
  44.         self.WIDTH = width
  45.         self.HEIGHT = height
  46.         self.timedelta = 0
  47.         self.counting_seconds = 0
  48.         self.start_time = 0
  49.         self.counting_time = 0
  50.  
  51.         self.HIGH_SCORE = 0
  52.         self.GENOME_SCORE = 0
  53.  
  54.  
  55.  
  56.         # TODO: change background image
  57.         #       GENOME_SCORE is not working properly          
  58.  
  59.         pygame.init()
  60.         self.running = True
  61.  
  62.  
  63.  
  64.         self.basic_font = pygame.font.SysFont(None, 32)
  65.  
  66.         self.clock = pygame.time.Clock()
  67.  
  68.         self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
  69.         pygame.display.set_caption("Dodge the spam!")
  70.         self.background = pygame.Surface(self.screen.get_size()).convert()
  71.  
  72.         self.background.fill((255,255,255))
  73.  
  74.         self.player = player.Player(self.WIDTH / 2, self.HEIGHT - 150, 30, 30)
  75.  
  76.         (player_image, player_image_rect) = self.load_image("player_icon.png")
  77.         (platform_image, platform_image_rect) = self.load_image("spam.png")
  78.        
  79.         self.player.PLAYER_IMAGE = player_image
  80.         self.player.PLAYER_IMAGE = pygame.transform.scale(self.player.PLAYER_IMAGE, (self.player.width, self.player.height))
  81.         self.player.PLAYER_IMAGE_RECT = player_image_rect
  82.  
  83.         platform.Platform.SPAM_IMAGE = platform_image
  84.         platform.Platform.SPAM_IMAGE = pygame.transform.scale(platform.Platform.SPAM_IMAGE, (50, 50))
  85.         platform.Platform.SPAM_IMAGE_RECT = platform_image_rect        
  86.  
  87.         self.screen.blit(self.background, (0,0))
  88.  
  89.         self.platforms = []
  90.         self.init_platforms()
  91.  
  92.  
  93.     def init_platforms(self):
  94.         for i in range(10):
  95.             self.platforms.append(platform.Platform(random.randint(0, self.WIDTH), random.randint(-350, 0), 50, 50))
  96.  
  97.     def reset_platforms(self):
  98.         for i in range(10):
  99.             self.platforms[i] = platform.Platform(random.randint(0, self.WIDTH), random.randint(-350, 0), 50, 50)
  100.  
  101.     def move_left(self):
  102.         self.player.x -= self.player.xSpeed * self.timedelta * 2
  103.  
  104.     def move_right(self):
  105.         self.player.x += self.player.xSpeed * self.timedelta * 2
  106.  
  107.     def jump(self):
  108.         self.player.y -= self.player.ySpeed * 2 * self.timedelta * 2
  109.  
  110.     def move_down(self):
  111.         self.player.y += self.player.ySpeed * 2 * self.timedelta * 2
  112.  
  113.     def gravity(self, rect):
  114.         rect.y += rect.ySpeed * self.timedelta * 2
  115.  
  116.  
  117.     def update_player_position(self):
  118.         if self.player.moving_left:
  119.             self.move_left()
  120.         elif self.player.moving_right:
  121.             self.move_right()
  122.  
  123.         if self.player.jumping:
  124.             self.jump()
  125.         elif self.player.moving_down:
  126.             self.move_down()
  127.  
  128.         self.gravity(self.player)
  129.  
  130.         x = 0
  131.         if self.player.y > self.HEIGHT or self.player.y < 0 or self.player.x < 0 or self.player.x > self.WIDTH:
  132.             x = float(self.counting_seconds)
  133.             self.GENOME_SCORE -= 1000
  134.  
  135.         return x
  136.  
  137.  
  138.  
  139.     def restart(self):
  140.  
  141.  
  142.         if self.HIGH_SCORE < float(self.counting_seconds):
  143.             self.HIGH_SCORE = float(self.counting_seconds)
  144.  
  145.         self.start_time = pygame.time.get_ticks()
  146.         self.counting_time = pygame.time.get_ticks() - self.start_time
  147.         self.timedelta = self.clock.tick(FPS)
  148.         self.timedelta /= 1000
  149.         self.player.x = self.WIDTH / 2
  150.         self.player.y = self.HEIGHT - 150
  151.         self.reset_platforms()
  152.         self.GENOME_SCORE = 0
  153.  
  154.  
  155.  
  156.     def on_collision(self, platform):
  157.         x = 0
  158.         if self.player.colliderect(platform):
  159.             x = float(self.counting_seconds)
  160.             # self.restart()
  161.         return x
  162.  
  163.  
  164.     def on_render(self):
  165.  
  166.         self.background.fill((255, 255, 255))
  167.  
  168.         counting_string = "%s" % (self.counting_seconds)
  169.  
  170.         score = self.basic_font.render("Score: " + counting_string, True, (255, 0, 0), (255,255,255))
  171.  
  172.  
  173.         self.screen.blit(self.background, (0,0)) # Order matters
  174.  
  175.         # Speed up player
  176.         # self.player.xSpeed += float(counting_string)
  177.  
  178.  
  179.         for obstacle in self.platforms:
  180.  
  181.             # Speed up obstacle
  182.             # obstacle.ySpeed += float(counting_string) / 10 Too hard for the AI currently, tryng to train it in simpler environments
  183.  
  184.             obstacle.gravity(self.timedelta)
  185.  
  186.             self.reset(obstacle)
  187.             # pygame.draw.rect(self.background, (30, 40, 50), obstacle)
  188.             self.screen.blit(obstacle.SPAM_IMAGE, (obstacle.x, obstacle.y))
  189.  
  190.  
  191.         # Draw player image
  192.         self.screen.blit(self.player.PLAYER_IMAGE, (self.player.x, self.player.y))
  193.  
  194.         # Draw score
  195.         self.screen.blit(score, (0,0))
  196.  
  197.  
  198.         pygame.display.update()
  199.  
  200.     def on_event(self, event):
  201.  
  202.         if event.type == QUIT:
  203.             self.running = False
  204.         elif event.type == KEYDOWN:
  205.             if event.key == K_ESCAPE:
  206.                 self.running = False
  207.             if event.key == K_LEFT:
  208.                 self.player.moving_left = True
  209.             elif event.key == K_RIGHT:
  210.                 self.player.moving_right = True
  211.             if event.key == K_UP or event.key == K_SPACE:
  212.                 self.player.jumping = True
  213.             elif event.key == K_DOWN:
  214.                 self.player.moving_down = True
  215.  
  216.         elif event.type == KEYUP:
  217.             if event.key == K_LEFT:
  218.                 self.player.moving_left = False
  219.             elif event.key == K_RIGHT:
  220.                 self.player.moving_right = False
  221.             if event.key == K_UP or event.key == K_SPACE:
  222.                 self.player.jumping = False
  223.             elif event.key == K_DOWN:
  224.                 self.player.moving_down = False
  225.  
  226.  
  227.  
  228.  
  229.     def on_loop(self):
  230.         pass
  231.  
  232.  
  233.     def has_platform_passed_player(self, platform):
  234.         if platform.y > self.player.y:
  235. #            print("PASSED")
  236.             if platform.passed_player == False:
  237.                 platform.passed_player = True
  238.                 self.GENOME_SCORE += 10
  239.  
  240.  
  241.     def reset(self, platform):
  242.         if platform.y > self.HEIGHT:
  243.             platform.y = -15
  244.             platform.x = random.randint(0, self.WIDTH)
  245.             platform.passed_player = False
  246.             # GENOME_SCORE += 1
  247.  
  248.     # functions to create our resources
  249.     def load_image(self, name, colorkey=None):
  250.         # fullname = resources_dir + "/" + name
  251.         fullname = resources_dir + os.sep + name
  252. #        print(fullname)
  253.         try:
  254.             image = pygame.image.load(fullname)
  255.         except pygame.error:
  256.             print('Cannot load image:', fullname)
  257.             raise SystemExit(str(geterror()))
  258.         image = image.convert()
  259.         if colorkey is not None:
  260.             if colorkey is -1:
  261.                 colorkey = image.get_at((0, 0))
  262.             image.set_colorkey(colorkey, RLEACCEL)
  263.         return image, image.get_rect()
  264.  
  265.     def eval_genomes(self, genomes, config):
  266.         i = 0
  267.         global GENERATION, MAX_FITNESS, BEST_GENOME
  268.         GENERATION = GENERATION + 1
  269.         for genome_id, genome in genomes:
  270.             genome.fitness = self.main(genome, config)
  271.  
  272.             print("Gen : %d Genome # : %d  Fitness : %f Max Fitness : %f"%(GENERATION,i,genome.fitness, MAX_FITNESS))
  273.             if genome.fitness >= MAX_FITNESS:
  274.                 MAX_FITNESS = genome.fitness
  275.                 BEST_GENOME = genome
  276.             self.GENOME_SCORE = 0
  277.             i+=1
  278.  
  279.     def main(self, genome, config):
  280.  
  281.         self.init(800, 600)
  282.         net = neat.nn.FeedForwardNetwork.create(genome, config)
  283.         self.start_time = pygame.time.get_ticks()
  284.         #distances = []
  285.         while self.running:
  286.             self.counting_time = pygame.time.get_ticks() - self.start_time
  287.             self.timedelta = self.clock.tick(FPS)
  288.             self.timedelta /= 1000
  289.             inputs = []
  290.             for platform in self.platforms:
  291.                 inputs.append(platform.x)
  292.                 inputs.append(platform.y)
  293.                 self.has_platform_passed_player(platform)
  294.                 #plat_x = (platform.x + platform.width ) / 2
  295.                 #plat_y = (platform.y + platform.height) / 2
  296.                 # distances.append()
  297.             inputs.append(self.player.x)
  298.             inputs.append(self.player.y)
  299.             print(inputs)
  300.             x = 0
  301.             # Check for collisions
  302.             for platform in self.platforms:
  303.                 x = self.on_collision(platform)
  304.                 if x != 0:
  305.                     print("x = ", x, ", genome_score = " , self.GENOME_SCORE)
  306.                     return x / 10 + self.GENOME_SCORE
  307.  
  308.             x = self.update_player_position()
  309.  
  310.             if x != 0:
  311.                 print("x = ", x, ", genome_score = " , self.GENOME_SCORE)
  312.                 return x / 10 + self.GENOME_SCORE
  313.  
  314.             output = net.activate(inputs)
  315. #            print("Output: ", output)
  316.  
  317.             if output[0] >= 0.5:
  318.                 self.jump()
  319.             elif output[1] >= 0.5:
  320.                 self.move_left()
  321.             if output[2] >= 0.5:
  322.                 self.move_right()
  323.             if output[3] >= 0.5:
  324.                 self.move_down()
  325.  
  326.             self.counting_seconds = str((self.counting_time % 60000) / 1000).zfill(2)
  327.             self.on_render()
  328. #            self.clock.tick(FPS)
  329.  
  330.  
  331.         print("Highest score:", self.HIGH_SCORE, sep=' ')
  332.         pygame.quit()
  333.  
  334.     def run(self):
  335.         config = neat.Config(neat.DefaultGenome, neat.DefaultReproduction,
  336.                          neat.DefaultSpeciesSet, neat.DefaultStagnation,
  337.                          'config')
  338.         pop = neat.Population(config)
  339.         stats = neat.StatisticsReporter()
  340.         pop.add_reporter(stats)
  341.         winner = pop.run(self.eval_genomes, 1000)
  342.         outputFile = "bestGenome/winner.p"
  343.         with open(outputFile, 'wb') as pickle_file:
  344.             pickle.dump(all, pickle_file)
  345.  
  346.  
  347. if __name__ == "__main__":
  348.     game = Game(800, 600)
  349.     game.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement