In order to get some nodes up on the screen we'll start by creating a Node class. We'll create a file called nodes.py and add that class to it.
Start by putting in the three imports.
When we create a Node we pass in the row and column values and then compute the x and y position we want to place the Node on the screen. We'll keep all of the neighbor nodes in a list. Initially, when creating the Node object, this list is empty. We'll fill it in later.
We have two methods for adding neighbors to our Node object. If we just need to add a single node then we can call the addNeighbor method. In that method we'll check to make sure that node doesn't already exist in our neighobrs list. We also have another add method that allows us to add more than one neighbor at a time. This is basically a convenience method, and it essentially just calls our other add method for all of the neighbors in our list. Just makes it easier on us instead of having to call the addNeighbor method multiple times ourselves.
Then all we need to do is render the Node so it appears on the screen. We draw all of the paths to the neighbors first as WHITE lines, and we draw the Node itself as a RED circle. When we're finished with the game we don't actually draw the nodes, but we draw them now while we're developing the game.
nodes.py
import pygame
from constants import *
class Node(object):
def __init__(self, x, y):
self.position = pygame.Vector2(x, y)
self.neighbors = []
def addNeighbor(self, node):
if node not in self.neighbors: self.neighbors.append(node)
def addNeighbors(self, nodelist):
for node in nodelist: self.addNeighbor(node)
def render(self, screen):
for node in self.neighbors:
pygame.draw.line(screen, WHITE, self.position, node.position, 4)
pygame.draw.circle(screen, RED, self.position, 12)