staging.inyokaproject.org

Python Pathfindig (Wegfindung)?

Status: Gelöst | Ubuntu-Version: Kubuntu 24.04 (Noble Numbat)
Antworten |

Kätzchen

Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Hallo zusammen,

ich bastel mit Hilfe von Ki unterstützung an einem Python Script das eine art Pathfinding (Wegfindung) möglich machen soll.

Es wird ein Fenster anzeigt in in dem ein weißes Quadrat zu sehen ist und ein Rotes Quadrat. Klickt man mit der Maus in das Fenster wandert das weiße Quadrat dorthin wo der Mausklick ausgeführt wurde. Soweit so okay.

Wenn zwischen dem Standort vom weißen Quadrat - das rote Quadrat liegt - "wandert" das weiße Quadrat entlang der Seite des Roten und zwar bis zur 1. Ecke, dann geht es nicht mehr weiter.

Ziel wäre es dass das weiße Quadrat dann auch am Mausklick-Punkt ankommt.

KI Code von https://www.phind.com/search?home=true

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import pygame
import sys
from heapq import heappop, heappush
import math

# Initialize Pygame
pygame.init()

# Set up the display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()

# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)

# Grid dimensions
GRID_WIDTH = 50
GRID_HEIGHT = 30
CELL_SIZE = 16

# Create a grid representing the environment
grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]

class AnimatedImage(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface([32, 32])
        self.image.fill(WHITE)
        self.rect = self.image.get_rect(center=(x, y))
        self.target_position = None
        self.reached_target = False
        self.current_frame = 0
        self.total_frames = 24
        self.animation_speed = 15
        self.red_square_radius = 75

    def update(self):
        if self.target_position and not self.reached_target:
            dx = self.target_position[0] - self.rect.centerx
            dy = self.target_position[1] - self.rect.centery
            dist_to_red = math.hypot(dx, dy)
            
            # Check if within radius of red square
            if dist_to_red == 0:
                self.reached_target = True
                return
            
            # Raycasting check for collision
            raycast_angle = math.atan2(dy, dx)
            raycast_steps = int(dist_to_red / 5)
            
            for i in range(raycast_steps):
                raycast_x = self.rect.centerx + math.cos(raycast_angle) * (i + 1)
                raycast_y = self.rect.centery + math.sin(raycast_angle) * (i + 1)
                
                if self.is_colliding_with_red_square(raycast_x, raycast_y):
                    # Avoid collision by moving slightly away from the red square
                    angle = math.atan2(dy, dx)
                    new_x = self.rect.centerx + math.cos(angle) * 5
                    new_y = self.rect.centery + math.sin(angle) * 5
                    
                    self.rect.center = (int(new_x), int(new_y))
                    break
            else:
                # Normal movement when no collision detected
                self.rect.centerx += dx / dist_to_red
                self.rect.centery += dy / dist_to_red
            
            # Update animation frame
            self.current_frame = (self.current_frame + 1) % self.total_frames

    def is_colliding_with_red_square(self, x, y):
        # Check if the point (x, y) is within the red square
        return (250 - self.red_square_radius < x < 250 + self.red_square_radius and
                250 - self.red_square_radius < y < 250 + self.red_square_radius)


    def get_closest_direction(self, dx, dy):
        if abs(dx) > abs(dy):
            return (1 if dx > 0 else -1, 0)
        return (0, 1 if dy > 0 else -1)

    def update_current_frame(self, direction):
        if direction == (1, 0):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(0, 16), (32, 16), (16, 0)])
        elif direction == (-1, 0):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(32, 16), (0, 16), (16, 0)])
        elif direction == (0, 1):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(16, 0), (0, 32), (32, 32)])
        elif direction == (0, -1):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(16, 32), (32, 0), (0, 32)])

def astar(start, goal):
    open_list = []
    closed_list = set()
    parent_dict = {}
    g_score = {start: 0}
    f_score = {start: heuristic(start, goal)}
    heappush(open_list, (f_score[start], start))

    while open_list:
        _, current = heappop(open_list)
        if current == goal:
            path = []
            current = goal
            while current in parent_dict:
                path.append(current)
                current = parent_dict[current]
            path.append(start)
            return path[::-1]

        closed_list.add(current)

        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            neighbor = (current[0] + dx, current[1] + dy)
            if (0 <= neighbor[0] < GRID_WIDTH and 0 <= neighbor[1] < GRID_HEIGHT and
                grid[neighbor[1]][neighbor[0]] != 1):
                tentative_g_score = g_score[current] + 1
                if neighbor not in g_score or tentative_g_score < g_score[neighbor]:
                    parent_dict[neighbor] = current
                    g_score[neighbor] = tentative_g_score
                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
                    heappush(open_list, (f_score[neighbor], neighbor))

    return None

def heuristic(a, b):
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

def draw_grid():
    for i in range(0, height, CELL_SIZE):
        pygame.draw.line(screen, BLACK, (0, i), (width, i))
    for j in range(0, width, CELL_SIZE):
        pygame.draw.line(screen, BLACK, (j, 0), (j, height))

def main():
    all_sprites = pygame.sprite.Group()
    
    # White Square
    white_square = AnimatedImage(200, 350)
    all_sprites.add(white_square)
    
    # Red Square
    red_sprite = pygame.sprite.Sprite()
    red_sprite.image = pygame.Surface((150, 150))
    red_sprite.image.fill(RED)
    red_sprite.rect = red_sprite.image.get_rect(topleft=(250, 250))
    all_sprites.add(red_sprite)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print(f"Mouse clicked at: {event.pos}")
                white_square.target_position = event.pos
                white_square.reached_target = False

        screen.fill(BLACK)
        draw_grid()
        
        # Bypass the red square
        if red_sprite.rect.collidepoint(white_square.rect.center):
            target_vector = pygame.math.Vector2(red_sprite.rect.topleft)
            current_vector = pygame.math.Vector2(white_square.rect.center)
            lerp_weight = 0.5
            white_square.target_position = tuple(current_vector.lerp(target_vector, lerp_weight))

        all_sprites.update()
        all_sprites.draw(screen)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()
    sys.exit()



if __name__ == "__main__":
    main()

Ich wollte es zwar nie im Forum schreiben aber ich bin psyschisch krank und das entwickelt sich langsam zu einem Zwang, aber mit KI komme ich nicht weiter. Das höchste der gefühle in meinem Fall ist es funktionierde Skripte an meine Bedürfnisse anzupassen.

Danke fürs lesen soweit und vielleicht hat ja jemand der Python Erfahrung hat lust mir zu helfen?

Mylin

Avatar von Mylin

Anmeldungsdatum:
23. Juli 2024

Beiträge: 371

Ich habe folgende mögliche Lösung vorgeschlagen bekommen:

Das Problem liegt darin, dass das weiße Quadrat, wenn es das rote Quadrat erreicht, seine Zielposition auf die Position des roten Quadrats setzt und dann nicht mehr weitergeht. Um dies zu beheben, müssen wir den A\*-Algorithmus verwenden, um eine Route um das rote Quadrat herum zu finden.

Hier ist eine mögliche Lösung:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def main():
    all_sprites = pygame.sprite.Group()
    
    # White Square
    white_square = AnimatedImage(200, 350)
    all_sprites.add(white_square)
    
    # Red Square
    red_sprite = pygame.sprite.Sprite()
    red_sprite.image = pygame.Surface((150, 150))
    red_sprite.image.fill(RED)
    red_sprite.rect = red_sprite.image.get_rect(topleft=(250, 250))
    all_sprites.add(red_sprite)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print(f"Mouse clicked at: {event.pos}")
                white_square.target_position = event.pos
                white_square.reached_target = False

        screen.fill(BLACK)
        draw_grid()
        
        # Bypass red square
        if red_sprite.rect.collidepoint(white_square.rect.center):
            # Find a route around the red square using A*
            start = (white_square.rect.centerx // CELL_SIZE, white_square.rect.centery // CELL_SIZE)
            goal = (white_square.target_position[0] // CELL_SIZE, white_square.target_position[1] // CELL_SIZE)
            path = astar(start, goal)
            if path:
                # Set the target position to the next point in the path
                white_square.target_position = (path[1][0] * CELL_SIZE + CELL_SIZE // 2, path[1][1] * CELL_SIZE + CELL_SIZE // 2)
                white_square.reached_target = False

        all_sprites.update()
        all_sprites.draw(screen)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()
    sys.exit()

In diesem Code wird der A\*-Algorithmus verwendet, um eine Route um das rote Quadrat herum zu finden, wenn das weiße Quadrat es erreicht. Die Zielposition des weißen Quadrats wird dann auf den nächsten Punkt in der Route gesetzt. Dies sollte es ermöglichen, dass das weiße Quadrat am Mausklick-Punkt ankommt.

Kätzchen

(Themenstarter)
Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Super das du mir helfen willst! ☺

simon@ZBOX:~/Desktop/Test$ python3 Stuck.py
pygame 2.6.0 (SDL 2.28.4, Python 3.12.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
Mouse clicked at: (455, 337)
Traceback (most recent call last):
  File "/home/simon/Desktop/Test/Stuck.py", line 198, in <module>
    main()
  File "/home/simon/Desktop/Test/Stuck.py", line 182, in main
    white_square.target_position = (path[1][0] * CELL_SIZE + CELL_SIZE // 2, path[1][1] * CELL_SIZE + CELL_SIZE // 2)
                                    ~~~~^^^
IndexError: list index out of range
simon@ZBOX:~/Desktop/Test$

phind.com hat mir das zu:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
def main():
    all_sprites = pygame.sprite.Group()
    
    # White Square
    white_square = AnimatedImage(200, 350)
    all_sprites.add(white_square)
    
    # Red Square
    red_sprite = pygame.sprite.Sprite()
    red_sprite.image = pygame.Surface((150, 150))
    red_sprite.image.fill(RED)
    red_sprite.rect = red_sprite.image.get_rect(topleft=(250, 250))
    all_sprites.add(red_sprite)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print(f"Mouse clicked at: {event.pos}")
                white_square.target_position = event.pos
                white_square.reached_target = False

        screen.fill(BLACK)
        draw_grid()
        
        # Bypass red square
        if red_sprite.rect.collidepoint(white_square.rect.center):
            # Find a route around the red square using A*
            start = (white_square.rect.centerx // CELL_SIZE, white_square.rect.centery // CELL_SIZE)
            goal = (white_square.target_position[0] // CELL_SIZE, white_square.target_position[1] // CELL_SIZE)
            path = astar(start, goal)
            
            if path is None:
                print("No path found")
            elif len(path) < 2:
                print("Invalid path length")
            else:
                # Set the target position to the next point in the path
                white_square.target_position = (path[1][0] * CELL_SIZE + CELL_SIZE // 2, path[1][1] * CELL_SIZE + CELL_SIZE // 2)
                white_square.reached_target = False

        all_sprites.update()
        all_sprites.draw(screen)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()
    sys.exit()

geändert:

Das Ergebnis ist dann, das weiße Quadrat wandert fast vollständig in das Rote und dann kommt mit immer wieder kehrender Ausgabe :

simon@ZBOX:~/Desktop/Test$ python3 Stuck.py
pygame 2.6.0 (SDL 2.28.4, Python 3.12.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
Mouse clicked at: (476, 362)
Invalid path length
Invalid path length
Invalid path length
Invalid path length
Invalid path length
simon@ZBOX:~/Desktop/Test$

Danke schon mal Mylin!

Mylin

Avatar von Mylin

Anmeldungsdatum:
23. Juli 2024

Beiträge: 371

Kätzchen schrieb:

simon@ZBOX:~/Desktop/Test$ python3 Stuck.py
pygame 2.6.0 (SDL 2.28.4, Python 3.12.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
Mouse clicked at: (455, 337)
Traceback (most recent call last):
  File "/home/simon/Desktop/Test/Stuck.py", line 198, in <module>
    main()
  File "/home/simon/Desktop/Test/Stuck.py", line 182, in main
    white_square.target_position = (path[1][0] * CELL_SIZE + CELL_SIZE // 2, path[1][1] * CELL_SIZE + CELL_SIZE // 2)
                                    ~~~~^^^
IndexError: list index out of range
simon@ZBOX:~/Desktop/Test$

Dazu hat Llama 3.1-70B-Instruct folgende Korrektur vorgeschlagen:

1
2
3
4
if path and len(path) > 1:
    # Set the target position to the next point in the path
    white_square.target_position = (path[1][0] * CELL_SIZE + CELL_SIZE // 2, path[1][1] * CELL_SIZE + CELL_SIZE // 2)
    white_square.reached_target = False

Kätzchen

(Themenstarter)
Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Mylin schrieb:

Dazu hat Llama 3.1-70B-Instruct folgende Korrektur vorgeschlagen:

1
2
3
4
if path and len(path) > 1:
    # Set the target position to the next point in the path
    white_square.target_position = (path[1][0] * CELL_SIZE + CELL_SIZE // 2, path[1][1] * CELL_SIZE + CELL_SIZE // 2)
    white_square.reached_target = False

Das bewegen vom weißen Quadrat ist normal, dann wandert es mit sehr vielen kleinen Schritten (jeder Mausklick ein Schritt) durch das Rote Quadrat.

Mylin

Avatar von Mylin

Anmeldungsdatum:
23. Juli 2024

Beiträge: 371

Computer sagt:

Das Problem liegt darin, dass der A*-Algorithmus bei jedem Mausklick aufgerufen wird und eine neue Route findet, die das weiße Quadrat durch das rote Quadrat führt. Da der A*-Algorithmus bei jedem Aufruf eine neue Route findet, bewegt sich das weiße Quadrat in kleinen Schritten durch das rote Quadrat. Um dies zu beheben, können wir den A*-Algorithmus nur einmal aufrufen, wenn das weiße Quadrat das rote Quadrat erreicht, und die Route speichern. Dann können wir das weiße Quadrat entlang der gespeicherten Route bewegen.

Hier ist ein Beispiel, wie du dies umsetzen kannst

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def main():
    all_sprites = pygame.sprite.Group()
    
    # White Square
    white_square = AnimatedImage(200, 350)
    all_sprites.add(white_square)
    
    # Red Square
    red_sprite = pygame.sprite.Sprite()
    red_sprite.image = pygame.Surface((150, 150))
    red_sprite.image.fill(RED)
    red_sprite.rect = red_sprite.image.get_rect(topleft=(250, 250))
    all_sprites.add(red_sprite)

    route = None
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print(f"Mouse clicked at: {event.pos}")
                white_square.target_position = event.pos
                white_square.reached_target = False

        screen.fill(BLACK)
        draw_grid()
        
        # Bypass red square
        if red_sprite.rect.collidepoint(white_square.rect.center) and route is None:
            # Find a route around the red square using A*
            start = (white_square.rect.centerx // CELL_SIZE, white_square.rect.centery // CELL_SIZE)
            goal = (white_square.target_position[0] // CELL_SIZE, white_square.target_position[1] // CELL_SIZE)
            route = astar(start, goal)

        if route and len(route) > 1:
            # Set the target position to the next point in the route
            white_square.target_position = (route[1][0] * CELL_SIZE + CELL_SIZE // 2, route[1][1] * CELL_SIZE + CELL_SIZE // 2)
            route = route[1:]
            white_square.reached_target = False

        all_sprites.update()
        all_sprites.draw(screen)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()
    sys.exit()

In diesem Code wird der A*-Algorithmus nur einmal aufgerufen, wenn das weiße Quadrat das rote Quadrat erreicht, und die Route wird gespeichert. Dann wird das weiße Quadrat entlang der Route bewegt, bis die Route abgeschlossen ist.

... jetzt war ich schon etwas neugierig und hab mal den Laptop angemacht.

Kätzchen

(Themenstarter)
Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Hallo,

Das Ergebnis ist jetzt das weiß durch rot durchgeht als wäre rot gar nicht da. Also ein klick und durchgehende Bewegung bis es ankommt. Edit: Wenn es angekommen ist gibt es eine kurze Korrektur von einer halben Höhe des weißen Quadrats.

Mylin schrieb:

... jetzt war ich schon etwas neugierig und hab mal den Laptop angemacht.

Ich hoffe du musstest jetzt nicht zulange auf meine Antwort warten. 😇

Mylin

Avatar von Mylin

Anmeldungsdatum:
23. Juli 2024

Beiträge: 371

Kätzchen schrieb:

Ich hoffe du musstest jetzt nicht zulange auf meine Antwort warten.

Nein, nein, ich wollte wissen ob es funktioniert.

Kätzchen schrieb:

Ziel wäre es dass das weiße Quadrat dann auch am Mausklick-Punkt ankommt.

Erledigt.

Kätzchen

(Themenstarter)
Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Mylin schrieb:

Kätzchen schrieb:

Ziel wäre es dass das weiße Quadrat dann auch am Mausklick-Punkt ankommt.

Erledigt.

Nein leider nicht.

Es kommt an, aber es sollte nicht direkt ankommen sondern am roten Quadrat außen entlang wandern, also es quasi umgehen:

   ******
   *0000*
   *0000*
****0000*******
    0000

Mylin

Avatar von Mylin

Anmeldungsdatum:
23. Juli 2024

Beiträge: 371

Kätzchen schrieb:

Es kommt an, aber es sollte nicht direkt ankommen sondern am roten Quadrat außen entlang wandern, also es quasi umgehen:

Viel Erfolg. Für mich ist hier Ende, dein Eingangsproblem ist erledigt.

Kätzchen

(Themenstarter)
Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Für alle interessierten:

Das angehängte Video zeigt das Ergebnis wenn man den Code aus aus dem Startpost ausführt:

Kätzchen schrieb:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import pygame
import sys
from heapq import heappop, heappush
import math

# Initialize Pygame
pygame.init()

# Set up the display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
clock = pygame.time.Clock()

# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)

# Grid dimensions
GRID_WIDTH = 50
GRID_HEIGHT = 30
CELL_SIZE = 16

# Create a grid representing the environment
grid = [[0 for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]

class AnimatedImage(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.Surface([32, 32])
        self.image.fill(WHITE)
        self.rect = self.image.get_rect(center=(x, y))
        self.target_position = None
        self.reached_target = False
        self.current_frame = 0
        self.total_frames = 24
        self.animation_speed = 15
        self.red_square_radius = 75

    def update(self):
        if self.target_position and not self.reached_target:
            dx = self.target_position[0] - self.rect.centerx
            dy = self.target_position[1] - self.rect.centery
            dist_to_red = math.hypot(dx, dy)
            
            # Check if within radius of red square
            if dist_to_red == 0:
                self.reached_target = True
                return
            
            # Raycasting check for collision
            raycast_angle = math.atan2(dy, dx)
            raycast_steps = int(dist_to_red / 5)
            
            for i in range(raycast_steps):
                raycast_x = self.rect.centerx + math.cos(raycast_angle) * (i + 1)
                raycast_y = self.rect.centery + math.sin(raycast_angle) * (i + 1)
                
                if self.is_colliding_with_red_square(raycast_x, raycast_y):
                    # Avoid collision by moving slightly away from the red square
                    angle = math.atan2(dy, dx)
                    new_x = self.rect.centerx + math.cos(angle) * 5
                    new_y = self.rect.centery + math.sin(angle) * 5
                    
                    self.rect.center = (int(new_x), int(new_y))
                    break
            else:
                # Normal movement when no collision detected
                self.rect.centerx += dx / dist_to_red
                self.rect.centery += dy / dist_to_red
            
            # Update animation frame
            self.current_frame = (self.current_frame + 1) % self.total_frames

    def is_colliding_with_red_square(self, x, y):
        # Check if the point (x, y) is within the red square
        return (250 - self.red_square_radius < x < 250 + self.red_square_radius and
                250 - self.red_square_radius < y < 250 + self.red_square_radius)


    def get_closest_direction(self, dx, dy):
        if abs(dx) > abs(dy):
            return (1 if dx > 0 else -1, 0)
        return (0, 1 if dy > 0 else -1)

    def update_current_frame(self, direction):
        if direction == (1, 0):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(0, 16), (32, 16), (16, 0)])
        elif direction == (-1, 0):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(32, 16), (0, 16), (16, 0)])
        elif direction == (0, 1):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(16, 0), (0, 32), (32, 32)])
        elif direction == (0, -1):
            self.image = pygame.Surface([32, 32])
            self.image.fill(WHITE)
            pygame.draw.polygon(self.image, BLACK, [(16, 32), (32, 0), (0, 32)])

def astar(start, goal):
    open_list = []
    closed_list = set()
    parent_dict = {}
    g_score = {start: 0}
    f_score = {start: heuristic(start, goal)}
    heappush(open_list, (f_score[start], start))

    while open_list:
        _, current = heappop(open_list)
        if current == goal:
            path = []
            current = goal
            while current in parent_dict:
                path.append(current)
                current = parent_dict[current]
            path.append(start)
            return path[::-1]

        closed_list.add(current)

        for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
            neighbor = (current[0] + dx, current[1] + dy)
            if (0 <= neighbor[0] < GRID_WIDTH and 0 <= neighbor[1] < GRID_HEIGHT and
                grid[neighbor[1]][neighbor[0]] != 1):
                tentative_g_score = g_score[current] + 1
                if neighbor not in g_score or tentative_g_score < g_score[neighbor]:
                    parent_dict[neighbor] = current
                    g_score[neighbor] = tentative_g_score
                    f_score[neighbor] = g_score[neighbor] + heuristic(neighbor, goal)
                    heappush(open_list, (f_score[neighbor], neighbor))

    return None

def heuristic(a, b):
    return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5

def draw_grid():
    for i in range(0, height, CELL_SIZE):
        pygame.draw.line(screen, BLACK, (0, i), (width, i))
    for j in range(0, width, CELL_SIZE):
        pygame.draw.line(screen, BLACK, (j, 0), (j, height))

def main():
    all_sprites = pygame.sprite.Group()
    
    # White Square
    white_square = AnimatedImage(200, 350)
    all_sprites.add(white_square)
    
    # Red Square
    red_sprite = pygame.sprite.Sprite()
    red_sprite.image = pygame.Surface((150, 150))
    red_sprite.image.fill(RED)
    red_sprite.rect = red_sprite.image.get_rect(topleft=(250, 250))
    all_sprites.add(red_sprite)

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                print(f"Mouse clicked at: {event.pos}")
                white_square.target_position = event.pos
                white_square.reached_target = False

        screen.fill(BLACK)
        draw_grid()
        
        # Bypass the red square
        if red_sprite.rect.collidepoint(white_square.rect.center):
            target_vector = pygame.math.Vector2(red_sprite.rect.topleft)
            current_vector = pygame.math.Vector2(white_square.rect.center)
            lerp_weight = 0.5
            white_square.target_position = tuple(current_vector.lerp(target_vector, lerp_weight))

        all_sprites.update()
        all_sprites.draw(screen)
        pygame.display.flip()

        clock.tick(60)

    pygame.quit()
    sys.exit()



if __name__ == "__main__":
    main()

Ich hätte gerne dss es komplett entlangwandert und dann am Mausklick-Ort ankommt.

Anhang

Kätzchen

(Themenstarter)
Avatar von Kätzchen

Anmeldungsdatum:
1. Mai 2011

Beiträge: 7130

Ich habe das Projekt aufgegeben.

Antworten |