コード例 #1
0
ファイル: main.py プロジェクト: LuisSuall/Mecanica_Celeste
	def draw(self):
		t = self.time()

		for i, planet in enumerate(self.planets):

			self.Labels[i*5].grid_remove()
			self.Labels[i*5+1].grid_remove()
			self.Labels[i*5+2].grid_remove()
			self.Labels[i*5+3].grid_remove()
			self.Labels[i*5+4].grid_remove()

			if(self.active_planets[i].get()):
				self.Labels[i*5] = tk.Label(self, text = "U: "+ str(planet.u(t)))
				self.Labels[i*5].grid(column = 2, row = i*5)
				self.Labels[i*5+1] = tk.Label(self, text = "C: "+ str(planet.angular_momentum(t)))
				self.Labels[i*5+1].grid(column = 2, row = i*5+1)
				self.Labels[i*5+2] = tk.Label(self, text = "H: "+ str(planet.energy(t)))
				self.Labels[i*5+2].grid(column = 2, row = i*5+2)
				self.Labels[i*5+3] = tk.Label(self, text = "X: "+ str(planet.position(t)))
				self.Labels[i*5+3].grid(column = 2, row = i*5+3)
				self.Labels[i*5+4] = tk.Label(self, text = " ")
				self.Labels[i*5+4].grid(column = 2, row = i*5+4)

		graphics.draw(self.planets,self.active_planets, t)

		self.after(500,self.draw)
コード例 #2
0
ファイル: main.py プロジェクト: LuisSuall/Mecanica_Celeste
    def draw(self):
        t = self.time()

        for i, planet in enumerate(self.planets):

            self.Labels[i * 5].grid_remove()
            self.Labels[i * 5 + 1].grid_remove()
            self.Labels[i * 5 + 2].grid_remove()
            self.Labels[i * 5 + 3].grid_remove()
            self.Labels[i * 5 + 4].grid_remove()

            if (self.active_planets[i].get()):
                self.Labels[i * 5] = tk.Label(self,
                                              text="U: " + str(planet.u(t)))
                self.Labels[i * 5].grid(column=2, row=i * 5)
                self.Labels[i * 5 + 1] = tk.Label(
                    self, text="C: " + str(planet.angular_momentum(t)))
                self.Labels[i * 5 + 1].grid(column=2, row=i * 5 + 1)
                self.Labels[i * 5 + 2] = tk.Label(self,
                                                  text="H: " +
                                                  str(planet.energy(t)))
                self.Labels[i * 5 + 2].grid(column=2, row=i * 5 + 2)
                self.Labels[i * 5 + 3] = tk.Label(self,
                                                  text="X: " +
                                                  str(planet.position(t)))
                self.Labels[i * 5 + 3].grid(column=2, row=i * 5 + 3)
                self.Labels[i * 5 + 4] = tk.Label(self, text=" ")
                self.Labels[i * 5 + 4].grid(column=2, row=i * 5 + 4)

        graphics.draw(self.planets, self.active_planets, t)

        self.after(500, self.draw)
コード例 #3
0
ファイル: visualizer.py プロジェクト: ClaytonKnittel/Qubits
 def graphics_update():
     screen.fill(g.CYAN)
     e.event_log.act(pygame.mouse.get_pos())
     qubit.draw(e.camera, g.WHITE, g.BLUE, g.RED, g.FOREST_GREEN, g.CYAN)
     g.draw(pygame.draw, screen)
     pygame.display.flip()
     gr.draw()
コード例 #4
0
ファイル: main.py プロジェクト: JackWetherell/pyboids
def main(resolution, fps):
    # initialse pygame
    pygame.init()

    # set up frame rate
    clock = pygame.time.Clock()
    dt = 1.0 / float(fps)
    timestep = 0
    time = 0.0

    # create the buffer and display
    buffer = pygame.display.set_mode(resolution)
    pygame.display.set_caption('Boids')
    pygame.display.set_icon(pygame.image.load('data/boid.png'))

    # enable smooth controls
    pygame.key.set_repeat(10, 10)

    # initialse the game
    universe = engine.Universe(resolution)

    # main game loop
    while universe.state is not engine.States.QUIT:
        universe.check_input()
        universe.update(resolution, fps, dt, timestep, time)
        graphics.draw(universe, buffer)
        pygame.display.flip()
        clock.tick(fps)
        timestep += 1
        time += dt
コード例 #5
0
ファイル: menu.py プロジェクト: cosmologicon/unifac
def draw(mpos):
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
	glEnable(GL_DEPTH_TEST)
#	glEnable(GL_CULL_FACE)

	camera.look()

	glDisable(GL_LIGHTING)
	graphics.draw(graphics.stars, min(settings.sx * settings.sy / 2000000., 1))
	glEnable(GL_LIGHTING)

	if hud.mode == "level" and hud.labels["leveltitle"]:
		lighting.setmoonlight(*info.moonlights[settings.level])
		lighting.moon()
		glPushMatrix()
		r = info.Rs[settings.level]
		glScale(r, r, r)
		graphics.draw(graphics.moon)
		glPopMatrix()

	text.setup()

	hud.draw()

#	text.write(settings.gamename, "Homenaje", hud.f(4), (200, 200, 200), (settings.sx/2, settings.sy/2), (0, 0, 0))

	if alpha < 1:
		graphics.fill(0, 0, 0, 1-alpha)

	glDisable(GL_TEXTURE_2D)
コード例 #6
0
def start():
    global boidflock

    seed(time.time())

    graphics.init(width=640, height=480)

    graphics.bg_colour(graphics.BLACK)

    #splatter a flock in the space randomly
    def generate_boid():
        x = randrange(0, 640) #random left-right
        y = randrange(0, 480) #random up-down

        position = pygame.math.Vector2(x, y)
        #splat a boid, add to flock list
        velocity = pygame.math.Vector2((random() * 2) - 1, (random() * 2) - 1)
        velocity.scale_to_length(50)

        boidflock.add(boids.Boid(position, velocity))

    for _ in range(50):
        generate_boid()

    for b in boidflock:
        b.image = pygame.Surface((1, 1))
        b.image.fill(graphics.WHITE)

    boidflock.draw(graphics.screen)

    graphics.draw()
コード例 #7
0
def update(dt):
    boidflock.update(dt, 0, 640, 0, 480)

    graphics.bg_colour(graphics.BLACK)

    boidflock.draw(graphics.screen)

    graphics.draw()
コード例 #8
0
ファイル: engine.py プロジェクト: Nip404/7-Segment-Display
    def update(self, num, update_surf=True):
        if not isinstance(num, int):
            raise ValueError("Input to display must be type <int>.")

        graphics.draw(str(num))

        if update_surf:
            pygame.display.flip()
コード例 #9
0
ファイル: test.py プロジェクト: marcomorucci/alliance-game
def test_sh_player():

    weights = {
        "unit_weight": 1.242,
        "node_weight": -0.4971,
        "occ_weight": 0,
        "occ_new_weight": 0.05953,
        "n_enemies_weight": 0.2306,
        "enemy_occ_nodes_weight": -1.126,
        "enemy_unit_weight": -0.2431,
        "empty_node_weight": -0.7042,
        "attacker_weight": -0.3131,
        "defender_weight": 0.06549,
        "occ_attacker_weight": -0.2173,
        "occ_defender_weight": 0.4239,
        "enemy_occ_attacker_weight": 0.3953,
        "enemy_occ_defender_weight": -0.02868,
    }

    nodes = [
        GameNode(0, [], [1, 2]),
        GameNode(1, [], [0, 2]),
        GameNode(2, [], [0, 1, 3]),
        GameNode(3, [], [2, 4, 5]),
        GameNode(4, [], [3, 5]),
        GameNode(5, [], [3, 4]),
    ]

    players = [
        ShortHorizonPlayer(0, [Unit(0, nodes[0])], [nodes[0]], nodes[0], **weights),
        ShortHorizonPlayer(1, [Unit(1, nodes[1])], [nodes[1]], nodes[1], **weights),
        ShortHorizonPlayer(2, [Unit(2, nodes[4])], [nodes[4]], nodes[4], **weights),
        ShortHorizonPlayer(3, [Unit(3, nodes[5])], [nodes[5]], nodes[5], **weights),
    ]

    nodes[0].add_unit(players[0].units[0])
    nodes[1].add_unit(players[1].units[0])
    nodes[4].add_unit(players[2].units[0])
    nodes[5].add_unit(players[3].units[0])

    graph = GameGraph(nodes)

    game = Game(players, graph)

    game.update_state([], False)

    def next_round(event):
        win = game.play_round()
        if win is None:
            graphics.draw(f, w, l, game.state)
        else:
            graphics.draw_winner(w, win)

    f, w, l = graphics.setup(game.state, next_round)

    graphics.draw(f, w, l, game.state)
    graphics.show()
コード例 #10
0
def test_human_player():

    nodes = [
        GameNode(0, [], [1, 2]),
        GameNode(1, [], [0, 2]),
        GameNode(2, [], [0, 1, 3]),
        GameNode(3, [], [2, 4, 5]),
        GameNode(4, [], [3, 5]),
        GameNode(5, [], [3, 4])
    ]

    players = [
        HumanPlayer(0, [HumanInteractionUnit(0, nodes[0])], [nodes[0]],
                    nodes[0]),
        HumanPlayer(1, [HumanInteractionUnit(1, nodes[1])], [nodes[1]],
                    nodes[1]),
        HumanPlayer(2, [HumanInteractionUnit(2, nodes[4])], [nodes[4]],
                    nodes[4]),
        HumanPlayer(3, [HumanInteractionUnit(3, nodes[5])], [nodes[5]],
                    nodes[5])
    ]

    nodes[0].add_unit(players[0].units[0])
    nodes[1].add_unit(players[1].units[0])
    nodes[4].add_unit(players[2].units[0])
    nodes[5].add_unit(players[3].units[0])

    graph = GameGraph(nodes)

    game = Game(players, graph)

    game.update_state([], False)

    def next_round(event):
        win = game.play_round()
        if win is None:
            graphics.draw(f, w, l, game.state)
        else:
            graphics.draw_winner(w, win)

    f, w, l = graphics.setup(game.state, next_round)

    for p in players:
        p.canvas = w

    graphics.draw(f, w, l, game.state)
    graphics.show()
コード例 #11
0
ファイル: main.py プロジェクト: mattjegan/IHSS
def main():
    running = True

    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

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

        # Calculate stats
        statsArr = processing.organiseXL2Array('scores.xls')

        # Display graphics
        graphics.draw(screen, statsArr)

        pygame.display.update()
コード例 #12
0
ファイル: main.py プロジェクト: mattjegan/IHSS
def main():
    running = True

    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

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

        # Calculate stats
        statsArr = processing.organiseXL2Array('scores.xls')

        # Display graphics
        graphics.draw(screen, statsArr)

        pygame.display.update()
コード例 #13
0
ファイル: test.py プロジェクト: marcomorucci/alliance-game
def test_human_player():

    nodes = [
        GameNode(0, [], [1, 2]),
        GameNode(1, [], [0, 2]),
        GameNode(2, [], [0, 1, 3]),
        GameNode(3, [], [2, 4, 5]),
        GameNode(4, [], [3, 5]),
        GameNode(5, [], [3, 4]),
    ]

    players = [
        HumanPlayer(0, [HumanInteractionUnit(0, nodes[0])], [nodes[0]], nodes[0]),
        HumanPlayer(1, [HumanInteractionUnit(1, nodes[1])], [nodes[1]], nodes[1]),
        HumanPlayer(2, [HumanInteractionUnit(2, nodes[4])], [nodes[4]], nodes[4]),
        HumanPlayer(3, [HumanInteractionUnit(3, nodes[5])], [nodes[5]], nodes[5]),
    ]

    nodes[0].add_unit(players[0].units[0])
    nodes[1].add_unit(players[1].units[0])
    nodes[4].add_unit(players[2].units[0])
    nodes[5].add_unit(players[3].units[0])

    graph = GameGraph(nodes)

    game = Game(players, graph)

    game.update_state([], False)

    def next_round(event):
        win = game.play_round()
        if win is None:
            graphics.draw(f, w, l, game.state)
        else:
            graphics.draw_winner(w, win)

    f, w, l = graphics.setup(game.state, next_round)

    for p in players:
        p.canvas = w

    graphics.draw(f, w, l, game.state)
    graphics.show()
コード例 #14
0
ファイル: dialogue.py プロジェクト: cosmologicon/unifac
def draw(mpos):
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
	glEnable(GL_DEPTH_TEST)

	camera.look()

	glDisable(GL_LIGHTING)
	graphics.draw(graphics.stars, min(settings.sx * settings.sy / 2000000., 1))
	glEnable(GL_LIGHTING)

	text.setup()

	hud.dialoguebox.draw()

	if alpha < 1:
		glPushMatrix()
		graphics.fill(0, 0, 0, 1-alpha)
		glPopMatrix()
		glEnable(GL_TEXTURE_2D)

	glDisable(GL_TEXTURE_2D)
コード例 #15
0
    def tick(self):

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return True

        if pygame.mouse.get_pressed()[0]:

            mx, my = pygame.mouse.get_pos()
            self.sun.x = mx
            self.sun.y = my
            self.sun.b = (self.size[1] - my) * 4  #This prolly needs tweaking

            graphics.firstDraw(self)
            pygame.display.update()

        elif pygame.mouse.get_pressed()[2]:

            self.sun.x, self.sun.y = pygame.mouse.get_pos()

            graphics.draw(self)
            pygame.display.update()
コード例 #16
0
    """
    lines = [line.strip('\n') for line in file]
    for i in range(len(lines)):
        for j in range(len(lines[i])):
            if lines[i][j] == '.':
                nodes.append(Node(j, i, 1))
            elif lines[i][j] == 'A':
                start = Node(j, i, 1)
                nodes.append(start)
            elif lines[i][j] == 'B':
                target = Node(j, i, 1)
                nodes.append(target)
            elif lines[i][j] == '#':
                nodes.append(Node(j, i, 1, True))

    target.target = True
    start.start = True

    path = []

    if astar(start, target, nodes, open_nodes, closed_nodes):
        node = target
        while node != start:
            path.append(node)
            node = node.parent
        path.append(start)
    else:
        print("No path from start to target found :(((")

    draw(nodes, path, open_nodes, closed_nodes, lines,
         './img/part1/' + board[9:-4] + '.png')
コード例 #17
0
                    nodes.append(Node(j, i, 1, description='Road'))
                if lines[i][j] == '.':
                    nodes.append(Node(j, i, 1))
                if lines[i][j] == '#':
                    nodes.append(Node(j, i, 1, obstacle=True))
                elif lines[i][j] == 'A':
                    start = Node(j, i, 1)
                    nodes.append(start)
                elif lines[i][j] == 'B':
                    target = Node(j, i, 1)
                    nodes.append(target)

        target.target = True
        start.start = True
        
        path = []
        

        if algorithm == 'astar' and astar(start, target, nodes, open_nodes, closed_nodes) or \
           algorithm == 'dijkstra' and dijkstra(start, target, nodes, open_nodes, closed_nodes) or \
           algorithm == 'bfs' and bfs(start, target, nodes, open_nodes, closed_nodes):
            node = target
            while node != start:
                path.append(node)
                node = node.parent
            path.append(start)
        else:
            print("No path from start to target found :(((")

        draw(nodes, path, open_nodes, closed_nodes, lines, './img/part3/' + board[9:-4] + algorithm + '.png')
コード例 #18
0
ファイル: game.py プロジェクト: CrankyKong/PhysicsGame
screen = pygame.display.set_mode((400, 400), pygame.DOUBLEBUF | pygame.HWSURFACE)

current_map = map.sample_map()
graphics.set_map(current_map)

slime = objects.Slime()
slime.x = 128
slime.y = 128
# minotaur.move_to(20, 100)
# minotaur.move_to(250, 100)
# minotaur.move_to(100, 150)
events.register(pygame.KEYDOWN, slime.key_handler)
events.register(pygame.KEYUP, slime.key_handler)
graphics.add_sprite(slime)

clock = pygame.time.Clock()
time_ms = 0
clock.tick()
while run:
    time_ms += clock.tick(50)

    while time_ms > 20:
        slime.update()
        time_ms -= 20

    graphics.draw(screen)
    events.handle()

pygame.quit()
コード例 #19
0
pygame.init()

stageData = gameLogic.getStageData()
inputData = {"grab": False, "run": True}

run = True
clock = pygame.time.Clock()

#-------- MAIN LOOP ----------
while run:
    #EVENTS
    inputData = inputHandling.handleInput(inputData)
    run = inputData["run"]

    if len(stageData["candy"]) <= 0:
        run = False
    elif stageData["mainCh"].pos[0] < 0 or stageData["mainCh"].pos[0] > size[
            0] or stageData["mainCh"].pos[1] > size[1]:
        run = False
    #GAMELOGIC
    gameLogic.updateStageData(inputData, stageData)
    #DRAWING CODE
    screen.fill((0, 0, 0))
    graphics.draw(screen, stageData)
    pygame.display.flip()

    #set update speed 60 frame/s
    clock.tick(60)

pygame.quit()
コード例 #20
0
    if use_example:
        # [a, c, b, d, e]
        f_k = [2.0, 2.0, -2.0, -1.0, -4.0]
    else:
        # [a, c, b, d, e]
        f_k = [4.0, 1.0, 2.0, -2.0, -3.0]

    eps: float = 0.1
    x, y = sp.symbols('x y')
    f: sp.Add = f_k[0]*x**2 + f_k[1]*y**2 + f_k[2]*x*y + f_k[3]*x + f_k[4]*y

    rules: List[sp.core.relational.Relational]
    if use_example:
        rules = [
            -x <= 0,
            -y <= 0,
            x + y <= 2,
            x + 5*y <= 5,
        ]
    else:
        rules = [
            x + 4 * y <= 16,
            11 * x - 4 * y <= 44,
            -x - y <= -4,
        ]

    points: List[float] = cg.calculate(f, rules, eps=eps)
    print(f'Found minimum after {Fore.GREEN}{len(points) - 1}{Fore.RESET} iterations!')
    print(f'Last point is {Fore.MAGENTA}{points[-1]}{Fore.RESET}')
    gr.draw(f_k, rules, points)
コード例 #21
0
ファイル: main.py プロジェクト: vincentyliu2001/Tetris
def game():
    clock = pygame.time.Clock()
    # Screen dimensions
    SCREEN_WIDTH = 700
    SCREEN_HEIGHT = 500
    # Create screen obj
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    piece_bag = []
    piece_bag2 = []
    hold_piece = None
    initialize_bag(piece_bag, piece_bag2)
    can_hold = True
    board = Board()

    active = extract_piece(piece_bag, piece_bag2)
    # Run until the user asks to quit
    running = True
    ticks = 0
    auto_drop_event = pygame.USEREVENT + 1  # Even to auto drop piece once every second
    check_new_event = pygame.USEREVENT + 2  # Checks to see if the piece hasn't changed height and get's new piece
    auto_drop_freq = 1000
    check_new_freq = 500
    pygame.time.set_timer(auto_drop_event, auto_drop_freq)  # set the event
    pygame.time.set_timer(check_new_event, check_new_freq)  # set the event
    das = 0.070  # Delayed auto shift see: https://harddrop.com/wiki/DAS
    # Note ARR in this iteration of the game is always 0 see: https://harddrop.com/wiki/DAS
    # below are variables to handle DAS
    right_timer = None
    left_timer = None
    left_pressed = False
    right_pressed = False
    left_first = False
    right_first = False
    curr_row = 0  # curr_row, used by check_new_event
    score = 0  # the user's score
    print_message_1 = ""  # print's singles, doubles, t-spins etc. if the user performs them
    print_message_2 = ""  # print's combo 1, combo 2 etc if the user performs them
    game_over = False  # checker to see if the game is over
    need_next = False  # checker to see if we need another piece
    ticker = 0  # ticks every time the game loop runs
    while running:
        changed = False  # nothing has changed from the last game loop
        if game_over:
            end_game(board)  # turn all active blocks gray
            # draw this newly grayed board
            graphics.draw(screen, active, board, hold_piece, piece_bag, score,
                          print_message_1, print_message_2)
        # soft_drop counting for scoring purposes
        if active.soft_drop(board):
            changed = True
            board.soft_drop += 1
        for event in pygame.event.get():
            if not game_over:
                # auto drops piece every second
                if event.type == auto_drop_event:
                    changed = active.move(0, -1, board)
                    board.soft_drop += 1
                # if the piece has not moved down for the event period, then get the next piece
                if event.type == check_new_event:
                    if active.get_row() == curr_row and not active.can_move(
                            0, -1, board):
                        need_next = True
                    # this is to prevent stalling, if a piece hasn't been plaed in 50 seconds, the next one auto appears
                    elif ticker > 100:
                        need_next = True
                        active.quick_move(0, -1, board)
                    else:
                        ticker += 1
                        curr_row = active.get_row()
            # Did the user click the window close button?
            if event.type == pygame.QUIT:
                running = False
            # If not then handle everything else
            else:
                if event.type == pygame.KEYDOWN:
                    # F4 is the reset button
                    if event.key == pygame.K_F4:
                        # essentially resetting every relevant var, see above for var descriptions
                        board = Board()
                        hold_piece = None
                        score = 0
                        right_timer = None
                        left_timer = None
                        left_pressed = False
                        right_pressed = False
                        left_first = False
                        right_first = False
                        board.soft_drop = 0
                        print_message_1 = ""
                        print_message_2 = ""
                        can_hold = True
                        initialize_bag(piece_bag, piece_bag2)
                        active = extract_piece(piece_bag, piece_bag2)
                        game_over = False
                        graphics.draw(screen, active, board, hold_piece,
                                      piece_bag, score, print_message_1,
                                      print_message_2)
                    # we don't want our user to keep playing if they've already lost
                    if not game_over:
                        # holding handling
                        if event.key == pygame.K_LSHIFT:
                            changed = True
                            if can_hold:
                                temp_piece = hold_piece
                                if isinstance(active, oPiece):
                                    hold_piece = type(active)(5, 22)
                                else:
                                    hold_piece = type(active)(4, 22)
                                active = temp_piece
                                if active is None:
                                    active = extract_piece(
                                        piece_bag, piece_bag2)
                                can_hold = False
                            board.soft_drop = 0
                        # handling pressing the right key, this is handled in the main
                        # because key presses should transfer over to next pieces
                        # ie if I hold the right key, and place a key, continue holding right, the next key should
                        # almost instantly move to the right as well
                        if event.key == pygame.K_RIGHT:
                            right_timer = time.time()
                            right_first = True
                            left_first = False
                            right_pressed = True
                        # handling pressing the left key
                        # handled in main for same reasons above, not unique to each piece
                        if event.key == pygame.K_LEFT:
                            left_timer = time.time()
                            left_first = True
                            right_first = False
                            left_pressed = True
            # reset variables if the left or right arrow key is released
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    right_pressed = False
                    right_first = False
                if event.key == pygame.K_LEFT:
                    left_pressed = False
                    left_first = False
            # update piece based on event
            if game_over:
                continue
            # returns if anything happened, if not nothing changed
            booleans = active.update(event, board)
            if booleans[0]:
                changed = booleans[0]
            if not need_next:
                need_next = booleans[1]
            # if we need another piece, set the piece into the game board
            # then get the next piece from the piece_bag
            if need_next:
                can_hold = True
                for block in active.get_blocks():
                    board.add(block.get_col(), block.get_row(),
                              block.get_color())
                results = board.clear_line(active, isinstance(active, tPiece),
                                           isinstance(active, iPiece))
                # updating print messages and score
                score += results[0]
                print_message_1 = results[1]
                print_message_2 = results[2]
                game_over = results[3]
                active = extract_piece(piece_bag, piece_bag2)
                curr_row = 0
                need_next = False
                ticker = 0
        # DAS handling
        temp_time = time.time()
        if left_pressed and (not right_pressed):
            if (temp_time - left_timer) > das:
                auto_repeat(active, board, False)
                changed = True
        elif right_pressed and (not left_pressed):
            if (temp_time - right_timer) > das:
                auto_repeat(active, board, True)
                changed = True
        elif right_pressed and left_pressed:
            if left_first:
                if (temp_time - left_timer) > das:
                    auto_repeat(active, board, False)
                    changed = True
            elif right_first:
                if (temp_time - right_timer) > das:
                    auto_repeat(active, board, True)
                    changed = True
        # Draw everything if something changed or if first frame
        pygame.display.flip()
        if changed or ticks == 0:
            graphics.draw(screen, active, board, hold_piece, piece_bag, score,
                          print_message_1, print_message_2)
        # Flip the display
        test = AI_helper.get__hrt_advanced(board)

        # Limit 1000 fps note rendering only occurs when something changes so this is not cpu heavy at all
        # for most ticks, nothing even happens since no events are even pressed, very cpu light
        # for accurate DAS and ARR recommended tick at least 1000
        clock.tick(300)
        # print fps
        if ticks == 300:
            print("fps: " + str(clock.get_fps()))
            ticks = 0
        ticks += 1
    # Done! Time to quit.
    pygame.quit()
コード例 #22
0
# env.print_rewards()
height = 30
width = 40

epochs = [256]
random_start = [True]
repetitions = 1

components = {}

for epoch, rs in zip(epochs, random_start):
    components[f'epochs:{epoch}-randstart:{rs}'] = []
    exploit = 0.05
    for _ in tqdm(
            range(repetitions)
    ):  # execute the algorithm multiple times just for experimenting it
        env = Environment(height, width)
        agent = Agent(env=env, discount=0.9)
        agent.learn(epochs=epoch, exploit=exploit, random_start=rs)
        policy = agent.policy()
        components[f'epochs:{epoch}-randstart:{rs}'].append(
            connected_components(policy))

for i in components:
    comp = components[i]
    print(f'{i}: {comp}')
    print(f'average:{sum(comp)/len(comp)}\n')

# draw last policy
draw(env, policy)
コード例 #23
0
def test_sh_player():

    weights = {
        "unit_weight": 1.242,
        "node_weight": -0.4971,
        "occ_weight": 0,
        "occ_new_weight": 0.05953,
        "n_enemies_weight": 0.2306,
        "enemy_occ_nodes_weight": -1.126,
        "enemy_unit_weight": -0.2431,
        "empty_node_weight": -0.7042,
        "attacker_weight": -0.3131,
        "defender_weight": 0.06549,
        "occ_attacker_weight": -0.2173,
        "occ_defender_weight": 0.4239,
        "enemy_occ_attacker_weight": 0.3953,
        "enemy_occ_defender_weight": -0.02868
    }

    nodes = [
        GameNode(0, [], [1, 2]),
        GameNode(1, [], [0, 2]),
        GameNode(2, [], [0, 1, 3]),
        GameNode(3, [], [2, 4, 5]),
        GameNode(4, [], [3, 5]),
        GameNode(5, [], [3, 4])
    ]

    players = [
        ShortHorizonPlayer(0, [Unit(0, nodes[0])], [nodes[0]], nodes[0],
                           **weights),
        ShortHorizonPlayer(1, [Unit(1, nodes[1])], [nodes[1]], nodes[1],
                           **weights),
        ShortHorizonPlayer(2, [Unit(2, nodes[4])], [nodes[4]], nodes[4],
                           **weights),
        ShortHorizonPlayer(3, [Unit(3, nodes[5])], [nodes[5]], nodes[5],
                           **weights)
    ]

    nodes[0].add_unit(players[0].units[0])
    nodes[1].add_unit(players[1].units[0])
    nodes[4].add_unit(players[2].units[0])
    nodes[5].add_unit(players[3].units[0])

    graph = GameGraph(nodes)

    game = Game(players, graph)

    game.update_state([], False)

    def next_round(event):
        win = game.play_round()
        if win is None:
            graphics.draw(f, w, l, game.state)
        else:
            graphics.draw_winner(w, win)

    f, w, l = graphics.setup(game.state, next_round)

    graphics.draw(f, w, l, game.state)
    graphics.show()
コード例 #24
0
ファイル: neat-AI.py プロジェクト: vincentyliu2001/Tetris
def eval_genome(genomes, config):
    pygame.init()
    ticks = 0
    running = True
    # Screen dimensions
    SCREEN_WIDTH = 700
    SCREEN_HEIGHT = 500
    # Create screen obj
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    # instead of individual variables, everything is a list as the AI runs multiple games at once to train
    # since training off one game at a time is too slow
    piece_bags = []
    piece_bags2 = []
    hold_pieces = []
    boards = []
    actives = []
    nets = []
    ge = []
    tickers = []
    changes = []
    piece_count = []
    # initializer for all the arrays
    for genome_id, genome in genomes:
        genome.fitness = 0
        net = neat.nn.FeedForwardNetwork.create(genome, config)
        nets.append(net)
        piece_bag = []
        piece_bag2 = []
        initialize_bag(piece_bag, piece_bag2)
        piece_bags.append(piece_bag)
        piece_bags2.append(piece_bag2)
        boards.append(Board())
        actives.append(extract_piece(piece_bag, piece_bag2))
        ge.append(genome)
        tickers.append(0)
        piece_count.append(1)
        changes.append(False)
        hold_pieces.append(None)
    # game loop very similar except every time the game loop runs, multiple games are played
    while running:
        # removes dead or stagnant genomes
        for x, active in enumerate(actives):
            changes[x] = False
            # if the instance of the game lost or if the piece_count is too high
            # remember: we also want our AI to be efficient, not just survive, so we cut it off after 150 pieces
            if boards[x].game_over or piece_count[x] > 150:
                # all of these basically remove them from the list of variables
                ge[x].fitness += boards[x].score
                ge[x].fitness = ge[x].fitness
                actives.pop(x)
                boards.pop(x)
                nets.pop(x)
                ge.pop(x)
                piece_bags.pop(x)
                piece_bags2.pop(x)
                tickers.pop(x)
                changes.pop(x)
                hold_pieces.pop(x)
        # if all the genomes have been terminated, end
        if len(actives) == 0:
            break

        for x, board in enumerate(boards):
            if actives[x].soft_drop(boards[x]):
                changes[x] = True
                boards[x].soft_drop += 1
        # Did the user click the window close button?
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            # update piece based on genome
            # AI training main part:
        for x, active in enumerate(actives):
            # plus 0.1 fitness every tick it survives, nothing too much, just a little incentive to see what happens
            ge[x].fitness += 0.1
            # if we need the next piece then none of this happens, we need to get that piece ASAP
            # this if statement should never be true, simply just an error catcher
            # so our training doesn't abruptly stop
            if boards[x].need_next:
                continue
            # gets all possible moves for current piece
            curr_possible_moves = AI_helper.get_possible_moves(boards[x], actives[x])
            # gets all possible moves for the piece if "hold" is used
            if hold_pieces[x] is None:
                curr_possible_moves_hold = AI_helper.get_possible_moves(boards[x],
                                                                        pieces.get_piece(piece_bags[x][0], 0, 0))
            else:
                curr_possible_moves_hold = AI_helper.get_possible_moves(boards[x], hold_pieces[x])
            # best_move_ratings and best_possible_moves are not used in this iteration but are there for future use
            move_ratings = []
            total_possible_moves = []
            best_move_ratings = []
            best_possible_moves = []
            # for all possible moves, get the move_rating
            for i in range(len(curr_possible_moves)):
                # create a copy of the board
                temp_board = deepcopy(boards[x])
                curr_piece = curr_possible_moves[i][1][1]
                # add the potential result of that move to the copy of the board
                for bl in curr_piece.get_blocks():
                    temp_board.add(bl.get_col(), bl.get_row(), bl.get_color())
                # evaluate the board
                temp_nums = temp_board.clear_line(curr_piece, isinstance(curr_piece, tPiece),
                                                  isinstance(curr_piece, iPiece))
                # evaluate the board
                nums = AI_helper.get__hrt_advanced(temp_board)
                # those numbers into the neural network to evaluate the state
                move_rating = nets[x].activate((*nums, temp_nums[0], temp_nums[4], temp_nums[5]))[0]

                # add that evaluation to the list of all other evaluations
                move_ratings.append(move_rating)
                # add the possible move to the list of all other possible moves
                # move ratings and moves correspond (if not then nothing will work)
                total_possible_moves.append(curr_possible_moves[i])
                # this adds to best_possible_moves and best_move_ratings
                # note these are not actually used in this iteration, simply for future use
                # if (nums[0] - boards[x].holes) <= 0:
                #     best_possible_moves.append(curr_possible_moves[i])
                #     best_move_ratings.append(move_rating)
            # does the exact same thing as the above loop but for the piece you get if you used the "hold" command
            # adds results to the same list
            # differences are commented
            for i in range(len(curr_possible_moves_hold)):
                temp_board = deepcopy(boards[x])
                curr_piece = curr_possible_moves_hold[i][1][1]
                for bl in curr_piece.get_blocks():
                    temp_board.add(bl.get_col(), bl.get_row(), bl.get_color())
                temp_nums = temp_board.clear_line(curr_piece, isinstance(curr_piece, tPiece),
                                                  isinstance(curr_piece, iPiece))
                nums = AI_helper.get__hrt_advanced(temp_board)
                move_rating = nets[x].activate((*nums, temp_nums[0], temp_nums[4], temp_nums[5]))[0]
                move_ratings.append(move_rating)
                # because we have to hold first to access this piece, insert the corresponding number to move set
                # remember: 7 = hold
                curr_possible_moves_hold[i][1][0].insert(0, 7)
                total_possible_moves.append(curr_possible_moves_hold[i])
                # if (nums[0] - boards[x].holes) <= 0:
                #     best_possible_moves.append(curr_possible_moves_hold[i])
                #     best_move_ratings.append(move_rating)
            index = move_ratings.index(max(move_ratings))
            final_move_set = total_possible_moves[index][1][0]
            # only if 0 holes: diff AI version, code commented out:
            # index = best_move_ratings.index(max(best_move_ratings))
            # final_move_set = best_possible_moves[index][1][0]

            # given the best move: we loop through the move set and perform those moves to the piece
            # the moves should result in the board state that the neural network evaluated in the loops above
            for i in range(len(final_move_set)):
                if final_move_set[i] != 7:
                    AI_helper.move_code(final_move_set[i], actives[x], boards[x])
                else:
                    if hold_pieces[x] is not None:
                        temp_piece = actives[x]
                        actives[x] = hold_pieces[x]
                        hold_pieces[x] = temp_piece
                    else:
                        hold_pieces[x] = actives[x]
                        actives[x] = extract_piece(piece_bags[x], piece_bags2[x])
                # every move_set hsa a 1 at the end because in regular tetris
                # hard dropping means you get the next piece instantly, if you soft drop, you have to wait a bit
                if final_move_set[i] == 1:
                    boards[x].need_next = True
        # draw the piece so we can see what's going on
        # this game loop pretty computationally heavy, the graphics will be really laggy
        graphics.draw(screen, actives[0], boards[0], hold_pieces[0], piece_bags[0], boards[0].score, "", "")
        # loop to get the next piece
        for x, active in enumerate(actives):
            if boards[x].need_next:
                # increment piece_count useful potentially in the future
                piece_count[x] += 1
                boards[x].can_hold = True
                # add it to that piece's game board
                for block in actives[x].get_blocks():
                    boards[x].add(block.get_col(), block.get_row(), block.get_color())
                # clear the line
                boards[x].clear_line(actives[x], isinstance(actives[x], tPiece), isinstance(actives[x], iPiece))
                # get the next piece
                actives[x] = extract_piece(piece_bags[x], piece_bags2[x])
                boards[x].curr_row = 0
                # we don't need a next anymore
                boards[x].need_next = False
                tickers[x] = 0
        # Draw everything if something changed or if first frame
        # We only draw the first in each genome, rendering all of them would be too much
        # Flip the display
        pygame.display.flip()
        graphics.draw(screen, actives[0], boards[0], hold_pieces[0], piece_bags[0], boards[0].score, "", "")
        # Done! Time to quit.
        ticks += 1
コード例 #25
0
ファイル: test.py プロジェクト: marcomorucci/alliance-game
 def next_round(event):
     win = game.play_round()
     if win is None:
         graphics.draw(f, w, l, game.state)
     else:
         graphics.draw_winner(w, win)
コード例 #26
0
ファイル: main.py プロジェクト: Wilkopolis/Projects
def main ():
	state = State.MAIN
	run = True
	draw(get_terminal_size(), state)
	while run:
		sleep(1)
コード例 #27
0
ファイル: game.py プロジェクト: CrankyKong/PhysicsGame
screen = pygame.display.set_mode((400, 400),
                                 pygame.DOUBLEBUF | pygame.HWSURFACE)

current_map = map.sample_map()
graphics.set_map(current_map)

slime = objects.Slime()
slime.x = 128
slime.y = 128
# minotaur.move_to(20, 100)
# minotaur.move_to(250, 100)
# minotaur.move_to(100, 150)
events.register(pygame.KEYDOWN, slime.key_handler)
events.register(pygame.KEYUP, slime.key_handler)
graphics.add_sprite(slime)

clock = pygame.time.Clock()
time_ms = 0
clock.tick()
while run:
    time_ms += clock.tick(50)

    while time_ms > 20:
        slime.update()
        time_ms -= 20

    graphics.draw(screen)
    events.handle()

pygame.quit()
コード例 #28
0
ファイル: game.py プロジェクト: cosmologicon/unifac
def draw(mpos):
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
	glEnable(GL_DEPTH_TEST)
#	glEnable(GL_CULL_FACE)

	lighting.setdamagelight(state.t % 1)
	camera.look()

	glDisable(GL_LIGHTING)
	graphics.draw(graphics.stars, min(settings.sx * settings.sy / 2000000., 1))
	glEnable(GL_LIGHTING)

	lighting.moon()
	glPushMatrix()
	glScale(state.R, state.R, state.R)
	graphics.draw(graphics.moon)
	glPopMatrix()

	lighting.normal()
	# wire thickness
	glLineWidth(int(math.ceil(camera.wthick())))
	for obj in state.drawers():
		glPushMatrix()
		obj.draw()
		glPopMatrix()
	for obj in state.drawers():
		if not obj.fx:
			continue
		glPushMatrix()
		obj.drawfx()
		glPopMatrix()

	px, py = mpos
	p = camera.screentoworld((settings.sx - px, settings.sy - py))
	
	cursor.pointingto = None
	warning = None
	if p and cursor.tobuild:
		phat = p.norm()
		f = camera.eye().rej(phat).norm()
		tower = cursor.tobuild(phat, f)
		tower.dummy = True
		tower.invalid = not state.canbuild(cursor.tobuild, p.norm())
		glPushMatrix()
		tower.draw()
		glPopMatrix()
		for w in state.wiresto(tower):
			w.draw()
		err = state.builderror(cursor.tobuild)
		if err is not None:
			warning = "Unable to build:\n%s" % err
		if warning is None:
			if not state.willgetpower(cursor.tobuild, p.norm()):
				for p, ptype in zip(cursor.tobuild.pneeds, info.pnames):
					if p:
						warning = "Warning: structure will not function\nwithout a %s connection." % ptype
		if warning is None:
			jfail = state.overload(cursor.tobuild.pneeds)
			if jfail is not None:
				warning = "Warning: placing this structure will\noverload %s capacity." % info.pnames[jfail]
	elif p:
		cursor.pointingto = state.pointing(p)

	if warning is None and hud.launchpoint:
		err = state.launcherror(hud.launchpoint)
		if err:
			warning = "Unable to launch:\n" + err


	if warning is None:
		for j in range(3):
			if state.reserves[j] < 0:
				warning = "Warning! %s capacity exceeded!\nShutdown imminent!" % info.pnames[j]
	if warning is None:
		if state.nsat > state.satcon:
			warning = "Warning! Satellite control exceeded!\nDe-orbiting imminent!"


	hud.labels["powerwarning"].settext(warning)


	text.setup()

	hud.draw()

	if alpha < 1:
		glPushMatrix()
		graphics.fill(0, 0, 0, 1-alpha)
		glPopMatrix()
		glEnable(GL_TEXTURE_2D)

	if hud.endtitle:
		hud.endtitle.draw()

#	if state.t < 1:
#		text.write("Moony moony moons!", None, 54, (255, 255, 0), (settings.sx/2, 100), (0, 0, 0))

#	text.write("Moony moony moons!", None, 54, (255, 255, 0), (settings.sx/2, 100), (0, 0, 0), alpha=0.3)
#	text.write("Moony moony moonzzzz!", None, 54, (255, 255, 0), (settings.sx/2, 200), (0, 0, 0))

#	text.write("O", None, 8, (255, 0, 0), camera.worldtoscreen(vec(0, 0, state.R)), (0, 0, 0))
	
	glDisable(GL_TEXTURE_2D)
コード例 #29
0
ファイル: autoPlay.py プロジェクト: vincentyliu2001/Tetris
def eval_genome(genome, config):
    pygame.init()
    clock = pygame.time.Clock()
    ticks = 0
    running = True
    # Screen dimensions
    SCREEN_WIDTH = 700
    SCREEN_HEIGHT = 500
    # Create screen obj
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    net = neat.nn.FeedForwardNetwork.create(genome, config)
    piece_bag = []
    piece_bag2 = []
    initialize_bag(piece_bag, piece_bag2)
    board = Board()
    active = extract_piece(piece_bag, piece_bag2)
    ge = genome
    tickers = 0
    piece_count = 0
    hold_piece = None
    print_message_1 = ""
    print_message_2 = ""
    # game loop very similar except every time the game loop runs, multiple games are played
    while running:
        # removes dead or stagnant genomes
        if board.game_over:
            board = Board()
            hold_piece = None
            score = 0
            board.soft_drop = 0
            print_message_1 = ""
            print_message_2 = ""
            can_hold = True
            initialize_bag(piece_bag, piece_bag2)
            active = extract_piece(piece_bag, piece_bag2)
            game_over = False
            graphics.draw(screen, active, board, hold_piece, piece_bag, score, print_message_1, print_message_2)
        # Did the user click the window close button?
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            # update piece based on genome
        # AI training main part:
        # gets all possible moves for current piece
        curr_possible_moves = AI_helper.get_possible_moves(board, active)
        # gets all possible moves for the piece if "hold" is used
        if hold_piece is None:
            curr_possible_moves_hold = AI_helper.get_possible_moves(board,
                                                                    pieces.get_piece(piece_bag[0], 0, 0))
        else:
            curr_possible_moves_hold = AI_helper.get_possible_moves(board, hold_piece)
        # best_move_ratings and best_possible_moves are not used in this iteration but are there for future use
        move_ratings = []
        total_possible_moves = []
        best_move_ratings = []
        best_possible_moves = []
        # for all possible moves, get the move_rating
        for i in range(len(curr_possible_moves)):
            # create a copy of the board
            temp_board = deepcopy(board)
            curr_piece = curr_possible_moves[i][1][1]
            # add the potential result of that move to the copy of the board
            for bl in curr_piece.get_blocks():
                temp_board.add(bl.get_col(), bl.get_row(), bl.get_color())
            # evaluate the board
            temp_nums = temp_board.clear_line(curr_piece, isinstance(curr_piece, tPiece),
                                              isinstance(curr_piece, iPiece))
            # evaluate the board
            nums = AI_helper.get__hrt_advanced(temp_board)
            # feed those numbers into the neural network to evaluate the state
            move_rating = net.activate((*nums, temp_nums[0], temp_nums[4], temp_nums[5]))[0]
            # add that evaluation to the list of all other evaluations
            move_ratings.append(move_rating)
            # add the possible move to the list of all other possible moves
            # move ratings and moves correspond (if not then nothing will work)
            total_possible_moves.append(curr_possible_moves[i])
            # this adds to best_possible_moves and best_move_ratings
            # note these are not actually used in this iteration, simply for future use
            if (nums[0] - board.holes) <= 0:
                best_possible_moves.append(curr_possible_moves[i])
                best_move_ratings.append(move_rating)
        # does the exact same thing as the above loop but for the piece you get if you used the "hold" command
        # adds results to the same list
        # differences are commented
        for i in range(len(curr_possible_moves_hold)):
            temp_board = deepcopy(board)
            curr_piece = curr_possible_moves_hold[i][1][1]
            for bl in curr_piece.get_blocks():
                temp_board.add(bl.get_col(), bl.get_row(), bl.get_color())
            temp_nums = temp_board.clear_line(curr_piece, isinstance(curr_piece, tPiece),
                                              isinstance(curr_piece, iPiece))
            nums = AI_helper.get__hrt_advanced(temp_board)
            move_rating = net.activate((*nums, temp_nums[0], temp_nums[4], temp_nums[5]))[0]
            move_ratings.append(move_rating)
            # because we have to hold first to access this piece, insert the corresponding number to move set
            # remember: 7 = hold
            curr_possible_moves_hold[i][1][0].insert(0, 7)
            total_possible_moves.append(curr_possible_moves_hold[i])
            if (nums[0] - board.holes) <= 0:
                best_possible_moves.append(curr_possible_moves_hold[i])
                best_move_ratings.append(move_rating)
        index = move_ratings.index(max(move_ratings))
        final_move_set = total_possible_moves[index][1][0]
        # only if 0 holes: diff AI version, code commented out:
        # index = best_move_ratings.index(max(best_move_ratings))
        # final_move_set = best_possible_moves[index][1][0]

        # given the best move: we loop through the move set and perform those moves to the piece
        # the moves should result in the board state that the neural network evaluated in the loops above
        for i in range(len(final_move_set)):
            if final_move_set[i] != 7:
                AI_helper.move_code(final_move_set[i], active, board)
            else:
                if hold_piece is not None:
                    temp_piece = active
                    active = hold_piece
                    hold_piece = temp_piece
                else:
                    hold_piece = active
                    active = extract_piece(piece_bag, piece_bag2)
            # every move_set hsa a 1 at the end because in regular tetris
            # hard dropping means you get the next piece instantly, if you soft drop, you have to wait a bit
            if final_move_set[i] == 1:
                board.need_next = True
            # draw the piece so we can see what's going on
            # this game loop pretty computationally heavy, the graphics will be really laggy
            # loop to get the next piece
        if board.need_next:
            # increment piece_count useful potentially in the future
            piece_count += 1
            board.can_hold = True
            # add it to that piece's game board
            for block in active.get_blocks():
                board.add(block.get_col(), block.get_row(), block.get_color())
            # clear the line
            messages = board.clear_line(active, isinstance(active, tPiece), isinstance(active, iPiece))
            print_message_1 = messages[1]
            print_message_2 = messages[2]
            # get the next piece
            active = extract_piece(piece_bag, piece_bag2)
            board.curr_row = 0
            # we don't need a next anymore
            board.need_next = False
            ticker = 0
        # Draw everything if something changed or if first frame
        # We only draw the first in each genome, rendering all of them would be too much
        # Flip the display
        pygame.display.flip()
        pps = 2
        # uncomment below line to limit pieces per second
        # clock.tick(pps)
        graphics.draw(screen, active, board, hold_piece, piece_bag, board.score, print_message_1, print_message_2)
        # Done! Time to quit.
        ticks += 1
コード例 #30
0
 def next_round(event):
     win = game.play_round()
     if win is None:
         graphics.draw(f, w, l, game.state)
     else:
         graphics.draw_winner(w, win)
コード例 #31
0
ファイル: gamelogic.py プロジェクト: barisser/pysim
def cycle(screen, world, tempdata):
    #render_land(screen)
    graphics.draw(screen, world, tempdata)
コード例 #32
0
ファイル: tetris.py プロジェクト: mpsilfve/tetris
import pygame

from Grid import Grid
from graphics import draw
from events import handle_events

pygame.init()
grid = Grid()

while 1:
    events = pygame.event.get()
    # A False return value signifies quit.
    if not handle_events(events, grid):
        break

    draw(grid)

    # Sleep a bit every iteration to reduce CPU load.
    pygame.time.wait(35)

    # The current active block will fall one row downward every
    # 1/level seconds.
    if pygame.time.get_ticks() - grid.prev_advance >= 1000 / grid.level:
        grid.prev_advance = pygame.time.get_ticks()
        grid.advance()

    # The level will increase every 50 second
    if pygame.time.get_ticks() - grid.prev_level_up >= 50000:
        grid.level_up()