class Program: def __init__(self, arg): pygame.init() self.opt = Setting() self.name_map = arg.name_map self.screen = pygame.display.set_mode((self.opt.WIDTH + self.opt.TILE_SIZE*15,self.opt.HEIGHT + self.opt.TILE_SIZE*3)) self.set_grill_surface() pygame.display.set_caption(self.opt.TITLE) self.path = os.path.dirname(__file__) self.path_img = os.path.join(self.path, ".." , "src", "img") self.images = Spritesheet(self) self.path_maps = os.path.join(self.path, ".." , "src", "maps", self.name_map + self.opt.LUA_FORMAT) self.create = not os.path.exists(self.path_maps) self.builder = Builder(self) self.clock = pygame.time.Clock() self.converter = Converter(self) self.map = Map(self) self.selector = Selector(self) self.toolbar = Toolbar(self) self.loop() pygame.quit() def set_grill_surface(self): self.grill = self.screen.copy() for y in range(0, self.opt.HEIGHT+1, self.opt.TILE_SIZE): pygame.draw.line(self.grill, (255,255,255), (0, y), (self.opt.WIDTH, y)) for x in range(0, self.opt.WIDTH+1, self.opt.TILE_SIZE): pygame.draw.line(self.grill, (255,255,255), (x, 0), (x, self.opt.HEIGHT)) self.grill.set_colorkey((0,0,0)) def draw(self): self.screen.fill((0,0,0)) self.screen.blit(self.map.screen,(0,0)) self.screen.blit(self.grill,(0,0)) self.toolbar.draw(self.screen) self.selector.draw(self.screen) pygame.display.flip() def event(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.pause = not self.pause elif event.key == pygame.K_s: self.builder.save() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: self.selector.click() if event.button == 3: self.selector.remove() elif event.type == pygame.MOUSEMOTION: if event.buttons[0] == 1: self.selector.click() if event.buttons[2] == 1: self.selector.remove() def loop(self): self.running = True self.pause = False while self.running: self.clock.tick(50) self.converter.update() self.selector.update() self.event() self.draw()
class App: windowDimY = 14 windowDimX = 18 windowWidth = 0 windowHeight = 0 toolbarWidth = 200 player = 0 apple = 0 toolbar = 0 dataCollect = 0 displayq = False def __init__(self,dq,state,freq): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(3,self.windowDimX, self.windowDimY) self.windowWidth = self.windowDimX*self.player.step self.windowHeight = self.windowDimY*self.player.step self.toolbar = Toolbar(self.toolbarWidth, self.windowWidth, self.windowHeight) self.apple = Apple(randint(0,self.windowDimX-1), randint(0,self.windowDimY-1)) self.dataCollect = DataCollector() self.displayq=dq self.state_size = state self.frequency = freq def on_init(self): pygame.init() if(self.displayq): self._display_surf = pygame.display.set_mode((self.windowWidth+self.toolbarWidth,self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame Snake game!') self._image_surf = pygame.image.load("images/game_objects/smake.png").convert() self._apple_surf = pygame.image.load("images/game_objects/smapple.png").convert() self.toolbar.load_images() self._running = True # self.savepath = "frames/"+time.strftime("%Y%m%d-%H%M%S") # os.mkdir(self.savepath) def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake collide with itself? for i in range(2,self.player.length): if self.game.isCollision(self.player.x[0],self.player.y[0],self.player.x[i], self.player.y[i],self.player.step-1): print("You lose! Collision with yourself: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") self.player.crashed = True # does snake eat apple? for i in range(0,self.player.length): if self.game.isCollision(self.apple.x,self.apple.y,self.player.x[i], self.player.y[i],self.player.step-1): self.apple.x = randint(0,self.windowDimX-1) * self.player.step self.apple.y = randint(0,self.windowDimY-1) * self.player.step print("apple x=",self.apple.x,"apple y=",self.apple.y) self.player.eatenApple = True #does snake collide with wall? if(self.player.x[0]<0 or self.player.x[0]>=self.windowWidth or self.player.y[0]<0 or self.player.y[0]>=self.windowHeight): print("You lose! Collision with wall: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") self.player.crashed = True pass def on_render(self, state): self._display_surf.fill((0,0,0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) self.toolbar.draw(self._display_surf, self.player.direction, state) pygame.display.flip() def on_cleanup(self): pygame.quit() # initializing agent before the 1st move def init_agent(self, agent): state_init1 = agent.get_state(game, self.player, self.food) #first state after random placement #first action def reset_player(self): self.player = Player(3,self.windowDimX, self.windowDimY) #print(self.player.x) #print(self.player.y) def on_execute(self,speed): print('starting execution!') params = parameters() agent = dqnagent(params,self.state_size) #initialize the agent! if(agent.load_weights): #load weights maybe agent.model.load_weights(agent.weights) print("loaded the weights") counter = 0 #how many games have been played/trials done record = 0 #highest score #--------------------------------------------------------------------------- #------------------------- LOOP THRU EPISODES ------------------------------ #--------------------------------------------------------------------------- while counter<params['episodes']: #still have more trials to do counter += 1 print(counter) print("\nEPISODE ", counter, "\n") if not params['train']: # if you're not training it, no need for exploration agent.epsilon = 0 else: agent.epsilon = 1.0 - ((counter -1) * params['epsilon_decay_linear'])#exploration/randomness factor that decreases over time #print("EPSILON = ", agent.epsilon, "\n") if self.on_init() == False: self._running = False #print("PLAYER\tx : ", self.player.x,"\ty : ", self.player.y, "\n") duration = 0 #--------------------------------------------------------------------------- #--------------------------- INDIVIDUAL EPISODE ---------------------------- #--------------------------------------------------------------------------- # indexx = 0 while(self._running): if(counter%self.frequency==0): self.dataCollect.record(self.player.x, self.player.y, self.apple.x, self.apple.y) duration+=1 #print("\nMOVE : ", duration, "\n") if(self.displayq): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_ESCAPE]): exit(0) oldstate = agent.get_state(self, self.player, self.apple) #print("\noldstate = ", oldstate) #--------------------------- GET AGENT ACTION ---------------------------- if random() < agent.epsilon: #every so often random exploration action = randint(0,3) #random action #print("random action : ",action) else: #Actionprecited by agent state = oldstate.reshape(1,self.state_size**2+8) predictedq= agent.model.predict(state) # predicts the q values for the action in that state action = np.argmax(predictedq[0]) #maximum (highest q) action #print("predicted action : ", action, "\tq-values : ", predictedq) #---------------------------- EXECUTE ACTION ----------------------------- print(action) self.player.do_move(action) #do the action self.on_loop() newstate = agent.get_state(self, self.player, self.apple) #new state from the action we've taken reward = agent.set_reward(self.player) #print("newstate = ", newstate) #print("reward = ", reward) #print("crashed = ", self.player.crashed, "\n") #---------------------------- SHORT TRAINING ----------------------------- if(params['train']): agent.train_short_memory(oldstate,action, reward, newstate, self.player.crashed) agent.remember(oldstate,action, reward, newstate, self.player.crashed) #------------------------------ RENDER GAME ------------------------------ self._running = not(self.player.crashed) if(self.displayq): self.on_render(newstate) # if(counter%self.frequency==0): # self.on_render(newstate) # pygame.image.save(self._display_surf,savepath+str(indexx)) time.sleep (speed/1000.0) # indexx +=1 #--------------------------------------------------------------------------- #----------------------- TRAINING & DATA COLLECTION ------------------------ #--------------------------------------------------------------------------- if(params['train']): agent.replay_new(agent.memory, params['batch_size']) # self.dataCollect.add(self.player.length,duration,agent.epsilon,agent.history.losses) self.dataCollect.add(self.player.length,duration,agent.epsilon, 0.0) self.dataCollect.save() #print(agent.history.losses.length()) #agent.history.losses = [] self.player.reset(3,self.windowDimX, self.windowDimY ) self.on_cleanup() #--------------------------------------------------------------------------- #------------------------------ DATA OUTPUT -------------------------------- #--------------------------------------------------------------------------- if(params['train']): os.mkdir(params['weights_path_save']) agent.model.save_weights(params['weights_path_save']+'/weights.hdf5') self.dataCollect.save()
class PygView(object): def __init__(self, width=640, height=400, fps=30): """Initialize pygame, window, background, font,... """ pygame.init() pygame.display.set_caption("Press ESC to quit") self.pygame = pygame self.width = width self.height = height #self.height = width // 4 self.display = pygame.display self.screen = pygame.display.set_mode((self.width, self.height), pygame.DOUBLEBUF) self.background = pygame.Surface(self.screen.get_size()).convert() self.clock = pygame.time.Clock() self.fps = fps self.playtime = 0.0 self.font = PygFont(pygame) self.sudoku = Sudoku() self.helper = False self.x_loc = 30 self.y_loc = 30 self.x_size = 450 self.y_size = 450 self.x_inc = self.x_size / 9 #number of columns self.y_inc = self.y_size / 9 #number of rows self.grid_x = -1 self.grid_y = -1 self.stats_x_loc = self.x_loc + self.x_size + 30 self.stats_y_loc = self.y_loc self.stats_x_size = 50 self.stats_y_size = 450 self.toolbar_x_loc = 20 self.toolbar_y_loc = self.y_loc + self.y_size + 70 self.toolbar_x_size = 600 self.toolbar_y_size = 80 self.toolbar = Toolbar(self.toolbar_x_size, self.toolbar_y_size, self.toolbar_x_loc, self.toolbar_y_loc) #print(pygame.font.get_fonts()) def select_tile(self, pos): x, y = pos x_low = self.x_loc x_high = self.x_loc + (self.x_inc * 9) y_low = self.y_loc y_high = self.y_loc + (self.y_inc * 9) if (x_low > x) or (y_low > y) or (x_high < x) or (y_high < y): print("No Collision") self.grid_x = -1 self.grid_y = -1 return self.grid_x = int((x - self.x_loc) // self.x_inc) self.grid_y = int((y - self.y_loc) // self.y_inc) print(f"Selection at {self.grid_x}, {self.grid_y}") def process_toolbar(self, raw_event, pos): event = self.toolbar.proccess_event(raw_event, pos) if event == 'New Game': self.playtime = 0.0 self.sudoku = Sudoku() self.run() elif event == 'Load': filename = filedialog.askopenfilename( filetypes=(("Alistair Sudoku Files", ".ajs"), ("All Files", "*.ajs"))) self.playtime = 0.0 self.sudoku.load(filename) self.run() elif event == 'Save': filename = filedialog.asksaveasfile( filetypes=[("Alistair Sudoku Files", "*.ajs")]) self.sudoku.save(filename) elif event == 'Helper': self.helper = not self.helper elif event == 'Solver': self.sudoku.solve() def run(self): """The mainloop """ running = True while running: for event in pygame.event.get(): pos = pygame.mouse.get_pos() if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: running = False numbers = [i for i in range(0, 10)] number = -1 try: number = int(chr(event.key)) except: pass if (number in numbers) and (self.grid_y > -1) and (self.grid_x > -1): print(number) self.sudoku.change_cell(number, self.grid_x, self.grid_y) elif event.type == pygame.MOUSEBUTTONUP: self.select_tile(pos) self.process_toolbar(event, pos) self.screen.fill(WHITE) milliseconds = self.clock.tick(self.fps) self.playtime += milliseconds / 1000.0 # self.draw_debug("FPS: {:6.3}{}PLAYTIME: {:6.3} SECONDS".format( # self.clock.get_fps(), " "*5, self.playtime)) self.draw_sudoku() self.draw_stats() self.screen.blit(self.toolbar.draw(), (self.toolbar_x_loc, self.toolbar_y_loc)) pygame.display.flip() self.screen.blit(self.background, (0, 0)) pygame.quit() def draw_debug(self, text): """Center text in window """ surface = self.font.debug.render(text, True, GREEN, BLACK) # // makes integer division in python3 self.screen.blit(surface, (0, 0)) def draw_sudoku(self): x_loc = self.x_loc y_loc = self.y_loc x_size = self.x_size y_size = self.y_size x_inc = self.x_inc #number of columns y_inc = self.y_inc #number of rows #Draw grid if self.sudoku.game_won(): grid_color = GREEN else: grid_color = BLACK for y in range(0, 3): for x in range(0, 3): x_dest = x_loc + (x_inc * 3 * x) y_dest = y_loc + (y_inc * 3 * y) rect = self.pygame.Rect(x_dest, y_dest, x_inc * 3, y_inc * 3) self.pygame.draw.rect(self.screen, grid_color, rect, 3) for y in range(0, 9): for x in range(0, 9): x_dest = x_loc + (x_inc * x) y_dest = y_loc + (y_inc * y) rect = self.pygame.Rect(x_dest, y_dest, x_inc, y_inc) #self.screen.blit(rect, (x_loc, y_loc)) if (self.grid_x == x) and (self.grid_y == y): self.pygame.draw.rect(self.screen, RED, rect, 3) else: self.pygame.draw.rect(self.screen, grid_color, rect, 1) #Draw Cell contents i = 0 for y in range(0, 9): for x in range(0, 9): self.sudoku.get_possible_for_cell(x, y) x_dest = x_loc + (x_inc * x) y_dest = y_loc + (y_inc * y) if (self.sudoku.grid[x][y].value == 0) and self.helper: i2 = 1 y2_inc = y_inc / 3 x2_inc = x_inc / 3 for y2 in range(0, 3): for x2 in range(0, 3): x2_dest = x_dest + (x2_inc * x2) y2_dest = y_dest + (y2_inc * y2) if i2 in self.sudoku.grid[x][y].possible: text = self.font.tiny.render( str(i2), True, BLACK, WHITE) text_center_x = (x2_inc - text.get_width()) // 2 text_center_y = (y2_inc - text.get_height()) // 2 self.screen.blit(text, (x2_dest + text_center_x, y2_dest + text_center_y)) i2 = i2 + 1 elif self.sudoku.grid[x][y].value != 0: if self.sudoku.grid[x][y].wrong: text = self.font.default.render( str(self.sudoku.grid[x][y]), True, RED, WHITE) else: text = self.font.default.render( str(self.sudoku.grid[x][y]), True, BLACK, WHITE) text_center_x = (x_inc - text.get_width()) // 2 text_center_y = (y_inc - text.get_height()) // 2 self.screen.blit( text, (x_dest + text_center_x, y_dest + text_center_y)) i = i + 1 def draw_stats(self): x_loc = self.stats_x_loc y_loc = self.stats_y_loc x_size = self.stats_x_size y_size = self.stats_y_size edge_x = 10 edge_y = 10 text_1 = f"Time Taken: {int(self.playtime)}" frequencies = self.sudoku.get_number_frequencies() surface_1 = self.font.default.render(text_1, True, BLACK, WHITE) self.screen.blit(surface_1, (y_loc, x_loc)) for i in range(9): text_2 = f"{i+1}: {frequencies[i]}" surface_2 = self.font.default.render(text_2, True, BLACK, WHITE) self.screen.blit(surface_2, (self.x_loc * 2 + self.x_size, self.y_loc + (edge_y * i) + surface_2.get_height() * i))
def run(states, level): # Set up the window for this game state gameWindow = pygame.display.get_surface() pygame.display.set_caption("Editor: " + level) # Get the window width and height rect = gameWindow.get_rect() SCREEN_WIDTH = rect.width SCREEN_HEIGHT = rect.height # Create Pygame clock to regulate frames clock = pygame.time.Clock() # Set up sprite groups sprites = pygame.sprite.Group() dummies = pygame.sprite.Group() Dummy.containers = sprites, dummies player = None # Load and parse the level text file leveltext = open(level, "r") for line in leveltext: line = line.split() if len(line) > 0: if line[0] == "dimensions": LEVEL_WIDTH, LEVEL_HEIGHT = int(line[1]), int(line[2]) elif line[0] == "player": if player != None: player.kill() player = Dummy(line) else: Dummy(line) # Create the camera camera = Camera(0, 0, LEVEL_WIDTH, LEVEL_HEIGHT) # Create the toolbar toolbar = Toolbar(SCREEN_WIDTH) # Create the variables for editor tools clickStart = [0, 0] justSaved = False makingPlatform = False while True: # Get events on the event queue for event in pygame.event.get(): if event.type == QUIT: return states["quit"] elif event.type == KEYDOWN: if event.key == K_ESCAPE: return states["menu"] elif event.key == K_w: camera.setSpeedY(camera.getSpeedY() - 5) elif event.key == K_a: camera.setSpeedX(camera.getSpeedX() - 5) elif event.key == K_s: if pygame.key.get_mods() & KMOD_CTRL: leveltext = open(level, "w") # Save level dimensions leveltext.write("dimensions " + str(LEVEL_WIDTH) + " " + str(LEVEL_HEIGHT) + "\n") # Add all dummy objects to level data for dummy in dummies: leveltext.write(dummy.getDataString()) justSaved = True print "Level saved as " + level else: camera.setSpeedY(camera.getSpeedY() + 5) elif event.key == K_d: camera.setSpeedX(camera.getSpeedX() + 5) elif event.key == K_SPACE: toolbar.toggle() elif event.key == K_1: toolbar.setTool("player") elif event.key == K_2: toolbar.setTool("platform") elif event.key == K_3: toolbar.setTool("enemy") elif event.key == K_4: toolbar.setTool("datboi") elif event.type == KEYUP: if event.key == K_w: camera.setSpeedY(camera.getSpeedY() + 5) elif event.key == K_a: camera.setSpeedX(camera.getSpeedX() + 5) elif event.key == K_s: if not justSaved: camera.setSpeedY(camera.getSpeedY() - 5) else: justSaved = False elif event.key == K_d: camera.setSpeedX(camera.getSpeedX() - 5) elif event.type == MOUSEBUTTONDOWN: if event.button == 1: mouse = pygame.mouse.get_pos() toolbarButton = toolbar.handleMouse(mouse, event.button) if toolbarButton == "none": clickStart = snapToGrid([mouse[0] + camera.getX(), mouse[1] + camera.getY()]) if toolbar.getTool() == "platform": makingPlatform = True elif toolbar.getTool() == "enemy": Dummy(["enemy", str(clickStart[0]), str(clickStart[1])]) elif toolbar.getTool() == "datboi": Dummy(["datboi", str(clickStart[0]), str(clickStart[1] - 32)]) elif toolbar.getTool() == "player": # Replace the old player dummy with the new one if player != None: player.kill() player = Dummy(["player", str(clickStart[0]), str(clickStart[1])]) elif toolbarButton == "quit": return states["menu"] elif toolbarButton == "save": leveltext = open(level, "w") # Save level dimensions leveltext.write("dimensions " + str(LEVEL_WIDTH) + " " + str(LEVEL_HEIGHT) + "\n") # Add all dummy objects to level data for dummy in dummies: leveltext.write(dummy.getDataString()) print "Level saved as " + level elif event.button == 3: mouse = pygame.mouse.get_pos() for dummy in dummies: if dummy.rect.left <= camera.getX() + mouse[0] <= dummy.rect.right and dummy.rect.top <= camera.getY() + mouse[1] <= dummy.rect.bottom: dummy.kill() break elif event.type == MOUSEBUTTONUP: if event.button == 1: if toolbar.getTool() == "platform" and makingPlatform: createPlatform(camera, clickStart) makingPlatform = False camera.move() gameWindow.fill((18, 188, 255)) for sprite in sprites: gameWindow.blit(sprite.image, (sprite.rect.left - camera.getX() + sprite.getOffset()[0], sprite.rect.top - camera.getY() + sprite.getOffset()[1])) if toolbar.getTool() == "platform" and pygame.mouse.get_pressed()[0] and makingPlatform: drawPreviewRect(gameWindow, camera, clickStart) drawGuidelines(gameWindow, camera, SCREEN_WIDTH, SCREEN_HEIGHT) drawBorderlines(gameWindow, camera, LEVEL_WIDTH, LEVEL_HEIGHT) toolbar.draw(gameWindow) clock.tick(60) pygame.display.flip()
class App(object): """A simple OpenGL drawing application.""" def __init__(self, config=default): """Create an instance of a PyRysunek application. Optional arguments: config -- dictionary containing configuration values (see `config.default`) """ self.config = config self.width, self.height = self.config.window_size self.toolbar = Toolbar(self.config.toolbar) self.context = Context( objects = ObjectList(), color_picker = self.toolbar.color_picker, ) self._init_opengl() if config.auto_load_on_start: self.load() def _init_opengl(self): """OpenGL initialization commands.""" glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(*self.config.window_position) glutCreateWindow(self.config.window_title) # Assign callback functions glutDisplayFunc(self.display) glutReshapeFunc(self.reshape) glutMouseFunc(self.mouse) glutMotionFunc(self.motion) glutIdleFunc(self.display) glutKeyboardFunc(self.keyboard) # Set background color glClearColor(*self.config.bg_color) def display(self): """Callback to draw the application in the screen.""" glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Clear frame buffer glClear(GL_COLOR_BUFFER_BIT) for obj in self.context.objects: obj.draw() # Make sure that toolbar is on top of everything self.toolbar.draw() # Flush and swap buffers glutSwapBuffers() def reshape(self, w, h): """Callback to adjust the coordinate system whenever a window is created, moved or resized. """ self.width, self.height = w, h glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() # Define left, right, bottom, top coordinates gluOrtho2D(0.0, w, h, 0.0) def mouse(self, button, state, x, y): """Callback to handle mouse click events.""" if (x, y) in self.toolbar: self.toolbar.mouse(button, state, x, y) else: if state == GLUT_DOWN: self.toolbar.current_tool.mouse_down(x, y, self.context) elif state == GLUT_UP: self.toolbar.current_tool.mouse_up(x, y, self.context) if DEBUG: print "<Mouse click event>" print " button=%s, state=%s, x=%s, y=%s" % (button, state, x, y) print " current_tool = %s" % self.toolbar.current_tool print " len(objects) = %s" % len(self.context.objects) print " objects[-3:] = %s" % self.context.objects[-3:] def motion(self, x, y): """Callback to handle mouse drag events. This method is called by OpenGL/GLUT when a mouse button is pressed and movement occurs. """ self.toolbar.current_tool.mouse_move(x, y, self.context) def keyboard(self, key, x, y): """Callback to handle key down events.""" if key == "\x1b": # Exit on `ESC` keycode. sys.exit(0) elif key == "\x13": # Ctrl+s self.save() elif key == "\x12": # Ctrl+r self.load() else: # Propagate event to toolbar. self.toolbar.keyboard(key, x, y) def save(self): """Save the current objects to disk. Fail silently if `self.config.temp_file` fails to open. """ try: temp_file = open(self.config.temp_file, "wb") pickle.dump(self.context.objects, temp_file) temp_file.close() if DEBUG: print "<Saved objects>" except IOError: if DEBUG: print "<Failed to save objects>" def load(self): """Load objects from disk. Fail silently if `self.config.temp_file` fails to open. """ try: temp_file = open(self.config.temp_file, "rb") self.context.objects = pickle.load(temp_file) temp_file.close() if DEBUG: print "<Load objects>" except IOError: if DEBUG: print "<Failed to load objects>"
class App: windowDimY = 14 windowDimX = 18 windowWidth = 0 windowHeight = 0 toolbarWidth = 200 player = 0 apple = 0 toolbar = 0 def __init__(self): self._running = True self._display_surf = None self._image_surf = None self._apple_surf = None self.game = Game() self.player = Player(3, self.windowDimX, self.windowDimY) self.windowWidth = self.windowDimX * self.player.step self.windowHeight = self.windowDimY * self.player.step self.toolbar = Toolbar(self.toolbarWidth, self.windowWidth, self.windowHeight) self.apple = Apple(randint(0, self.windowDimX - 1), randint(0, self.windowDimY - 1)) def on_init(self): pygame.init() self._display_surf = pygame.display.set_mode( (self.windowWidth + self.toolbarWidth, self.windowHeight), pygame.HWSURFACE) pygame.display.set_caption('Pygame Snake game!') self._running = True self._image_surf = pygame.image.load( "images/game_objects/smake.png").convert() self._apple_surf = pygame.image.load( "images/game_objects/smapple.png").convert() self.toolbar.load_images() def on_event(self, event): if event.type == QUIT: self._running = False def on_loop(self): self.player.update() # does snake collide with itself? for i in range(2, self.player.length): if self.game.isCollision(self.player.x[0], self.player.y[0], self.player.x[i], self.player.y[i], self.player.step - 1): print("You lose! Collision with yourself: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") print("x[" + str(i) + "] (" + str(self.player.x[i]) + "," + str(self.player.y[i]) + ")") exit(0) # does snake eat apple? for i in range(0, self.player.length): if self.game.isCollision(self.apple.x, self.apple.y, self.player.x[i], self.player.y[i], self.player.step - 1): self.apple.x = randint(0, self.windowDimX - 1) * self.player.step self.apple.y = randint(0, self.windowDimY - 1) * self.player.step print("apple x=", self.apple.x, "apple y=", self.apple.y) self.player.eatenApple = True #does snake collide with wall? if (self.player.x[0] < 0 or self.player.x[0] >= self.windowWidth or self.player.y[0] < 0 or self.player.y[0] >= self.windowHeight): print("You lose! Collision with wall: ") print("x[0] (" + str(self.player.x[0]) + "," + str(self.player.y[0]) + ")") exit(0) pass def state(self): middle = int(dim / 2) grid = np.zeros((dim, dim), dtype=bool) print("x=", self.player.x, "y=", self.player.y) relativex = [ int((a - self.player.x[0]) / self.player.step + middle) for a in self.player.x ] relativey = [ int((a - self.player.y[0]) / self.player.step + middle) for a in self.player.y ] for x, y in zip(relativex, relativey): if (x >= 0 and y >= 0 and x < dim and y < dim): grid[y, x] = True print("x", relativex, "y", relativey) right = int(self.windowDimX - (self.player.x[0] / self.player.step) + middle) down = int(self.windowDimY - (self.player.y[0] / self.player.step) + middle) up = int(middle - (self.player.y[0] / self.player.step)) left = int(middle - (self.player.x[0] / self.player.step)) if (right < dim and right >= 0): grid[:, right:] = True if (left < dim and left >= 0): grid[:, :left] = True if (down < dim and down >= 0): grid[down:, :] = True if (up < dim and up >= 0): grid[:up, :] = True print(right, left, up, down) print("GRID after") print(grid) grid = list(grid.flatten()) state = [ self.player.direction == 0, #right self.player.direction == 1, #left self.player.direction == 2, #up self.player.direction == 3, #down self.apple.y < self.player.y[0], #food is up from the player self.apple.y > self.player.y[0], #food is down from the player self.apple.x < self.player.x[0], #food is to the left of the player self.apple.x > self.player.x[0] #food is to the right of the player ] state += grid for i in range(len(state)): #convert list to 0s and 1s if (state[i]): state[i] = 1 else: state[i] = 0 return np.asarray(state) def on_render(self): self._display_surf.fill((0, 0, 0)) self.player.draw(self._display_surf, self._image_surf) self.apple.draw(self._display_surf, self._apple_surf) print(self.state()) self.toolbar.draw(self._display_surf, self.player.direction, self.state()) pygame.display.flip() def on_cleanup(self): pygame.quit() def on_execute(self): if self.on_init() == False: self._running = False while (self._running): pygame.event.pump() keys = pygame.key.get_pressed() if (keys[K_RIGHT]): self.player.moveRight() if (keys[K_LEFT]): self.player.moveLeft() if (keys[K_UP]): self.player.moveUp() if (keys[K_DOWN]): self.player.moveDown() if (keys[K_ESCAPE]): self._running = False self.on_loop() self.on_render() time.sleep(70.0 / 1000.0) self.on_cleanup()
class App(object): """A simple OpenGL drawing application.""" def __init__(self, config=default): """Create an instance of a PyRysunek application. Optional arguments: config -- dictionary containing configuration values (see `config.default`) """ self.config = config self.width, self.height = self.config.window_size self.toolbar = Toolbar(self.config.toolbar) self.context = Context( objects=ObjectList(), color_picker=self.toolbar.color_picker, ) self._init_opengl() if config.auto_load_on_start: self.load() def _init_opengl(self): """OpenGL initialization commands.""" glutInit(sys.argv) glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE) glutInitWindowSize(self.width, self.height) glutInitWindowPosition(*self.config.window_position) glutCreateWindow(self.config.window_title) # Assign callback functions glutDisplayFunc(self.display) glutReshapeFunc(self.reshape) glutMouseFunc(self.mouse) glutMotionFunc(self.motion) glutIdleFunc(self.display) glutKeyboardFunc(self.keyboard) # Set background color glClearColor(*self.config.bg_color) def display(self): """Callback to draw the application in the screen.""" glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Clear frame buffer glClear(GL_COLOR_BUFFER_BIT) for obj in self.context.objects: obj.draw() # Make sure that toolbar is on top of everything self.toolbar.draw() # Flush and swap buffers glutSwapBuffers() def reshape(self, w, h): """Callback to adjust the coordinate system whenever a window is created, moved or resized. """ self.width, self.height = w, h glViewport(0, 0, w, h) glMatrixMode(GL_PROJECTION) glLoadIdentity() # Define left, right, bottom, top coordinates gluOrtho2D(0.0, w, h, 0.0) def mouse(self, button, state, x, y): """Callback to handle mouse click events.""" if (x, y) in self.toolbar: self.toolbar.mouse(button, state, x, y) else: if state == GLUT_DOWN: self.toolbar.current_tool.mouse_down(x, y, self.context) elif state == GLUT_UP: self.toolbar.current_tool.mouse_up(x, y, self.context) if DEBUG: print "<Mouse click event>" print " button=%s, state=%s, x=%s, y=%s" % (button, state, x, y) print " current_tool = %s" % self.toolbar.current_tool print " len(objects) = %s" % len(self.context.objects) print " objects[-3:] = %s" % self.context.objects[-3:] def motion(self, x, y): """Callback to handle mouse drag events. This method is called by OpenGL/GLUT when a mouse button is pressed and movement occurs. """ self.toolbar.current_tool.mouse_move(x, y, self.context) def keyboard(self, key, x, y): """Callback to handle key down events.""" if key == "\x1b": # Exit on `ESC` keycode. sys.exit(0) elif key == "\x13": # Ctrl+s self.save() elif key == "\x12": # Ctrl+r self.load() else: # Propagate event to toolbar. self.toolbar.keyboard(key, x, y) def save(self): """Save the current objects to disk. Fail silently if `self.config.temp_file` fails to open. """ try: temp_file = open(self.config.temp_file, "wb") pickle.dump(self.context.objects, temp_file) temp_file.close() if DEBUG: print "<Saved objects>" except IOError: if DEBUG: print "<Failed to save objects>" def load(self): """Load objects from disk. Fail silently if `self.config.temp_file` fails to open. """ try: temp_file = open(self.config.temp_file, "rb") self.context.objects = pickle.load(temp_file) temp_file.close() if DEBUG: print "<Load objects>" except IOError: if DEBUG: print "<Failed to load objects>"