Esempio n. 1
0
    def __init__(self, port):
        self.running = False

        self.pid = 0
        self.pids = []

        self.nbPlayer = 0
        self.players = {}

        self.entities = {}

        self.moves = []
        self.shoot = False
        self.shoots = []
        self.deads = []
        self.killed = []

        self.input = Input()
        self.graphics = Graphics()
        self.velocity = Constant.VELOCITY

        self.id = 0
        self.port = port

        self.players_socket = {}
        self.players_socket_awaiting = {}

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind(('', self.port))
        self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.socket.listen(5)
Esempio n. 2
0
def main():
    Graphics.init(Size(1280, 720))
    Time.init()

    line = GameObject()
    line.add_component(LineRenderer(Vector2(0, 0), Vector2(10, 10)))

    fps = GameObject()
    text = fps.add_component(Text)

    # game loop
    while True:
        # check for events
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN
                                      and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

        update()

        text.text = str(int(Time.time))
        text.transform.position = text.transform.position + Vector2(1, 0)

        Graphics.draw()
Esempio n. 3
0
 def timer(self):
     print "Time: ", self.time
     print '==============\n'
     g = Graphics(config.MAP)
     g.print_grid()
     sleep(config.SLEEP_TIME)
     self.time += 1
Esempio n. 4
0
 def timer(self):
     print "Time: ", self.time
     print '==============\n'
     g = Graphics(config.MAP)
     g.print_grid()
     sleep(config.SLEEP_TIME)
     self.time += 1
Esempio n. 5
0
def loop():
	g = Graphics()
	last_paint = 0

	pygame.key.set_repeat(500, 100)

	model = type('Model', (object,), {})
	model.exit = False
	model.new_scene = 'main_menu'
	model.wait = False	

	t = time.time()
	while not model.exit:
		
		while model.new_scene != None:
			next_scene = model.new_scene
			model.new_scene = None
			clazz = scenes[next_scene]
			#give the scene a handle to the mixer
			scene = clazz(model)

		events = pygame.event.get()
		keymap = {}
		for event in events:
			if event.type == pygame.KEYDOWN:
				if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
					return
			
		scene.update(events, time_passed = time.time() - t)
		t = time.time()

		if time.time() - last_paint > 1/30.0 or model.wait:
			#print 'fps: ', 1.0/(time.time() - last_paint)
			last_paint = time.time()
			g.paint(scene, model)
Esempio n. 6
0
  def __init__(self, asset_path, fps, loc):
      """
        asset_path: the full path to the directory containing the art assets for this animation
      """
      model = [ (0,0), (0,100), (100,100), (100,0) ]
      super(AnimatedActor,self).__init__( model )
      gfx = Graphics()
      self._textures = list()
      image_names = os.listdir(asset_path)
      image_names.sort()
      for each in image_names:  
        path = os.path.join( asset_path, each ) #use path.join to insure cross platform
        self._textures.append( gfx.texture_register(path) )#register the texture with the graphics

        #we need to scale, and the scale factor needs to come from somewhere
#      for i,v in enumerate(self.images):
#        self.images[i] = pygame.transform.scale(v,( v.get_height()/3, v.get_width()/3    ))


      # Track the time we started, and the time between updates.
      # Then we can figure out when we have to switch the image.
      self._start = pygame.time.get_ticks()
      self._delay = 1000 / fps
      self._last_update = 0
      self._frame = 0

        # Call update to set our first image.
      self.update(pygame.time.get_ticks())
      self.loc = loc

      self.alive = True
      self.repeat = False
Esempio n. 7
0
    def __init__(self, asset_path, fps, loc):
        """
        asset_path: the full path to the directory containing the art assets for this animation
      """
        model = [(0, 0), (0, 100), (100, 100), (100, 0)]
        super(AnimatedActor, self).__init__(model)
        gfx = Graphics()
        self._textures = list()
        image_names = os.listdir(asset_path)
        image_names.sort()
        for each in image_names:
            path = os.path.join(asset_path,
                                each)  #use path.join to insure cross platform
            self._textures.append(gfx.texture_register(
                path))  #register the texture with the graphics

            #we need to scale, and the scale factor needs to come from somewhere


#      for i,v in enumerate(self.images):
#        self.images[i] = pygame.transform.scale(v,( v.get_height()/3, v.get_width()/3    ))

# Track the time we started, and the time between updates.
# Then we can figure out when we have to switch the image.
        self._start = pygame.time.get_ticks()
        self._delay = 1000 / fps
        self._last_update = 0
        self._frame = 0

        # Call update to set our first image.
        self.update(pygame.time.get_ticks())
        self.loc = loc

        self.alive = True
        self.repeat = False
Esempio n. 8
0
    def __init__(self, game= 0, playersave= 0):
        self.type  = "player"
        self.game = game
#        self.chunkno = 0
#        self.spawn = (240,260)    #spawn coordinates
        self.velx, self.vely, self.kbvelx, self.kbvely = 0, 0, 0, 0
        self.size = (24,48)        #size of the player sprite, used for hitbox logic etc. This cannot be changed without changing the logic in the hitbox functions!
        self.screensize = (32,48)

        self.upperbody = Graphics.loadplayerimages()[0]
        self.lowerbody = Graphics.loadplayerimages()[1]
        self.playervarsa()
        if not playersave:
            self.playervarsb_make()
            self.spawn = False
        else:
            self.playervarsb_load(playersave)
        
        #playerstatus variables
        self.walking, self.working, self.jumping, self.falling, self.knockedback = False, False, False, False, False
        self.walksound, self.worksound = False, False
        self.rect = pygame.Rect((0, 0), (40, 48))
        self.attrect = pygame.Rect((-100, -100), self.size)
        self.walkanimation = False
        self.workanimation = True
        self.dir = 0
def due_picture():
    data_list = db.run_query("due.sql")
    new_list = DueDate.time_converter(data_list)
    return_list = DueDate.make_dict(new_list)

    Graphics.setup(mode="RGBA", size=(1024, 1024), color=(255, 255, 255, 200))
    Graphics.make_image(return_list, "due.png")
Esempio n. 10
0
    def __init__(self):
        self.temp = 0
        self.data = []
        # *************************#
        self.barrier_out_flag = 0
        self.input_chess_show = 0
        self.opposite_ch = 0
        self.queen_single_flag_in = 0
        self.queen_single_flag_out = 0
        self.queen_single_flag = 0
        self.main_status = MAIN_WAIT
        self.main_status_count = 0
        self.go = True
        self.go_status = GO_WAIT
        self.model = knn()
        self.optim = number_confirm(57)
        self.bd = barrier_detect()
        # self.uart = uart()
        self.graph = Graphics()
        self.img = '加入视频提取的图像'
        self.status = WAIT
        self.last_status = WAIT
        self.button_status = UP
        self.dis = 25  # 目标数字
        self.dis_list = [self.dis]
        self.barrier_list = []
        self.last_angel = 0
        self.last_position = [7, 0]  # 行进中上一次的位置
        self.barrier_dir = 'none'
        self.arm_status = 0
        self.arm_count = 0
        self.system_mode = QUEEN
        self.mode = 0  #1:put 2:take
        self.queen_mode = TAKE
        self.press = False
        self.barrier_flag = 0
        # *************************#
        self.debug = False
        self.capture = cv2.VideoCapture(0)
        # *************************#
        # 数字上次的位置坐标
        self.last_location = [150, 150]
        # 小车的位置 [数字坐标,x,y]
        self.pos = [64, 150, 150]
        # 障碍 [type, i ,j]
        self.bundary_list = []  #[, [3,2,2]]
        # 棋子 [number]
        self.chess_list = []  #[15]
        # 棋盘
        self.map = np.zeros((17, 17), dtype=np.int)
        # 路径
        self.path = []
        # *************************#
        super(Map_gui, self).__init__()

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.interrupt)
        self.timer.start(25)
        self.init_ui()
Esempio n. 11
0
    def __init__(self):
        self.graphics = Graphics()
        self.board = Board()

        self.turn = Color.BLUE
        self.selected_piece = None  # a board location.
        self.hop = False
        self.selected_legal_moves = []
Esempio n. 12
0
    def __init__(self, led_count):
        self.terminal = Terminal()
        print(self.terminal.enter_fullscreen)

        self.graphics = Graphics(led_count)

        self.raspberry = Raspberry(self.on_step)
        self.websockets_server = WebsocketsServer(self.on_message)
Esempio n. 13
0
class Display(object):
    """
    The display manager owns the pygame screen object, and the translation
    between world coordinates and screen coordinates. It also dispatches to the
    Graphics class to draw various kinds of objects.

    Architecturally, the display manager looks at the environment, and shows it
    as it chooses, rather than having the environment tell the display manager
    how to show its various pieces.
    """
    def __init__(self, environment, screen_size):
        self.environment = environment
        self.screen_size = screen_size
        self.pixels_per_unit = 15 # TEMP, hardcoded zoom level.
        flags = pg.HWSURFACE | pg.DOUBLEBUF
        if FULLSCREEN:
            flags |= pg.FULLSCREEN
        self.screen = pg.display.set_mode(tuple(self.screen_size), flags)

        self.screen_origin = vec.div(self.screen_size, 2)

        self.widgets = []

        if SHOW_JOYSTICK:
            for i, inp in enumerate(self.environment.inputs):
                self.widgets.append(JoystickWidget(self, inp, i))
        if SHOW_INFO:
            self.fps = 0.0
            self.widgets.append(InfoWidget(self))

        self.widgets.append(HealthWidget(self, self.environment.players))

        self.graphics = Graphics(self)

    def draw(self):
        self.screen.fill(BG_COLOR)

        for o in self.environment.objects:
            self.graphics.draw(o)
        for widget in self.widgets:
            widget.draw(self.screen)

        pg.display.flip()

    def to_screen(self, pos):
        """Convert pos to screen coordinates.

        Takes a tuple a world position, and returns a tuple for the
        screen position.
        """
        x, y = vec.add(
            self.screen_origin,
            vec.mul(pos, self.pixels_per_unit),
        )
        return (int(x), int(y))

    def set_fps(self, fps):
        self.fps = fps
Esempio n. 14
0
class Display(object):
    """
    The display manager owns the pygame screen object, and the translation
    between world coordinates and screen coordinates. It also dispatches to the
    Graphics class to draw various kinds of objects.

    Architecturally, the display manager looks at the environment, and shows it
    as it chooses, rather than having the environment tell the display manager
    how to show its various pieces.
    """
    def __init__(self, environment, screen_size):
        self.environment = environment
        self.screen_size = screen_size
        self.pixels_per_unit = 15  # TEMP, hardcoded zoom level.
        flags = pg.HWSURFACE | pg.DOUBLEBUF
        if FULLSCREEN:
            flags |= pg.FULLSCREEN
        self.screen = pg.display.set_mode(tuple(self.screen_size), flags)

        self.screen_origin = vec.div(self.screen_size, 2)

        self.widgets = []

        if SHOW_JOYSTICK:
            for i, inp in enumerate(self.environment.inputs):
                self.widgets.append(JoystickWidget(self, inp, i))
        if SHOW_INFO:
            self.fps = 0.0
            self.widgets.append(InfoWidget(self))

        self.widgets.append(HealthWidget(self, self.environment.players))

        self.graphics = Graphics(self)

    def draw(self):
        self.screen.fill(BG_COLOR)

        for o in self.environment.objects:
            self.graphics.draw(o)
        for widget in self.widgets:
            widget.draw(self.screen)

        pg.display.flip()

    def to_screen(self, pos):
        """Convert pos to screen coordinates.

        Takes a tuple a world position, and returns a tuple for the
        screen position.
        """
        x, y = vec.add(
            self.screen_origin,
            vec.mul(pos, self.pixels_per_unit),
        )
        return (int(x), int(y))

    def set_fps(self, fps):
        self.fps = fps
Esempio n. 15
0
    def __init__(self: 'Game') -> 'None':

        self.graphics = Graphics()
        self.audio = Audio()
        self.controller = Controller()
        self.data = Data()
        self.clock = Clock()

        return None
def updateCamera(screen, game, center, space, draw_options):
    x, y = screen.get_size()
    c_x, c_y = pygame_util.to_pygame(center, game)
    dest = max(c_x - x // 2, 0), max(c_y - y // 2, 0)
    print((x, y), (c_x, c_y), dest)
    screen.fill((0, 0, 0))
    graph.drawStars(screen, center)
    game.blit(screen, dest)
    space.debug_draw(draw_options)
    screen.blit(game, (0, 0), pg.Rect(dest[0], dest[1], x, y))
Esempio n. 17
0
class Game(events.EventEnabled):
    """
    
    """

    # TODO: hack!!
    def __init__(self, chat):
        """
        
        """
        events.EventEnabled.__init__(self)
        self.gamestate = GameState()
        self.game_logic = GameLogic(self.gamestate)
        self.graphics = Graphics()
        self.event_source = events.RootEventSource()
        self.event_source.set_blocking(False)

        self.chat = chat
        self._running = True

        self.reg_event_func(pygame.QUIT, self.on_quit)
        self.reg_event_func(pygame.KEYDOWN, self.on_key)
        self.event_source.add_listener(self)

        self.clock = pygame.time.Clock()

    def run(self):
        """
        
        """
        # here comes the main loop of the game
        self._running = True
        while self._running:
            self.clock.tick(60)
            # update network
            # update events
            self.event_source.update()
            # update gamelogic
            # udpate gamestate
            self.gamestate.update()
            # update graphics (draw)
            self.graphics.update(self.chat)

    def on_quit(self, event):
        """
        
        """
        self._running = False

    def on_key(self, event):
        if event.key == pygame.K_F1:
            print self.clock.get_fps()
        elif event.key == pygame.K_ESCAPE:
            pygame.event.post(pygame.event.Event(pygame.QUIT))
Esempio n. 18
0
    def run(self):
        placer = Placer(NEW, NR_OLD_ONES, from_nr)
        if SHOW:
            graphics = Graphics(placer)
            graphics.display()

            while True:
                pass

        else:
            placer.run()
Esempio n. 19
0
def main():
    input = ComLine(sys.argv[1:])
    cvFile = CV(input.args.cv)
    cvFile.readText()
    #cvFile.printText()

    so = CVStats(cvFile.d, input.args.out)
    so.calcStats()
    so.printStats()

    plot = Graphics(cvFile.d, input.args.cv)
    plot.printFigure()
Esempio n. 20
0
 def __init__(self, goal_value, agent=None, graphics=True):
     self.goal = goal_value
     self.graphics = graphics
     self.score = 2
     self._legal_moves = []
     # Initialize state space representation
     self._current_state = {
         (0, 0): 0,
         (1, 0): 0,
         (2, 0): 0,
         (3, 0): 0,
         (0, 1): 0,
         (1, 1): 0,
         (2, 1): 0,
         (3, 1): 0,
         (0, 2): 0,
         (1, 2): 0,
         (2, 2): 0,
         (3, 2): 0,
         (0, 3): 0,
         (1, 3): 0,
         (2, 3): 0,
         (3, 3): 0
     }
     # Initialize Graphics and keybindings
     if self.graphics:
         self._root = Graphics()
     self.__random_cell()  # Make first random cell
     self.print_state()
     if not agent:
         self._root.back_grid.bind('<KeyPress-Up>', self.__up)
         self._root.back_grid.bind('<KeyPress-Down>', self.__down)
         self._root.back_grid.bind('<KeyPress-Left>', self.__left)
         self._root.back_grid.bind('<KeyPress-Right>', self.__right)
     # If using AI, initiate first event
     if agent:
         self.agent = agent
         if self.graphics:
             self._root.back_grid.bind(
                 '<<Action>>', self._agent_move)  # Bind virtual events
             self._root.back_grid.bind('<<Up>>', self.__up)
             self._root.back_grid.bind('<<Down>>', self.__down)
             self._root.back_grid.bind('<<Left>>', self.__left)
             self._root.back_grid.bind('<<Right>>', self.__right)
             self._root.back_grid.after(
                 100, self._agent_move)  # Start agent move loop
         else:
             self.end = False
             while not self.end:
                 self._agent_move(None)
     # Begin main loop of Tkinter, wait for input
     if self.graphics:
         self._root.mainloop()
Esempio n. 21
0
def sierpinski(triangle: Triangle, level, graphics: Graphics):
    """
    Draw the Sierpinski triangle.
    """
    assert (level >= 0), 'level must be >= 0'
    if level == 0:
        graphics.draw_polygon(triangle, level)
    else:
        central_triangle, corner_triangles = get_sub_triangles(triangle)
        graphics.draw_polygon(central_triangle, level)
        for corner_triangle in corner_triangles:
            sierpinski(corner_triangle, level - 1, graphics)
Esempio n. 22
0
    def renderhud(inventory, inventoryqty, inventoryselected, inventoryopen, windowsize, fps, playerhealth):    #Creates the heads up display surface
        '''Creates and returns HUD'''
        #in: list of 40xint, int 0-9 , bool, tuple of 2 int
        #out: Surface object
        invsurf = pygame.Surface(windowsize, pygame.SRCALPHA, 32)
        text = pygame.font.Font(None, 15).render("FPS:" + str(fps)[0:4], 1, (84, 101, 112))
        invsurf.blit(text, (20,10)) 
        
        slotsize = (40,40)
        slotcolor = (42,42,160)
        slotnumcolor = (220, 220, 220)
        slotnumcolorselected = (40, 200, 40)
        slotnumsize = 16
        slotalpha = 180
        slotoffset = (8,8)
        slotoffset0 = (20, 20)
        
        #inventory
        if not inventoryopen:
            for slot in range(10):
                    slotimg = pygame.Surface(slotsize)
                    slotimg.fill(slotcolor)
#                    if inventory[slot] < 256:
                    slotimg.blit(Graphics.toolimg(inventory[slot]), (0,0))
                    slotimg.set_alpha(slotalpha)
                    slotimg.blit(pygame.font.Font(None, slotnumsize).render(str((slot +1)if slot < 9 else 0), 1, slotnumcolor if not slot == inventoryselected else slotnumcolorselected), (2,2))
                    slotimg.blit(pygame.font.Font(None, slotnumsize).render(str(inventoryqty[slot]), 1, slotnumcolor if not slot == inventoryselected else slotnumcolorselected), (2,28))
                    invsurf.blit(slotimg, (slot * (slotsize[0] + slotoffset[0]) + slotoffset0[0], slotoffset0[1]))

        elif inventoryopen:
            for row in range(4):
                for slot in range(10):
                    slotimg = pygame.Surface(slotsize)
                    slotimg.fill(slotcolor)
                    slotimg.blit(Graphics.toolimg(inventory[slot + 10*row]), (0,0))
                    slotimg.set_alpha(slotalpha)
                    if row ==0:
                        slotimg.blit(pygame.font.Font(None, slotnumsize).render(str(slot +1), 1, slotnumcolor if not slot == inventoryselected else slotnumcolorselected), (2,2))
                    slotimg.blit(pygame.font.Font(None, slotnumsize).render(str(inventoryqty[slot +10*row]), 1, slotnumcolor if not slot == inventoryselected else slotnumcolorselected), (2,28))
                    invsurf.blit(slotimg, (slot * (slotsize[0] + slotoffset[0]) + slotoffset0[0], row * (slotsize[1] + slotoffset[1]) + slotoffset0[1]))
        
        #health hearts
        for i in range(playerhealth[1] / 20):
            if playerhealth[0] / 20:
                playerhealth[0] -=20
                invsurf.blit(Graphics.hearts[0], (windowsize[0] - 46, 20 + 32 *i))
            elif playerhealth[0] / 10:
                playerhealth[0] -=10
                invsurf.blit(Graphics.hearts[1], (windowsize[0] - 46, 20 + 32 *i))
            else:
                invsurf.blit(Graphics.hearts[2], (windowsize[0] - 46, 20 + 32 *i))
                
        return invsurf
Esempio n. 23
0
    def get_graphics(self):
        url = os.path.join(self._task_master.get_bundle_path(), 'html-content',
                           self._uri)

        graphics = Graphics()
        webkit = graphics.add_uri('file://' + url, height=self._height)
        graphics.set_zoom_level(self._zoom_level)

        self._task_master.activity.set_copy_widget(webkit=webkit)
        self._task_master.activity.set_paste_widget()

        return graphics, self._prompt
Esempio n. 24
0
 def __init__(self, snake_picker=None, snake_getter=None):
     self.master = tk.Tk()
     canvas = tk.Canvas(
         self.master, width=WINDOW_SIZE[0], height=WINDOW_SIZE[1])
     self.pick_snake = snake_picker
     self.get_snake_number = snake_getter
     self.init_snake()
     self.free_space = []
     self.calculate_free_space()
     self.food = Food(self.free_space)
     self.graphics = Graphics(canvas)
     self.bind_events()
Esempio n. 25
0
    def get_graphics(self):
        name = self._get_user_name().split(',')[0]
        url = os.path.join(self._task_master.get_bundle_path(), 'html-content',
                           '%s?NAME=%s' %
                           (self._uri, utils.get_safe_text(name)))
        graphics = Graphics()
        webkit = graphics.add_uri('file://' + url, height=self._height)
        graphics.set_zoom_level(self._zoom_level)

        self._task_master.activity.set_copy_widget(webkit=webkit)
        self._task_master.activity.set_paste_widget()

        return graphics, self._prompt
Esempio n. 26
0
    def __init__(self, show_graphics: bool = True):

        self.running: bool = True

        self.game = GameController(self)
        RunController.game = self.game

        self.gph = Graphics(self, self.game.map, self.game.player)
        RunController.gph = self.gph

        self.game_events: list = []
        self.show_graphics: bool = show_graphics
        self.graphics_events: deque = deque([])
Esempio n. 27
0
    def run(self, actual_map, size):
        final_path = [self.start]
        graphics = Graphics(actual_map, self.start, self.goal, size=size)
        graphics.display(final_path, self.obstacles)

        path = self.init_path()
        if path == None:
            return None

        curr = self.get(self.start)

        while curr.loc != self.goal:
            self.change_map(actual_map, curr)
            path = self.navigate_map(curr)

            if path == None:
                return None

            curr = self.get(path[1])
            final_path.append(path[1])

            graphics.display(final_path, self.obstacles)

        graphics.display(final_path, self.obstacles, done=True)
        return final_path
Esempio n. 28
0
def main():
    display_dimensions = get_display_dimensions(SIDE_LEN, MARGIN_WIDTH)
    graphics = Graphics(display_dimensions, COLOURS)

    main_triangle = get_main_triangle(SIDE_LEN, MARGIN_WIDTH)
    initial_level = len(COLOURS) - 1
    sierpinski(main_triangle, initial_level, graphics)

    status = graphics.save(OUTPUT_PATH)
    if not status.ok:
        print(status.err_str)
        return 1
    print('Created {}.'.format(OUTPUT_PATH))
    return 0
Esempio n. 29
0
class Driver:
    def __init__(self):
        self.game = Game(BOARD_SIZE, START_TILES)
        self.gui = Graphics(self.game.get_board(), self.play)
        self.gui.mainloop()
        # self.play()

    def play(self):
        while not self.game.game_over():
            direction = keyboard.read_key()
            self.game.take_turn(direction)
            self.gui.display_board(self.game.get_board())

    def start_game(self):
        self.game = Game(BOARD_SIZE, START_TILES)
Esempio n. 30
0
 def _load_intro_graphics(self, file_name='generic-problem.html',
                          message=None):
     center_in_panel = Gtk.Alignment.new(0.5, 0, 0, 0)
     url = os.path.join(self.bundle_path, 'html-content', file_name)
     graphics = Graphics()
     if message is None:
         graphics.add_uri('file://' + url)
     else:
         graphics.add_uri('file://' + url + '?MSG=' +
                          utils.get_safe_text(message))
     graphics.set_zoom_level(0.667)
     center_in_panel.add(graphics)
     graphics.show()
     self.set_canvas(center_in_panel)
     center_in_panel.show()
Esempio n. 31
0
def runner(env: Environment, f=50):
    """Opens a pygame window and runs simulation forever.

    Pygame window is initialised and updated once every 'f' iterations
    that the simulation runs. Simulation can be closed with ESC key or
    by clicking on the window close button."""

    g = Graphics()
    i = 0
    while True:
        i += 1
        env.step()
        if i % f == 0:
            i = 0
            g.update(env.particles)
Esempio n. 32
0
    def __init__(self):
        self.program_counter = ProgramCounter()

        self.stack = []

        # Chip 8 has 15 8-bit registers: V0-VE
        # 16th register is carry flag
        self.registers = Registers()

        # Index register
        self.i = 0

        # Graphics memory
        self.graphics = Graphics()

        # Timer registers should count at 60hz
        self.timers = Timers()

        # State of hex-based keypad
        self.keys = Keypad()

        # Chip 8 has 4K memory
        # 0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
        # 0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
        # 0x200-0xFFF - Program ROM and work RAM
        self.memory = Memory()

        self.op_table = [None] * 16
        self.register_opcodes()
Esempio n. 33
0
class Game():
    def __init__(self):
        self.graphics = Graphics()
        self.character = Character(Point(400, 300))
        self.graphics.register(self.character)
        self.event = Event()
        self.event.register(self.character.handler)

    def process_input(self):
        self.event.process_input()

    def update(self):
        self.character.update()

    def render(self):
        self.graphics.render()
Esempio n. 34
0
 def __init__(self, chat_id, bot ):
     conn = sqlite3.connect(dataBaseDjangoDir)
     cursor = conn.cursor()
     cursor.execute("""select * from usuarios_usuario""")
     conn.commit()
     query = (cursor.fetchall())
     for user in query:
         if user[4] == chat_id:
             self.name = user[1]
             self.email = user[4]
             self.authorize = True
             self.help = Help(chat_id)
             self.sensiTags = SensiTags(bot)
             self.graphic = Graphics()
             self.report = Reports()
     self.chat_id = chat_id
Esempio n. 35
0
    def game_loop(self):
        clock = pygame.time.Clock()

        #Initialize
        self.scoreboard = Scoreboard()
        self.timer = CountDown()
        self.control = Control()
        self.graphics = Graphics(self.scoreboard, self.timer);
        self.player = Player(self.graphics)
        self.world = World(self.graphics, self.player) 
        self.logic = Logic(self.player, self.world, self.graphics, self.scoreboard, self.timer, self.control)
        
        while globalvars.run_game:
            delta = clock.tick(30) # fps

            # Catch input event
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                else:
                    self.control.update(event)
                
            # Update 
            self.logic.update(delta)
            self.world.update(delta)
            self.graphics.update(self.screen, delta)
            
            # Render
            self.graphics.draw(self.screen, delta);
            self.screen.blit(self.player.speedmsg, (0, 35))
            self.screen.blit(self.player.rotmsg, (0, 55))            
              
            pygame.display.flip()        
Esempio n. 36
0
 def __init__(self, point):
     super(Character, self).__init__(point)
     self.spritesheet = Graphics.load("./assets/characters/george.png")
     self.mapping = self.get_mapping()
     self.height = 33
     self.width = 24
     self.facing = "down"
Esempio n. 37
0
    def __init__(self):
        ''' Initialize starting state'''
        self.graphics = Graphics()
        self.log = logging.getLogger("Game");
        logging.basicConfig(filename='main.log', level=DEBUG_LEVEL)
        self.log_handler = CursesHandler(self.graphics.windows["log"])
        self.log_handler.setLevel(DEBUG_LEVEL)
        self.log.addHandler(self.log_handler)
        self.commands = Commands(self)
        self.cursor_pos = [0,0]
        self.game_mode = GameModes.normal
        self.world = World(log_handler=self.log_handler)

        try:
            # Try to load a level from a text file and add it to the world
            # self.world.add_level(self.world.read_level('../data/testworld'))
            # self.world.get_current_level().add_entity(entity.creatures.SpaceOrk(5,5))
            self.world.add_level(
                    self.world.generate_level(
                        self.graphics.max_x, self.graphics.world_height))

            #Place player at spawn
            self.player = entity.creatures.Player(1,1)
            for ent in self.world.get_current_level().entities:
                if ent.__class__ == entity.world.PlayerSpawn:
                    self.player = entity.creatures.Player(ent.position[0],ent.position[1])

            self.world.get_current_level().add_entity(self.player)
        except Exception:
            # use better exception
            self.exit(1)

        self.log.debug("Game started")
 def __init__(self, scripts, useGraphics = False, synchronizeGraphics = False, maximumRounds = DEFAULT_MAXIMUM_ROUNDS, decay = 1, minimumRounds = 0):
     '''
     Constructor for Game class.
     
     @param scripts: A dict of robotBehavior objects keyed to the script's name.
     @param useGraphics: The Graphics object being used to render the graphics object. If graphics is None, no graphical display will be done.
     @param synchronizeGraphics: If graphics are being used, making this True will cause the game loop to update at the same rate as the graphics loop,
     rather than running as fast as it can. This is available for debugging purposes.
     @param maximumRounds: The maximum number of rounds in the game.
     @param decay: The decay rate of the game, i.e. the probability that the next round will take place.
     @param minimumRounds: The minimum number of rounds in the game.
     '''
     
     # ====================
     # INITIALIZE VARIABLES
     # ====================
     
     # initialize passed in variables
     self.maximumRounds = maximumRounds
     self.decay = decay
     self.minimumRounds = minimumRounds
     self.scripts = scripts
     
     # if graphics are being used, initialize graphics
     if useGraphics: 
         self.graphics = Graphics()
         self.synchronizeGraphics = synchronizeGraphics
Esempio n. 39
0
    def updateblockgraphix(self, blx, bly):     #updates graphics when a block changes
        self.newtex = Graphics.blocktexture((self.blocks[blx][bly] & 65280) >>8)[(self.blocks[blx][bly] & 240) >> 4]
#        self.surface.blit(self.newtex if not self.blocks[blx][bly] & 0b11110000 == 0b11110000 else pygame.transform.flip(self.newtex, np.random.randint(0, 1), np.random.randint(0, 1)), (blx * 16, bly * 16))
#        self.surface.blit(pygame.transform.flip(self.newtex, np.random.randint(0, 2), np.random.randint(0, 2)) if self.blocks[blx][bly] & 0b11110000 == 0b11110000 else self.newtex, (blx * 16, bly * 16))          #flips
        self.surface.blit(pygame.transform.flip(pygame.transform.rotate(self.newtex, np.random.randint(0, 4) *90), np.random.randint(0, 2), np.random.randint(0, 2))  if self.blocks[blx][bly] & 0b11110000 == 0b11110000 else self.newtex, (blx * 16, bly * 16))          #flips
        if settings.game["debugmode"]:        
            pygame.draw.line(self.surface, Color.red, (0,0), (0,1024))
            pygame.draw.line(self.surface, Color.red, (0,0), (1024,0))
Esempio n. 40
0
class Game:
    def __init__(self):
        self.graphics = Graphics()
        self.board = Board()
        self.selected_piece = None

    def setup(self):
        self.graphics.setup_window()

    def event_loop(self):
        self.mouse_pos = self.graphics.board_coords(pygame.mouse.get_pos())

        for event in pygame.event.get():
            if event.type == QUIT:
                self.quit()
            if event.type == MOUSEBUTTONDOWN:
                if self.board.location(self.mouse_pos).occupant != None and \
                    self.board.location(self.mouse_pos).occupant.color == self.turn:
                    self.selected_piece = self.mouse_pos

                elif self.selected_piece != None and self.mouse_pos in \
                    self.board.legal_moves(self.selected_piece):
                    self.board.move_piece(self.selected_piece, self.mouse_pos)

                else:
                    self.end_turn()

    def update(self):
        self.graphics.update(self.board)

    def quit(self):
        pygame.quit()
        sys.exit()

    def main(self):
        self.setup()

        while True:
            self.event_loop()
            self.update()

    def end_turn(self):
        if self.turn == BLUE:
            self.turn = RED
        else:
            self.turn = BLUE
Esempio n. 41
0
 def __init__(self):
     if ScoreCard.__instance is not None:
         raise Exception("This class is a singleton")
     else:
         ScoreCard.__instance = self
         self.__graphics = Graphics.getInstance()
         self.__remainingLifeCount = self.__maxLifeCount
         print("ScoreCard Initialized")
Esempio n. 42
0
class Engine:
    graphics = Graphics()
    room_index = 0
    input = Input()
    run = True

    #Startet das Spiel und input thread
    def __init__(self):
        input_thread = threading.Thread(target=self.getinput)
        input_thread.start()

        while (self.run):
            self.room_switch()

    #Holt input und fügt ihn dem Input_buffer hinzu
    def getinput(self):
        while (self.run):
            self.input.add_input(ord(getch.getch()))

    #Wechselt room
    def room_switch(self):
        if (self.room_index == 0):
            self.room_index = self.main_loop(Titlescreen)
        elif (self.room_index == 1):
            self.room_index = self.main_loop(Level)
        elif (self.room_index == 2):
            self.room_index = self.main_loop(Gameover)
        else:
            self.run = False

    #main loop berechnet zeit zum pausieren und ruft room funktionen auf
    def main_loop(self, room_class):

        room = room_class()

        while (room.run):

            start_time = time.time()

            #inner loop

            room.update(self.input)
            room.draw()

            #-----

            end_time = time.time()

            if (end_time - start_time < 1000. / self.graphics.frame_limit
                    and end_time - start_time >= 0):
                time.sleep((1000. / self.graphics.frame_limit -
                            (end_time - start_time)) / 1000)

        end = room.ends_with()
        room.clear_objects()
        del room

        return end
Esempio n. 43
0
def main():
    print('The program calculates numerical and analitical solution of the boundary values problem.')
    config = Config()
    config['a'] = float(input('Enter a: ')) if not DEBUG else 0
    config['b'] = float(input('Enter b: ')) if not DEBUG else 1

    config['g(x)'] = input('Enter g(x): ') if not DEBUG else '1'
    config['p(x)'] = input('Enter p(x): ') if not DEBUG else '1'
    config['q(x)'] = input('Enter q(x): ') if not DEBUG else '-2'
    config['f(x)'] = input('Enter f(x): ') if not DEBUG else '2*(-x**2 + x + 1)'

    config['a0'] = float(input('Enter a0: ')) if not DEBUG else 1
    config['a1'] = float(input('Enter a1: ')) if not DEBUG else 0
    config['A'] = float(input('Enter A: ')) if not DEBUG else 1

    config['b0'] = float(input('Enter b0: ')) if not DEBUG else 1
    config['b1'] = float(input('Enter b1: ')) if not DEBUG else -1
    config['B'] = float(input('Enter B: ')) if not DEBUG else -1

    step = float(input('Enter step: ')) if not DEBUG else 0.1
    check = input(
        'Enter the required function (if do not have one - just press enter.)') if not DEBUG else '2.7182818284**x + x**2'

    if not check == '': #or config.is_valid(check):
        rm = ReductionMethod(config)
        ls = LeastSquare(config)
        grp = Graphics()
        xpoints = list()
        rmpoints = list()
        lspoints = list()
        rpoints = list() if check != '' else None
        for set_rm, set_ls in zip(rm.get_values(step), ls.get_values(step)):
            xpoints.append(set_rm[0])
            rmpoints.append(set_rm[1])
            lspoints.append(set_ls[1]-1)    # Replace '-1' by '' if Least Square Method shows incorrect results lower by 1
            if rpoints is not None:
                rpoints.append(eval(check.replace('x', f'({set_rm[0]})')))
        print(ls.get_analytical_solution())
        if rpoints is not None:
            tb = TablePrinter(['xs', *xpoints], ['Reduction Method', *rmpoints], ['Least Square Method', *lspoints], ['Original values', *rpoints])
            tb.print_table()
            grp.draw([xpoints, xpoints, xpoints], [rmpoints, lspoints, rpoints], ['Reduction Method','Least Square Method','Original function'], 'Numerical Analisys Lab 2')
    else:
        print('Sorry, the conditions are not valid.')
        exit()
Esempio n. 44
0
class Actor( object ):
  """
    Base Class for Actors. Actors are any objects with an onscreen representation.

    Actor class contains:
     model    : wireframe model representing the onscreen actor
     rectangle: bounding rectangle, projection of model on to the plane, used for intersection 
                and collision detection            
     texture  : image to texture the model
  """
  def __init__( self, model, texture=None, drawmode='polygon', offset=(0,0) ):
    """
      Initialize the actor
      INPUT:
            - model: unknown representation of this Actor's model, dependent on graphics system
            - texture: unknow representation of the texture to apply to this Actor's model
            - bounding_rect: rectangular projection of this actor's model onto the plane, used
                             for intersection and collision
            - gfx_sys: graphics system reference TODO: get rid of this
    """
    self._model = model #TODO assume array
    #self._boundrect = bounding_rect #TODO assume array
    self._texpath = texture #TODO assume path
    self._mode = drawmode
    self._gfxsys = Graphics()
    self._offset = offset
    if texture: 
      self._texid = self._gfxsys.texture_register( self._texpath )
    else:
      self._texid = None
    self._position = (0,0)
#=================================================================================================
  def draw( self, pos, name ):
    """
      Request that this object be drawn at pos
    """
    self._position = (pos[0]+self._offset[0],pos[1]+self._offset[1])
    #print self._position
    self._gfxsys.blit( self._model, self._position, name, self._texid, self._mode )
#=================================================================================================
  def updatepos( self, pos ):
    """
      update this actor's position outside of a draw call
    """
    self._position = pos
Esempio n. 45
0
 def _load_intro_graphics(self, file_name='generic-problem.html',
                          message=None):
     center_in_panel = Gtk.Alignment.new(0.5, 0, 0, 0)
     url = os.path.join(self.bundle_path, 'html-content', file_name)
     graphics = Graphics()
     if message is None:
         graphics.add_uri('file://' + url)
     else:
         graphics.add_uri('file://' + url + '?MSG=' +
                          utils.get_safe_text(message))
     graphics.set_zoom_level(0.667)
     center_in_panel.add(graphics)
     graphics.show()
     self.set_canvas(center_in_panel)
     center_in_panel.show()
Esempio n. 46
0
def main():
	# Parse arguments
	argparser = argparse.ArgumentParser()
	argparser.add_argument('-g', '--graphics', action="store_true")
	flags = argparser.parse_args()

	# Let there be light! (create an N-particle universe)
	universe = Universe(N_PARTICLES)
	print universe
	
	# Create graphics 
	if flags.graphics and graphics_imported:
		graph = Graphics(universe, GRAPHICS_DIR)
		graph.save_plot()
	
	# Incremenent time
	for i in xrange(50):
		print 'Computing step', i+1
		universe.increment_time()
		if flags.graphics and graphics_imported:
			graph.save_plot()
Esempio n. 47
0
	def __init__(self):

		'''
		Initializes window, canvas, gameplay options and menus,
		loads resources (settings, images, dictionaries)
		and sets up debugging.

		'''

		# Window
		self.size = Size(650, 650)
		self.root = self.createWindow(self.size)
		self.icon = self.loadIcon('icon.png')

		# Internal settings
		self.validState = False 						# Not ready to accept guesses
		self.DEBUG 		= tk.BooleanVar(value=False)	# Print debug messages
		self.VERBOSE 	= tk.BooleanVar(value=True)		# Print verbose debug messages

		# Logging
		self.messages 	= []
		self.logger = Logger('Hangman')

		# Resources
		self.dictData 	= self.loadDictionaries('data/dicts/dictionaries.json')
		self.dictNames 	= [name for name in self.dictData.keys()]
		self.flags 		= self.loadFlags()

		# Gameplay settings
		self.restartDelay   = 1500 	# Delay before new round begins (ms)
		self.revealWhenLost = False	# Reveal the word when the game is lost
		
		# TODO: Save reference to current dict (?)
		self.DICT 			= tk.StringVar(value=choice(self.dictNames)) 	# Select random dictionary
		self.characterSet 	= self.dictData[self.DICT.get()]['characters'] 	# TODO: Make this dictionary-dependent

		# Menus
		self.menubar = self.createMenus()

		# Events
		self.bindEvents()

		# Game play
		self.graphics = Graphics(self.root, *self.size, characterSet=self.characterSet)	# Renderer
		self.logic 	  = Logic(self.graphics.chances)									# Logic
		self.wordFeed = self.createWordFeed(self.DICT.get()) 							# Provides a stream of words and hints
		self.chances  = self.graphics.chances 											# Initial number of chances for each round

		self.word = None # Initialized later on
		self.hint = None # Initialized later on

		# Audio
		self.effects = self.loadAudio()
Esempio n. 48
0
def main():
    ext.init()
    graphics = Graphics(640, 480)

    TTF_Init()
    font = TTF_OpenFont(b"rebel.ttf", 16)
    if(not font):
        print(TTF_GetError())
    color = SDL_Color(180, 189, 180)


    s = "Un Deux Trois Quatre"
    text = b"Un Deux Trois Quatre"
    text2 = bytes(s, "utf-8")

    surface = TTF_RenderText_Solid(font, text2, color)

    x = 50
    y = 30

    srcRect = SDL_Rect(0, 0, surface.contents.w, surface.contents.h)
    dstRect = SDL_Rect(x, y, surface.contents.w, surface.contents.h)

    texture = SDL_CreateTextureFromSurface(graphics.renderer, surface)
    graphics.blit_surface(texture, srcRect, dstRect)


    while(not SDL_QuitRequested()):
        SDL_Delay(250)
        graphics.flip()



    TTF_CloseFont(font)

    TTF_Quit()
    ext.quit()
Esempio n. 49
0
    def get_graphics(self):
        self._entries = []
        name = self._task_master.read_task_data(NAME_UID)
        if name is None:  # Should never happen
            name = ''
        email_address = self._task_master.read_task_data(EMAIL_UID)
        if email_address is None:  # Should never happen
            email_address = ''
        phone_number = self._task_master.read_task_data(PHONE_NUMBER_UID)
        if phone_number is None:  # Should never happen
            phone_number = ''
        school = self._task_master.read_task_data(SCHOOL_NAME)
        if school is None:  # Should never happen
            school = ''
        if self._task_master.returning_user:
            i = 1
            self._task_master.returning_user = False
        else:
            i = 0
        url = os.path.join(
            self._task_master.get_bundle_path(), 'html-content',
            '%s?NAME=%s&EMAIL=%s&PHONE=%s&SCHOOL=%s' %
            (self._uri[i],
             utils.get_safe_text(name),
             utils.get_safe_text(email_address),
             utils.get_safe_text(phone_number),
             utils.get_safe_text(school)))

        graphics = Graphics()
        webkit = graphics.add_uri('file://' + url, height=400)
        graphics.set_zoom_level(self._zoom_level)

        self._task_master.activity.set_copy_widget(webkit=webkit)
        self._task_master.activity.set_paste_widget()

        return graphics, self._prompt
Esempio n. 50
0
 def main(self, selection, args=None):
   self.graphics = Graphics()
   try:
     self.graphics.start()
     while True:
       if selection == 'quit':
         break
       if selection == 'play':
         selection, args = self.playGame(args)
       if selection == 'game over':
         selection, args = self.gameOver(args)
       if selection == 'menu':
         selection, args = self.menu()
   finally:
     self.graphics.cleanUp()
Esempio n. 51
0
class Go(object):
  
  def main(self, selection, args=None):
    self.graphics = Graphics()
    try:
      self.graphics.start()
      while True:
        if selection == 'quit':
          break
        if selection == 'play':
          selection, args = self.playGame(args)
        if selection == 'game over':
          selection, args = self.gameOver(args)
        if selection == 'menu':
          selection, args = self.menu()
    finally:
      self.graphics.cleanUp()

  def playGame(self, args):
    board = Board(args)
    
    blackTurn = True
    message = ''
    passed = False
    
    while True:    
      move = self.graphics.getTurn(board, blackTurn, message)
      if move == 'pass':
        if passed:
          return 'game over', board
        blackTurn = not blackTurn
        message = ''
        passed = True
      else:
        result = board.makeMove(move, blackTurn)
        if result == 'success':
          blackTurn = not blackTurn
          message = ''
          passed = False
        else:
          message = result

  def gameOver(self, args):
    return self.graphics.gameOver(args)

  def menu(self):
    return self.graphics.renderMenu()
Esempio n. 52
0
 def __init__(self, typ, pos, inst, kill, world, player, game):
     self.type = typ
     self.game = game
     self.world = world
     self.player = player
     self.x, self.y = pos[0], pos[1]
     self.velx, self.vely, self.kbvelx, self.kbvely = 0, 0, 0, 0
     self.walking, self.working, self.jumping, self.falling = False, False, False, False
     self.instance = inst
     
     self.kill = lambda: kill(self.instance) #define self.kill as lamda that runs the kill frunction of parent and passes self.instance to see which enemy to remove
     
     self.dir = 0
     self.sprite = Graphics.enemyimg("zombie")
     self.sprite = (self.sprite, pygame.transform.flip(self.sprite, True, False))
     self.size = (24,48)
     self.rect = pygame.Rect((self.x, self.y), self.size)
     self.initvars()
Esempio n. 53
0
    def get_graphics(self):
        self._graphics = Graphics()

        url = os.path.join(self._task_master.get_bundle_path(), 'html-content',
                           self._uri[0])
        self._graphics.add_uri('file://' + url, height=self._height)
        self._graphics.set_zoom_level(self._zoom_level)

        target = self._task_master.read_task_data(POST_CODE)
        if target is not None and \
           self._is_valid_postal_code_entry(target=target):
            self._postal_code_entry = self._graphics.add_entry(text=target)
        else:
            self._postal_code_entry = self._graphics.add_entry()

        self._postal_code_entry.connect('key-release-event',
                                        self._postal_code_entry_cb)
        self._postal_code_entry.connect('key-press-event',
                                        self._postal_code_entry_cb)
        self._postal_code_entry.connect('activate',
                                        self._postal_code_enter_entered)

        url = os.path.join(self._task_master.get_bundle_path(), 'html-content',
                           self._uri[1])
        self._graphics.add_uri('file://' + url, height=self._height)
        self._graphics.set_zoom_level(self._zoom_level)

        target = self._task_master.read_task_data(SCHOOL_NAME)
        if target is not None:
            self._school_entry = self._graphics.add_entry(text=target)
        else:
            self._school_entry = self._graphics.add_entry()

        self._school_entry.connect('key-release-event',
                                   self._school_entry_release_cb)
        self._school_entry.connect('key-press-event',
                                   self._school_entry_press_cb)
        self._school_entry.connect('focus-in-event',
                                   self._school_entry_focus_cb)
        self._school_entry.connect('activate', self._school_enter_entered)

        self._postal_code_entry.grab_focus()

        return self._graphics, self._prompt
Esempio n. 54
0
 def __init__( self, model, texture=None, drawmode='polygon', offset=(0,0) ):
   """
     Initialize the actor
     INPUT:
           - model: unknown representation of this Actor's model, dependent on graphics system
           - texture: unknow representation of the texture to apply to this Actor's model
           - bounding_rect: rectangular projection of this actor's model onto the plane, used
                            for intersection and collision
           - gfx_sys: graphics system reference TODO: get rid of this
   """
   self._model = model #TODO assume array
   #self._boundrect = bounding_rect #TODO assume array
   self._texpath = texture #TODO assume path
   self._mode = drawmode
   self._gfxsys = Graphics()
   self._offset = offset
   if texture: 
     self._texid = self._gfxsys.texture_register( self._texpath )
   else:
     self._texid = None
   self._position = (0,0)
Esempio n. 55
0
    def __init__(self, environment, screen_size):
        self.environment = environment
        self.screen_size = screen_size
        self.pixels_per_unit = 15 # TEMP, hardcoded zoom level.
        flags = pg.HWSURFACE | pg.DOUBLEBUF
        if FULLSCREEN:
            flags |= pg.FULLSCREEN
        self.screen = pg.display.set_mode(tuple(self.screen_size), flags)

        self.screen_origin = vec.div(self.screen_size, 2)

        self.widgets = []

        if SHOW_JOYSTICK:
            for i, inp in enumerate(self.environment.inputs):
                self.widgets.append(JoystickWidget(self, inp, i))
        if SHOW_INFO:
            self.fps = 0.0
            self.widgets.append(InfoWidget(self))

        self.widgets.append(HealthWidget(self, self.environment.players))

        self.graphics = Graphics(self)
Esempio n. 56
0
    def get_graphics(self):
        target = self._get_user_name()
        url = os.path.join(self._task_master.get_bundle_path(), 'html-content',
                           self._uri)

        graphics = Graphics()
        graphics.add_uri('file://' + url, height=self._height)
        graphics.set_zoom_level(self._zoom_level)

        if target is not None and len(target) > 0:
            first, last = target.split(',')
        else:
            first = ''
            last = ''
        self._first_entry, self._last_entry = graphics.add_two_entries(
            _('First name(s):'), first, _('Last name(s):'), last)

        self._first_entry.connect('activate', self._first_enter_entered)
        self._last_entry.connect('activate', self._last_enter_entered)

        return graphics, self._prompt
"""

#required modules and functions
import sys, pygame
from initialise_game import Board
from graphics import Graphics

#create game
pygame.init()

#initialise board
board = Board()
board.initialise()

#initialise display of board
images = Graphics(board.gridsize,board.boardsize)
images.draw_initial_board(board)

#respond to input
while 1:
    for event in pygame.event.get():
        if event.type==pygame.QUIT: 
            sys.exit()
        elif event.type==pygame.KEYDOWN:
            #update robot location on board
            board.process_keypress(event.key)
            #move_active_robot(event.key)
            
            #animate motion
            images.animate(board,event.key)
            
Esempio n. 58
0
class Game(object):
    ''' Handles a game instance '''

    def __init__(self):
        ''' Initialize starting state'''
        self.graphics = Graphics()
        self.log = logging.getLogger("Game");
        logging.basicConfig(filename='main.log', level=DEBUG_LEVEL)
        self.log_handler = CursesHandler(self.graphics.windows["log"])
        self.log_handler.setLevel(DEBUG_LEVEL)
        self.log.addHandler(self.log_handler)
        self.commands = Commands(self)
        self.cursor_pos = [0,0]
        self.game_mode = GameModes.normal
        self.world = World(log_handler=self.log_handler)

        try:
            # Try to load a level from a text file and add it to the world
            # self.world.add_level(self.world.read_level('../data/testworld'))
            # self.world.get_current_level().add_entity(entity.creatures.SpaceOrk(5,5))
            self.world.add_level(
                    self.world.generate_level(
                        self.graphics.max_x, self.graphics.world_height))

            #Place player at spawn
            self.player = entity.creatures.Player(1,1)
            for ent in self.world.get_current_level().entities:
                if ent.__class__ == entity.world.PlayerSpawn:
                    self.player = entity.creatures.Player(ent.position[0],ent.position[1])

            self.world.get_current_level().add_entity(self.player)
        except Exception:
            # use better exception
            self.exit(1)

        self.log.debug("Game started")

    def run(self):
        ''' Draw the world and get input '''
        try:
            self.graphics.draw_world(self.world)
            self.graphics.show_stats(self.player)
            self.graphics.update()
            while True:
                self.parse_command(self.graphics.get_input())
                if self.game_mode == GameModes.cursor or self.game_mode == GameModes.look:
                    self.graphics.clear()
                    self.graphics.draw_world(self.world)
                    self.graphics.draw_cursor(self.cursor_pos)
                if self.game_mode == GameModes.look:
                    for ent in self.world.get_current_tile(self.cursor_pos):
                        self.log.info(ent.name)
                self.graphics.show_stats(self.player)
                self.graphics.update()
        except (Exception, KeyboardInterrupt):
            self.exit(1)

    def turn(self):
        ''' Take a turn; redraw world, run ai... '''
        try:
            for ent in self.world.get_current_level().entities:
                if hasattr(ent, "die"):
                    if ent.die():
                        continue
                if issubclass(ent.__class__, entity.base.Creature):
                    ent.turn(self.player)
            self.graphics.clear()
            self.graphics.draw_world(self.world)
        except (Exception, KeyboardInterrupt):
            self.exit(1)



    def exit(self, status):
        ''' Shutdown curses, close files, and print errors if any'''
        self.log.debug("exiting")
        self.graphics.exit()
        if sys.exc_info()[2] is not None:
            print(traceback.format_exc())
        sys.exit(status)


    def parse_command(self, command):
        ''' Executes the function associated with a command string '''
        self.log.debug(command)
        if hasattr(self.commands, command):
            try:
                self.commands.__class__.__dict__[command](self.commands)
            except (Exception, KeyboardInterrupt):
                self.exit(1)
        else:
            self.log.error("Command not found")
Esempio n. 59
0
class Shapescape:
    # Initialize the boid view
    def __init__(self):
        self.win_width = 1024
        self.win_height = 768
        pygame.init()
        self.init_window()
        
        #title screen
        title_screen = TitleScreen(self.screen)
        title_screen.do_loop()

        self.game_loop()
        
        #gameover screen
        if globalvars.failed:
            gameover_screen = GameOver(self.screen, self.scoreboard)
            gameover_screen.do_loop()
    
    # Prepares the boid view
    def init_window(self): 
        # Initialize window
        self.screen = pygame.display.set_mode((self.win_width, self.win_height))
        pygame.display.set_caption('Shapescape')
        
        pygame.mouse.set_visible(1)
        
    # Continuesly renders the boid swarm
    def game_loop(self):
        clock = pygame.time.Clock()

        #Initialize
        self.scoreboard = Scoreboard()
        self.timer = CountDown()
        self.control = Control()
        self.graphics = Graphics(self.scoreboard, self.timer);
        self.player = Player(self.graphics)
        self.world = World(self.graphics, self.player) 
        self.logic = Logic(self.player, self.world, self.graphics, self.scoreboard, self.timer, self.control)
        
        while globalvars.run_game:
            delta = clock.tick(30) # fps

            # Catch input event
            for event in pygame.event.get():
                if event.type == QUIT:
                    return
                else:
                    self.control.update(event)
                
            # Update 
            self.logic.update(delta)
            self.world.update(delta)
            self.graphics.update(self.screen, delta)
            
            # Render
            self.graphics.draw(self.screen, delta);
            self.screen.blit(self.player.speedmsg, (0, 35))
            self.screen.blit(self.player.rotmsg, (0, 55))            
              
            pygame.display.flip()        
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
from datamanager import DataManager
from graphics import Graphics
from due import DueDate


db = DataManager()
db.create_tables("base_data.sql")
data_list = db.run_query("due.sql")
new_list = DueDate.time_converter(data_list)
return_list = DueDate.make_dict(new_list)
Graphics.setup(mode="RGB", size=(1024, 1024), color=(255, 255, 255))
Graphics.make_image(return_list, "due.png")