Python Forum

Full Version: Can't make the turtle walk..
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I made this game that there is a turtle and you can make walls using mouse1, delete them using mouse2 and "command" the turtle to walk with scroll click.
The problems that I have are:
The turtle is teleporting all over the place.
The turtle is not even going on the right path..
I've tried to fix it for 3~4h and still can't seem to find a solution.
Here is the code:
import pygame
import a_star, numpy, heapq, time
size = screen_width , screen_heigth= 900, 900

LeftClick = False
MiddleClick = False
RightClick = False

turtle = pygame.image.load("turtle.png")
turtleRect = turtle.get_rect()
turtleRect.center = (406, 406) #Initiate the turtle in the middle


black = (0, 0, 0)
white = (255, 255, 255)
width = 25
margin = 5
grid = [[0 for x in range(30)] for y in range(30)]

screen = pygame.display.set_mode(size)


def draw_grid(length, margin):
"""Draws the grid"""
for row in range(30):
for column in range(30):
color = white
if grid[row][column] == 1:
color = (127, 123, 111) #The color of the wall
pygame.draw.rect(screen,
color,
[(margin+ width) * column + margin,
  (margin+ width) * row + margin,
  length, length])

def set_block(value):
"""Sets the value of the block"""
row, column = get_coords()
grid[row][column] = value

def get_coords():
"""Get's the coordonates of the block that was clicked"""
pos = pygame.mouse.get_pos()
row, column = get_block(pos[0], pos[1])
return (row, column)



def get_path(endX, endY):
"""Get the path"""
try:
print("Incercam la get_path")
NPgrid = numpy.array(grid)
start = get_block(turtleRect.center[0],turtleRect.center[1])
goal =  get_block(endY, endX)
path = a_star.astar(NPgrid, start, goal)
path = path[::-1]
return path
except:
pass


def blockCenter(x,y):
return (x*30+12.5, y*30+12.5)



def get_block(x, y):
"""Gets the row and column given the position of the block"""
column = x // (width + margin)
row = y // (width + margin)
return row, column

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit() #Exit
elif event.type == pygame.MOUSEBUTTONDOWN: # Mouse click
TypeOfClick = pygame.mouse.get_pressed()
if TypeOfClick[0] == 1: #Left Click
LeftClick = True
else: LeftClick = False
if TypeOfClick[1] == 1: #Middle Click
MiddleClick = True
else: MiddleClick = False
if TypeOfClick[2] == 1: #Right Click
RightClick = True
else: RightClick = False

elif event.type == pygame.MOUSEBUTTONUP:
LeftClick, RightClick, MiddleClick = False, False , False

#Daca Click-ul este inca apasat atunci seteaza block-ul
if LeftClick:
set_block(1)
elif RightClick:
set_block(0)
elif MiddleClick:
pos = pygame.mouse.get_pos()
path = get_path(pos[0], pos[1])


screen.fill(black) #Keep this so it doesn't make a trail

#Miscam testoasa
try:
for coords in path:
print(coords,path)
#continue
print("Incercam la asta cu try")
bx, by = blockCenter(coords[0], coords[1]) #Mijloacele blockurilor
dx, dy = (bx - turtleRect.center[0] , by - turtleRect.center[1]) #Distanta
stepx, stepy = (dx / 30., dy / 30.) #Cati pasi sa ia
for _ in range(30):
turtleRect = turtleRect.move(stepx, stepy)
screen.blit(turtle, turtleRect)
#time.wait(0.01)
path = []
except:
pass

pygame.display.set_caption("ATurtle") #The title
pygame.time.Clock().tick(30) #30 fps

# Draw the screen
draw_grid(width, margin)



#print(turtleRect.center)
screen.blit(turtle, turtleRect)
pygame.display.flip()
Here is the a_star:
# Author: Christian Careaga ([email protected])
# A* Pathfinding in Python (2.7)
# Please give credit if used

import numpy
from heapq import *


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

def astar(array, start, goal):

   neighbors = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]

   close_set = set()
   came_from = {}
   gscore = {start:0}
   fscore = {start:heuristic(start, goal)}
   oheap = []

   heappush(oheap, (fscore[start], start))
   
   while oheap:

       current = heappop(oheap)[1]

       if current == goal:
           data = []
           while current in came_from:
               data.append(current)
               current = came_from[current]
           return data

       close_set.add(current)
       for i, j in neighbors:
           neighbor = current[0] + i, current[1] + j            
           tentative_g_score = gscore[current] + heuristic(current, neighbor)
           if 0 <= neighbor[0] < array.shape[0]:
               if 0 <= neighbor[1] < array.shape[1]:                
                   if array[neighbor[0]][neighbor[1]] == 1:
                       continue
               else:
                   # array bound y walls
                   continue
           else:
               # array bound x walls
               continue
               
           if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
               continue
               
           if  tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1]for i in oheap]:
               came_from[neighbor] = current
               gscore[neighbor] = tentative_g_score
               fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
               heappush(oheap, (fscore[neighbor], neighbor))
               
   return False
Difficult to help you, if your code is not indented right.
1. Indentation like heiner55 said !

2. no loops in main loop. it just make him do all his moves in 1 turn.
for coords in path:
3. pygame.display.set_caption should not be in loop
4. suggestion pygame.time.Clock() should be a variable outside the loop
5. never use python time.sleep() it stop the world.
@Windspar:
Good suggestions