pygame 可视化A*算法动态过程

前言
本来想用QT实现这个可视化过程但奈何QT学起来有些花费时间,所以我就自顾自的用pygame实现了一个不是很完美的A*寻路可视化。

正题:
看一下代码:

import pygame
import sys
import queue as Q


class Node(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

    def __lt__(self, other):
        return self.a < other.a


class NS(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y


ex = 29
ey = 39
q = Q.Queue()
Map = [[0 for i in range(40)] for _ in range(30)]


def calc(x, y):
    return (ex-x)+(ey-y)


def A_star():
    vis = [[0 for i in range(40)] for _ in range(30)]
    dir = [[1, 0], [-1, 0], [0, 1], [0, -1],
           [1, 1], [-1, 1], [1, -1], [-1, -1]]
    dis = [[100000 for i in range(40)] for _ in range(30)]
    que = Q.PriorityQueue()
    dis[0][0] = 0
    que.put(Node(calc(0, 0)+dis[0][0], 0, 0))
    while not que.empty():
        st = que.get()

        if vis[st.b][st.c] == 0:
            q.put(NS(st.b, st.c))
            vis[st.b][st.c] = 1
            if st.b == ex and st.c == ey:
                break
            for i in range(8):
                xx = st.b+dir[i][0]
                yy = st.c+dir[i][1]
                if (xx >= 0) and (yy >= 0) and (xx <= ex) and (yy <= ey) and Map[xx][yy] == 0:
                    dis[xx][yy] = min(dis[xx][yy], dis[st.b][st.c]+1)
                    que.put(Node(dis[xx][yy]+calc(xx, yy), xx, yy))


for i in range(30):
    for j in range(40):
        if i+j == 15:
            Map[i][j] = 1
        elif j == 8:
            Map[i][j] = 1

Map[0][15] = 0
Map[15][0] = 0
Map[0][8] = 0
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("py")
Black = pygame.Color("black")
Green = pygame.Color("green")
Red = pygame.Color("red")
fps = 100
fclock = pygame.time.Clock()

screen.fill("grey")
for i in range(0, 30):
    for j in range(0, 40):
        pygame.draw.rect(screen, Black, (j*20, i*20, 20, 20), 1)
for i in range(30):
    for j in range(40):
        if(Map[i][j] == 1):
            pygame.draw.rect(screen, Red, (j*20, i*20, 20, 20), 0)
A_star()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    if not q.empty():
        st = q.get()
    pygame.draw.rect(screen, Green, (st.y*20, st.x*20, 20, 20), 0)
    fclock.tick(fps)
    pygame.display.update()

动态图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yangzijiangac/article/details/112567638
今日推荐