Пример #1
0
	def draw(self):
		py = px = 0
		if self.getActiveClip().xml.hasAttribute("px"):
			px = float(self.getActiveClip().xml.getAttribute("px"))
		if self.getActiveClip().xml.hasAttribute("py"):
			py = float(self.getActiveClip().xml.getAttribute("py"))
		drawer.draw(self.getActiveClip().grabFrame(),0,0,py,px)
Пример #2
0
def update():
    global running
    global window
    global clock

    mouseup = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouseup = True
            mouse.down = True

        if not mouseup:
            mouse.down = False

        if event.type == pygame.MOUSEMOTION:
            mouse.x = pygame.mouse.get_pos()[0]
            mouse.y = pygame.mouse.get_pos()[1]

    clock.tick(60)

    drawer.draw(assets.background_image, 0, 0)
    keyboard.update()

    board.update()

    pygame.display.flip()

    if turnmanager.won:
        os.system("say 'Closing the window in 5 seconds'")
        time.sleep(5)
        exit(0)
Пример #3
0
def main():
    pygame.init()
    displayManager.createDisplay()

    pygame.mouse.set_cursor(*pygame.cursors.broken_x)

    data = loader.loadLevel("level")

    camera = Camera(0, 0)

    while True:
        if builtins.EXIT:
            return
        for event in pygame.event.get():
            if event.type == QUIT:
                quit()
            if event.type == KEYDOWN:
                if event.key == K_BACKQUOTE:
                    exec(input())
                elif event.key == K_r:
                    data.player.gun.reload(True)
                elif event.key == K_KP_PLUS:
                    pygame.mixer.music.set_volume(
                        pygame.mixer.music.get_volume() + .05)
                elif event.key == K_KP_MINUS:
                    pygame.mixer.music.set_volume(
                        pygame.mixer.music.get_volume() - .05)
                else:
                    eventState.setState(event.key, True)
            if event.type == KEYUP:
                eventState.setState(event.key, False)
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    data.player.shoot()

        data.player.move()
        for entity in data.entities:
            dead = entity.move(data.player)
            if dead:
                data.entities.remove(entity)
        for bullet in data.myBullets:
            dead = bullet.move(data.entities)
            if dead:
                data.myBullets.remove(bullet)
        for bullet in data.enemyBullets:
            dead = bullet.move(data.entities + [data.player])
            if dead:
                data.enemyBullets.remove(bullet)
        camera.move(data.player, data.entities)

        for event in data.events:
            delete = event.run(data, camera)
            if delete:
                data.events.remove(event)

        drawer.draw(data, camera)
        displayManager.updateDisplay()
Пример #4
0
def main():

    # keys erstellen
    numKeys = (pygame.K_0, pygame.K_1, pygame.K_2, pygame.K_3, pygame.K_4, pygame.K_5, pygame.K_6, pygame.K_7, pygame.K_8, pygame.K_9, pygame.K_BACKSPACE)
    numpadKeys = (pygame.K_KP0, pygame.K_KP1, pygame.K_KP2, pygame.K_KP3, pygame.K_KP4, pygame.K_KP5, pygame.K_KP6, pygame.K_KP7, pygame.K_KP8, pygame.K_KP9, pygame.K_BACKSPACE)

    # Zeitmanagement des Spiels
    CLOCK = pygame.time.Clock()

    # Frames per Second
    FPS = 30


    # 0=MainMenu, 1=Game, 2=Modules, 3=Options, 4=Stop
    mode = 0

    # Eigentliches Spiel erstellen
    GAME = Game()

    # Hauptmenu
    MAINMENU = mainMenu()
    # ModulesMenu
    MODULESMENU = modulesMenu()
    # OptionsMenu
    OPTIONSMENU = optionsMenu(numKeys, numpadKeys)

    SCREENS = (MAINMENU, GAME, MODULESMENU, OPTIONSMENU)


    # Startbildschirm auf mainMenu setzen
    curScreen = MAINMENU

    # GameLoop
    RUNNING = True
    while RUNNING:
        events = pygame.event.get()
        dt = CLOCK.get_time() / 1000

        curScreen = SCREENS[mode]
        mode = curScreen.update(events, dt)

        if curScreen == MAINMENU and mode == 2:
            MODULESMENU.updateModules()
        elif mode == 4:
            RUNNING = False
        

        # alles malen, was diesen Tick gemalt werden muss
        drawer.draw(curScreen.getDrawStuff())

        # 1 / 30 Sekunde warten, bis wir in den nächsten Tick gehen
        CLOCK.tick(FPS)

    # Pygame und Python nach Ausbruch aus Loop schließen
    pygame.quit()
    quit()
Пример #5
0
def solve():
    global grid
    for j in range(9):
        for i in range(9):
            if grid[j][i] == 0:
                for n in range(1, 10):
                    if ispossible(j, i, n):
                        grid[j][i] = n
                        drawer.draw(600)
                        solve()
                        grid[j][i] = 0
                return
    print(np.matrix(grid))
    input("Another solution?")
Пример #6
0
def test_wrong_canvas():
    commands = iter([
        'Can 20 4',
    ])
    with pytest.raises(drawer.CanvasParsingError):
        for screen in drawer.draw(commands):
            print(screen)
Пример #7
0
def test_fill_all():
    commands = iter([
        'C 20 4',
        'B 10 3 o',
    ])
    results = [
        '''
----------------------
|                    |
|                    |
|                    |
|                    |
----------------------
''',
        '''
----------------------
|oooooooooooooooooooo|
|oooooooooooooooooooo|
|oooooooooooooooooooo|
|oooooooooooooooooooo|
----------------------
''',
    ]
    results = [x.strip('\r\n') for x in results]
    for screen, expected in zip(drawer.draw(commands), results):
        assert screen == expected
Пример #8
0
    def loop(self, data, camera):
        i = 0
        while i < len(self.text):
            for event in pygame.event.get():
                if event.type == QUIT:
                    quit()
                if event.type == KEYDOWN:
                    if event.key == K_BACKQUOTE:
                        exec(input())
                    else:
                        eventState.setState(event.key, True)
                if event.type == KEYUP:
                    eventState.setState(event.key, False)
                if event.type == MOUSEBUTTONDOWN:
                    if event.button == 1:
                        i += 3

            camera.move(data.player, data.entities, posX=self.cameraPos)

            drawer.draw(data, camera)

            displayManager.display.blit(self.messageSurf, self.messageRect)

            if i < len(self.text):
                text = loader.font.render(self.text[i], True, (0xFF, 0xFF, 0xFF))
                textRect = text.get_rect()
                textRect.left = 70 * displayManager.SCALE
                textRect.top = 70 * displayManager.SCALE
                displayManager.display.blit(text, textRect)
            if i + 1 < len(self.text):
                text = loader.font.render(self.text[i+1], True, (0xFF, 0xFF, 0xFF))
                textRect = text.get_rect()
                textRect.left = 70 * displayManager.SCALE
                textRect.top = 70 * displayManager.SCALE + text.get_height()
                displayManager.display.blit(text, textRect)
            if i + 2 < len(self.text):
                text = loader.font.render(self.text[i+2], True, (0xFF, 0xFF, 0xFF))
                textRect = text.get_rect()
                textRect.left = 70 * displayManager.SCALE
                textRect.top = 70 * displayManager.SCALE + text.get_height() * 2
                displayManager.display.blit(text, textRect)

            displayManager.updateDisplay()

        for effect in self.effects:
            effect.run()
        return True
Пример #9
0
async def draw_valentine(val_id: int) -> str:
    val = ValentineModel.get(id=val_id)
    path = f'templates/{val.theme}/{val.file}'
    val.full_path = drawer.draw(path, val.initiator_pseudo,
                                val.receiver_pseudo,
                                val.file.split('.')[-1])
    val.save()
    return val.full_path
def ForStatement():
    global Start, End, Step, x_ptr, y_ptr
    MatchToken("FOR")
    MatchToken("T")
    MatchToken("FROM")
    Start = GetExprValue(Expression())
    MatchToken("TO")
    End = GetExprValue(Expression())
    MatchToken("STEP")
    Step = GetExprValue(Expression())
    MatchToken("DRAW")
    MatchToken("L_BRACKET")
    x_ptr = GetExprValue(Expression())
    MatchToken("COMMA")
    y_ptr = GetExprValue(Expression())
    MatchToken("R_BRACKET")
    draw()
Пример #11
0
	def run(self):
		self.current_message = 'Welcome!'
		self.command = ''
		self.last_line_breaks=0
		while self.command != 'exit':
			try:
				self.last_line_breaks = draw(self.model,"Command %s was %s!"%(self.command,self.current_message),self.last_line_breaks)
				self.command = raw_input("Type a command to go: ")
				if self.command == '!!':
					self.command = self.last_command
				self.last_command = self.command
				self.run_command()
			except Exception as e:
				self.current_message = "error caught"
Пример #12
0
def main():
    if len(sys.argv) < 2: raise Exception("Please provide json file")
    argparser = argparse.ArgumentParser(description='Parse and draw from json')
    argparser.add_argument('input', help='path to json')
    argparser.add_argument('-o',
                           '--output',
                           help='Optional png file to save image')
    args = argparser.parse_args()

    # print(args.input)
    # print(args.output)

    if not path.isfile(args.input):
        raise Exception("Input file does not exist")

    with open(args.input) as input_file:
        data = json.load(input_file)

    Figures = data["Figures"]
    Screen = data["Screen"]
    Palette = data["Palette"]

    draw(Figures, Screen, Palette, args.output)
Пример #13
0
def test_draw():
    commands = iter([
        'C 20 4',
        'L 1 2 6 2',
        'L 6 3 6 4',
        'R 16 1 20 3',
        'B 10 3 o',
    ])
    results = [
        '''
----------------------
|                    |
|                    |
|                    |
|                    |
----------------------
''', '''
----------------------
|                    |
|xxxxxx              |
|                    |
|                    |
----------------------
''', '''
----------------------
|                    |
|xxxxxx              |
|     x              |
|     x              |
----------------------
''', '''
----------------------
|               xxxxx|
|xxxxxx         x   x|
|     x         xxxxx|
|     x              |
----------------------
''', '''
----------------------
|oooooooooooooooxxxxx|
|xxxxxxooooooooox   x|
|     xoooooooooxxxxx|
|     xoooooooooooooo|
----------------------
'''
    ]
    results = [x.strip('\r\n') for x in results]
    for screen, expected in zip(drawer.draw(commands), results):
        assert screen == expected
Пример #14
0
def solver(a, b, c):
    print("\nReduced form: %.2fX^2 + %.2fX^1 + %.2f = 0\n" %
          (float(a), float(b), float(c)))
    if (a == 0 and b == 0):
        if (c == 0):
            print("Well done, you learn that 0 = 0!")
        else:
            print("Invalid equation")
    elif a == 0:
        print("Polynomial degree: 1")
        sol = (-c) / b
        print("x = " + str(sol))
        ans = input('Do you want a graph, yes or no? : ')
        if (ans == "yes"):
            draw(a, b, c)
    else:
        print("Polynomial degree: 2")
        delta = b * b - 4 * a * c
        print("Delta: " + str(delta))
        if delta > 0:
            num = -b - math.sqrt(delta)
            den = 2 * a
            print("\nx1 = " + str(num / den))
            num = -b + math.sqrt(delta)
            print("x2 = " + str(num / den))
            ans = input('Do you want a graph, yes or no? : ')
            if (ans == "yes"):
                draw(a, b, c)
        elif delta == 0:
            x1 = -b / (2 * a)
            print("\nx = " + str(x1))
            ans = input('Do you want a graph, yes or no? : ')
            if (ans == "yes"):
                draw(a, b, c)
        else:
            print('\nComplex solutions:')
            first = -b / (2 * a)
            second = math.sqrt(-delta) / (2 * a)
            print("x1 = " + str(first) + " + i * " + str(second))
            print("x2 = " + str(first) + " - i * " + str(second))
Пример #15
0
            if newy < my and newy >= 0 and newx < mx and newx >= 0:
                if visited[newy][newx] == 0:
                    avail.append(i)
        next_pos = None
        if len(avail) == 0:  # никуда не можем пойти, значит это тупик
            next_pos = stack.pop()  # идем назад
        else:
            dest = avail[randrange(len(avail))]
            next_pos = (x + dx[dest], y + dy[dest])

            index = count_index(next_pos[0], next_pos[1])
            prev_index = count_index(x, y)
            maze[index][prev_index] = 1
            maze[prev_index][index] = 1
            stack.append(next_pos)
        visit(next_pos[0], next_pos[1])


startx = randrange(mx)
starty = randrange(my)
stack.append((startx, starty))
visit(startx, starty)

for row in maze:
    for cell in row:
        f.write(str(cell))
    f.write('\n')

drawer = drawer.Drawer(h, mx, my)
drawer.draw(maze)
Пример #16
0
def test_wrong_rectangle():
    commands = iter(['C 20 4', 'Re 1 2 6 2'])
    with pytest.raises(drawer.ParsingError):
        for screen in drawer.draw(commands):
            print(screen)
Пример #17
0
def test_wrong_line_type():
    commands = iter(['C 20 4', 'L 1 2 6 4'])
    with pytest.raises(drawer.WrongLineTypeError):
        for screen in drawer.draw(commands):
            print(screen)
Пример #18
0
def test_outside_canvas():
    commands = iter(['C 20 4', 'R 1 200 6 2'])
    with pytest.raises(drawer.OutsideCanvasError):
        for screen in drawer.draw(commands):
            print(screen)
Пример #19
0
            best_fit = cw.fitness()
            best_cw = copy.deepcopy(cw)
            print("New best:", best_fit)
        del cw
        iters += 1
    if best_cw == None:
        print("Error: could not create a single crossword puzzle")
        exit(-1)
    print("Used words:", best_cw.get_used_words())
    print("Grid:")
    print(best_cw.get_grid())
    print("Fitness:", best_fit)

    print("TOTAL WORDS:", len(words))

    #draw(best_cw.get_grid(), best_cw.used_words, best_cw.solution_positions)

    best_cw.store_grid("intermediate_store.txt")

if EDIT_OLD:
    cw = Crossword(SIZE, SIZE)
    cw.load_grid("intermediate_store.txt")

    cw.hide_secret(loesung)

    print(cw.fitness())

    draw(cw.get_grid(), cw.used_words, cw.solution_positions, DRAW_LINES)

else:
    print("Doing nothing...")
Пример #20
0
def test_wrong_fill():
    commands = iter(['C 20 4', 'B 1s 2 o'])
    with pytest.raises(drawer.ParsingError):
        for screen in drawer.draw(commands):
            print(screen)
Пример #21
0
from model import Model
from main_loop import Main_Loop

from drawer import draw

if __name__ == '__main__':
	if len(sys.argv) == 1:
		print "Client: Starting!"
		model = Model(uid=1)
		main = Main_Loop(model)
		main.run()
		print "Client: Exiting!"
	else:
		if sys.argv[1] == 'close':
			print request_exit(0)
			print "Client: Sent shutdown to server!"
		elif sys.argv[1] == 'check':
			try:
				print request_test(0)
				print "Server is UP!"
			except socket.error:
				print "Server is DOWN!"
		elif sys.argv[1] == '-c':
			with open(os.path.join(os.environ['postpromptroot'],'var','log','test.log'),'a') as f:
				main = Main_Loop(Model(uid=1))
				for command in sys.argv[2].split(' '):
					main.run_command(command)
					f.write('%s\n'%main.resp)
					f.write('%s\n'%draw(main.model,main.current_message))
					print draw(main.model,main.current_message)
Пример #22
0
            loss.backward()
            optimizer.step()
            print("[Epoch %d/%d] [Batch %d/%d] [loss: %f]" %
                  (epoch + 1, epochs, i + 1, len(dataloader), loss.item()))

    return net


def cutSignal(signal, start):
    signal = signal[start - 30:start + 31]
    return signal


if __name__ == "__main__":
    dataloader = data_loader.QrsDataset(istrain=True)
    testSignal = dataloader.getSignal()
    dataloader = DataLoader(dataloader, batch_size=4)

    net = tryToTrain()
    result = []

    for i in range(30, 5000 - 31):
        signal = cutSignal(testSignal, i)
        signal = torch.from_numpy(signal)
        tempResult = net(signal)
        tempResult = tempResult.detach().numpy()
        result.append(tempResult[0])

    drawer.draw(testSignal)
    drawer.draw(result)