Exemplo n.º 1
0
def draw_grid(renderer):
    x = 0
    while x < 1 + n_grid_x * grid_cell_size:
        renderer.draw_line([x, 0, x, window_height], lib.Color(255, 255, 255))
        x += grid_cell_size

    y = 0
    while y < 1 + n_grid_y * grid_cell_size:
        renderer.draw_line([0, y, window_width, y], lib.Color(255, 255, 255))
        y += grid_cell_size
Exemplo n.º 2
0
 def test_FontManager(self):
     fm = sdl2ext.FontManager(RESOURCES.get_path("tuffy.ttf"),
                              bg_color=(100, 0, 0))
     assert isinstance(fm, sdl2ext.FontManager)
     assert fm.default_font == "tuffy"
     assert fm.size == 16
     assert fm.bg_color == sdl2ext.Color(100, 0, 0, 0)
Exemplo n.º 3
0
 def test_FontManager(self):
     fm = sdl2ext.FontManager(RESOURCES.get_path("tuffy.ttf"),
                              bg_color=(100, 0, 0))
     self.assertIsInstance(fm, sdl2ext.FontManager)
     self.assertEqual(fm.default_font, "tuffy")
     self.assertEqual(fm.size, 16)
     self.assertEqual(fm.bg_color, sdl2ext.Color(100, 0, 0, 0))
Exemplo n.º 4
0
 def rendergoodies(self, g_row):
     '''draw the goodies in game'''
     self.color = sdl.Color(random.randint(0, 255), random.randint(0, 255),
                            random.randint(0, 255), 0)
     for r in g_row:
         for g in range(r.num):
             self.__rendercircle(r.co[g], r.pos, gameinfo.BONUSRADIUS)
 def test_Renderer_clear(self):
     sf = SDL_CreateRGBSurface(0, 10, 10, 32, 0xFF000000, 0x00FF0000,
                               0x0000FF00, 0x000000FF)
     renderer = sdl2ext.Renderer(sf.contents)
     self.assertIsInstance(renderer.color, sdl2ext.Color)
     self.assertEqual(renderer.color, sdl2ext.Color(0, 0, 0, 0))
     renderer.color = 0x00FF0000
     self.assertEqual(renderer.color, sdl2ext.Color(0xFF, 0, 0, 0))
     renderer.clear()
     view = sdl2ext.PixelView(sf.contents)
     self.check_areas(view, 10, 10, [[0, 0, 10, 10]], 0xFF000000, (0x0, ))
     del view
     renderer.clear(0xAABBCCDD)
     self.assertEqual(renderer.color, sdl2ext.Color(0xFF, 0, 0, 0))
     view = sdl2ext.PixelView(sf.contents)
     self.check_areas(view, 10, 10, [[0, 0, 10, 10]], 0xBBCCDDAA, (0x0, ))
     del view
     del renderer
     SDL_FreeSurface(sf)
     dogc()
Exemplo n.º 6
0
def draw(window, robot):
    events = sdl.get_events()
    for event in events:
        if event.type == sdl2.SDL_QUIT:
            running = False
            break

    surface = window.get_surface()
    sdl.fill(surface, sdl.Color(0, 0, 0))

    #Drawing the walls
    sdl.line(surface, sdl.Color(255, 255, 255),
             (-meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, 0,
              -meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, WINDOW_SIZE[1],
              meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, 0,
              meters_to_pixels(0.4) + WINDOW_SIZE[0] // 2, WINDOW_SIZE[1]))

    draw_robot(surface, robot)

    window.refresh()
Exemplo n.º 7
0
def draw_lines(surface, width, height):
    # Fill the whole surface with a black color.
    sdl2ext.fill(surface, 0)
    for x in range(15):
        # Create a set of four random points for drawing the line.
        x1, x2 = randint(0, width), randint(0, width)
        y1, y2 = randint(0, height), randint(0, height)
        # Create a random color.
        color = sdl2ext.Color(randint(0, 255), randint(0, 255),
                              randint(0, 255))
        # Draw the line with the specified color on the surface.
        # We also could create a set of points to be passed to the function
        # in the form
        #
        # line(surface, color, (x1, y1, x2, y2, x3, y3, x4, y4, ...))
        #                       ^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^
        #                         first line     second line
        sdl2ext.line(surface, color, (x1, y1, x2, y2))
Exemplo n.º 8
0
def draw_rects(surface, width, height):
    # Fill the whole surface with a black color.
    sdl2ext.fill(surface, 0)
    for k in range(15):
        # Create a set of four random points for the edges of the rectangle.
        x, y = randint(0, width), randint(0, height)
        w, h = randint(1, width // 2), randint(1, height // 2)
        # Create a random color.
        color = sdl2ext.Color(randint(0, 255), randint(0, 255),
                              randint(0, 255))
        # Draw the filled rect with the specified color on the surface.
        # We also could create a set of points to be passed to the function
        # in the form
        #
        # fill(surface, color, ((x1, y1, x2, y2), (x3, y3, x4, y4), ...))
        #                        ^^^^^^^^^^^^^^    ^^^^^^^^^^^^^^
        #                          first rect        second rect
        sdl2ext.fill(surface, color, (x, y, w, h))
Exemplo n.º 9
0
def draw_robot(surface, robot):
    pos_x = meters_to_pixels(robot.position.x) + WINDOW_SIZE[0] // 2
    pos_y = meters_to_pixels(robot.position.y) % WINDOW_SIZE[1]

    line = (pos_x, pos_y, pos_x +
            int(meters_to_pixels(0.10) * math.cos(robot.angle - math.pi / 2)),
            pos_y +
            int(meters_to_pixels(0.10) * math.sin(robot.angle - math.pi / 2)),
            pos_x, pos_y, pos_x +
            int(meters_to_pixels(0.05) * math.cos(robot.angle + math.pi / 2)),
            pos_y +
            int(meters_to_pixels(0.05) * math.sin(robot.angle + math.pi / 2)),
            pos_x, pos_y,
            pos_x + int(meters_to_pixels(0.05) * math.cos(robot.angle + 0)),
            pos_y + int(meters_to_pixels(0.05) * math.sin(robot.angle + 0)),
            pos_x, pos_y, pos_x +
            int(meters_to_pixels(0.05) * math.cos(robot.angle - math.pi)),
            pos_y +
            int(meters_to_pixels(0.05) * math.sin(robot.angle - math.pi)))

    sdl.line(surface, sdl.Color(255, 255, 100), line)
Exemplo n.º 10
0
def fill_circle(renderer, x, y, color=lib.Color(255, 255, 255)):
    gfx.filledCircleRGBA(renderer.sdlrenderer,
                         x * grid_cell_size + int(grid_cell_size / 2) + 1,
                         y * grid_cell_size + int(grid_cell_size / 2) + 1,
                         int(grid_cell_size / 4), color.r, color.g, color.b,
                         color.a)
Exemplo n.º 11
0
import os
import sys
from random import randint

try:
    from sdl2 import *
    import sdl2.ext as sdl2ext
except ImportError:
    import traceback
    traceback.print_exc()
    sys.exit(1)

WHITE = sdl2ext.Color(255, 255, 255)


class SoftwareRenderer(sdl2ext.SoftwareSpriteRenderer):
    def __init__(self, window):
        super(SoftwareRenderer, self).__init__(window)

    def render(self, components):
        sdl2ext.fill(self.surface, sdl2ext.Color(0, 0, 0))
        super(SoftwareRenderer, self).render(components)


class Player(sdl2ext.Entity):
    def __init__(self, world, sprite, posx=0, posy=0, ai=False):
        self.sprite = sprite
        self.sprite.position = posx, posy
        self.velocity = Velocity()
        self.playerdata = PlayerData()
        self.playerdata.ai = ai
Exemplo n.º 12
0
 def render(self, components):
     sdl2ext.fill(self.surface, sdl2ext.Color(0, 0, 0))
     super(SoftwareRenderer, self).render(components)
Exemplo n.º 13
0
import sys
from sdl2.events import SDL_TEXTINPUT

# Try to import SDL2. The import might fail, if the SDL2 DLL could not be
# loaded. In that case, just print the error and exit with a proper
# error code.
try:
    from sdl2 import SDL_QUIT
    import sdl2.ext as sdl2ext
except ImportError:
    import traceback
    traceback.print_exc()
    sys.exit(1)

# Define some global color constants
WHITE = sdl2ext.Color(255, 255, 255)
GREY = sdl2ext.Color(200, 200, 200)
RED = sdl2ext.Color(255, 0, 0)
GREEN = sdl2ext.Color(0, 255, 0)

# Create a resource, so we have easy access to the example images.
RESOURCES = sdl2ext.Resources(__file__, "resources")


# A callback for the Button.motion event.
def onmotion(button, event):
    print("Mouse moves over the button!")


# A callback for the Button.click event.
def onclick(button, event):
Exemplo n.º 14
0
def set_color(r, g, b):
    global current_color
    current_color = sdl.Color(r, g, b)
Exemplo n.º 15
0
def fill_tile(renderer, x, y, color=lib.Color(255,255,255)):
    blendmode = renderer.blendmode
    renderer.blendmode = sdl2.blendmode.SDL_BLENDMODE_ADD
    renderer.fill(((x*grid_cell_size+1, y*grid_cell_size+1, grid_cell_size-1, grid_cell_size-1)), color=color)
    renderer.blendmode = blendmode
Exemplo n.º 16
0
import sdl2.ext as sdl

WINDOW_WIDTH = 700
WINDOW_HEIGHT = 900
GAP = 80
SCORE_DIFF = 2000
BLOCK_IN_MOTION = 0x0
SNAKE_IN_MOTION = 0x1
GAME_OVER = 0x2
STABLE = 0x0
LEFT = 0x1
RIGHT = 0x2
INITIAL_SPEED = 2 
MIN_T_STAMP = 200
COLOR_GRID =     {   "black":sdl.Color(0, 0, 0, 0), 
                     "white":sdl.Color(255, 255, 255, 0), 
                     "red":sdl.Color(255, 0, 0, 0), 
                     "green":sdl.Color(0, 255, 0, 0),
                     "yellow":sdl.Color(255, 255, 0, 0),
                     "white-green":sdl.Color(190, 255, 190, 0),
                     "blue":sdl.Color(0, 0, 255, 0),
                     "blue-green":sdl.Color(0, 255, 255, 0),
                     "red-blue":sdl.Color(255, 0, 255, 0)
                 }
MAX_PER_ROW = 7
TOLERANCE = 20
DELAY1 = 6
DELAY2 = 9
BLOCK_GAP = 4
BLOCKSIZE = int(WINDOW_WIDTH / MAX_PER_ROW - BLOCK_GAP)
Exemplo n.º 17
0
def fill_tile(renderer, x, y, color=lib.Color(255, 255, 255)):
    renderer.fill(((x * grid_cell_size + 1, y * grid_cell_size + 1,
                    grid_cell_size - 1, grid_cell_size - 1)),
                  color=color)
Exemplo n.º 18
0
import sys

# Try to import SDL2. The import might fail, if the SDL2 DLL could not be
# loaded. In that case, just print the error and exit with a proper
# error code.
try:
    from sdl2 import SDL_QUIT, SDL_MOUSEBUTTONDOWN
    import sdl2.ext as sdl2ext
except ImportError:
    import traceback
    traceback.print_exc()
    sys.exit(1)

# Define black and white as global values, so we can access them throughout
# the code.
BLACK = sdl2ext.Color(0, 0, 0)
WHITE = sdl2ext.Color(255, 255, 255)


# This function will use a rectangular area and fill each second horizontal
# line with a white color on the passed surface.
def draw_horizontal_stripes(surface, x1, x2, y1, y2):
    # Fill the entire surface with a black color. In contrast to
    # colorpalettes.py we use a Color() value here, just to demonstrate that
    # it really works.
    sdl2ext.fill(surface, BLACK)

    # Create a 2D view that allows us to directly access each individual pixel
    # of the surface. The PixelView class is quite slow, since it uses an non-
    # optimised read-write access to each individual pixel and offset. It works
    # on every platform, though.
Exemplo n.º 19
0
import ctypes
import sdl2.ext as sdl
import sdl2

window_width = window_height = 0
renderer = None
window = None
current_color = sdl.Color(255, 255, 255)
evh = None


def init(windowname='ZOMG FORGOT TO NAME IT', width=640, height=400):
    global renderer, window, window_width, window_height
    window_width = width
    window_height = height
    sdl.init()
    window = sdl.Window(windowname, size=(window_width, window_height))
    window.show()
    renderer = sdl.Renderer(window)
    # renderer = sdl2.SDL_CreateRenderer(
    #     window,
    #     -1,
    #     sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC
    #     )
    # sdl.

def is_window_closed():
    event = sdl2.SDL_Event()
    if sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
        if event.type == sdl2.SDL_QUIT:
            return True
Exemplo n.º 20
0
def clear_screen(r=0, g=0, b=0):
    color = sdl.Color(r, g, b)
    renderer.clear(color)
Exemplo n.º 21
0
class Simulation:
    white = sdl.Color(255, 255, 255, 0)
    black = sdl.Color(0, 0, 0, 0)
    red = sdl.Color(255, 0, 0, 0)

    def __init__(self, renderer, x, y, data):
        self.data = data
        self.widy = len(self.data[0])
        self.widx = len(self.data)
        self.r = renderer
        self.__y = x * SIZE
        self.__x = y * SIZE

    def __draw_square(self, x, y):
        '''draw a sqaure at given points'''
        for i in range(y, y + SIZE):
            self.r.draw_line((x, i, x + SIZE, i))

    def __rendercircle(self, xc, yc, r=int(SIZE / 2 - SIZE / 5)):
        '''function to draw circle of radius and XY coordinates'''
        xc, yc = int(xc), int(yc)
        for x in range(r):
            y = floor(sqrt(r**2 - x**2))
            self.r.draw_line((xc + x, yc + y, xc + x, yc - y))
            self.r.draw_line((xc - x, yc + y, xc - x, yc - y))

    def __rendersprite(self):
        '''render a sprite which travels in the maze according to the path
        does not present the rendered sprite on window'''
        self.r.color = self.red
        self.__rendercircle(self.__x + SIZE / 2, self.__y + SIZE / 2)

    def build_maze(self):
        '''build maze in window
        does not present the rendered maze on window'''
        self.r.color = self.black
        for i in range(self.widx):
            for j in range(self.widy):
                if self.data[i][j] == 1:
                    self.__draw_square(j * SIZE, i * SIZE)

    # pylint: disable=no-self-argument, protected-access, not-callable
    def renderfirst(fun):
        '''takes a yielding function which performs a certain rendering of
        the sprite in a direction and returns a wrapper over it
        which takes care of things like rendering maze, handling mouse click events,
        clearing and rendering the content of window etc'''
        def fullfun(self):
            self.__clear()
            for _ in fun(self):
                i = sdl2.SDL_GetTicks()
                self.build_maze()
                self.__rendersprite()
                events = sdl.get_events()
                for e in events:
                    if e.type == sdl2.SDL_QUIT:
                        return False
                self.__present()
                self.__clear()
                i = sdl2.SDL_GetTicks() - i
                if i < (1000 // 500):
                    sdl2.SDL_Delay(1000 // 500 - i)
            return True

        return fullfun

    @renderfirst
    def move_up(self):
        '''move the sprite up'''
        for _ in range(SIZE // 2):
            self.__y -= 2
            yield

    @renderfirst
    def move_down(self):
        '''move the sprite down'''
        for _ in range(SIZE // 2):
            self.__y += 2
            yield

    @renderfirst
    def move_right(self):
        '''move the sprite right'''
        for _ in range(SIZE // 2):
            self.__x += 2
            yield

    @renderfirst
    def move_left(self):
        '''move the sprite left'''
        for _ in range(SIZE // 2):
            self.__x -= 2
            yield

    def __clear(self):
        self.r.clear(self.white)

    def __present(self):
        self.r.present()
Exemplo n.º 22
0
class Renderer:
    WINDOW_X = 1280
    WINDOW_Y = 960
    PIXCNT = WINDOW_X * WINDOW_Y
    scale = 5
    pixels = array.array('i', [c_int(0).value for i in range(PIXCNT)])
    pitch = c_int()
    frameCount = 0
    backgroundColor = sdle.Color(0, 0, 0)
    previousFrameTime = 0
    setPixels = []

    def __init__(self, entities, timer):
        self.entities = entities
        self.timer = timer
        self.window = sdle.Window("Game", size=(self.WINDOW_X, self.WINDOW_Y))
        self.renderer = sdle.Renderer(self.window,
                                      flags=sdl.SDL_RENDERER_ACCELERATED)
        self.texture = sdl.SDL_CreateTexture(self.renderer.renderer,
                                             sdl.SDL_PIXELFORMAT_ARGB8888,
                                             sdl.SDL_TEXTUREACCESS_STREAMING,
                                             self.WINDOW_X, self.WINDOW_Y)
        self.window.show()

    def blit(self, _x, _y, _sx, _sy):
        sdl.SDL_UpdateTexture(self.texture, None,
                              c_void_p(self.pixels.buffer_info()[0]),
                              c_int(self.WINDOW_X * 4))
        sdl.SDL_RenderCopy(self.renderer.renderer, self.texture, None, None)
        self.renderer.present()

    def drawRect(self, _x, _y, _sx, _sy, r, g, b, a=255):
        for y in range(_y, _y + _sy, 1):
            if y >= self.WINDOW_Y - 1 or y < 0:
                continue
            for x in range(_x, _x + _sx, 1):
                if x >= self.WINDOW_X - 1 or x < 0:
                    continue
                self.pixels[c_int(getPixel(x, y,
                                           self.WINDOW_X)).value] = c_int(
                                               getColor(r, g, b, a)).value

    def setPixel(self, x, y, color):
        #if x >=0 and y >=0 and x < self.WINDOW_X and y < self.WINDOW_Y:
        self.pixels[c_int(getPixel(x, y, self.WINDOW_X)).value] = color
        self.setPixels.append([x, y])

    def drawSprite(self, sprite, ex, ey):
        for y in range(sprite.sy):
            #if y >= self.WINDOW_Y - 1 or y < 0 or y >= sprite.sy:
            #    continue
            for x in range(sprite.sx):
                #if x >= self.WINDOW_X-1 or x < 0 or x >= sprite.sx:
                #    continue
                self.setPixel(x + ex, y + ey,
                              sprite.pixels[getPixel(x, y, sprite.sx)])

    def clearScreen(self):
        for x, y in self.setPixels:
            self.pixels[c_int(getPixel(x, y, self.WINDOW_X)).value] = 0
        self.setPixels = []

    def render(self):

        self.clearScreen()
        for k, e in self.entities.items():
            self.drawSprite(e.sprites[e.currentSprite], e.x, e.y)

        self.blit(0, 0, self.WINDOW_X, self.WINDOW_Y)

        self.frameCount = self.frameCount + 1
        if self.timer.currentTime - self.previousFrameTime >= 1.0:
            print("fps:", self.frameCount)
            self.previousFrameTime = self.timer.currentTime
            self.frameCount = 0