在rect ERROR中的pygame文本

时间:2017-10-20 21:56:23

标签: python user-interface graph pygame

我试图在每个节点(rect)中添加数字来创建一个节点图,我可以应用算法来逐步查看它们是如何工作的,但是我遇到了一些错误。

"File "test.py", line 97, in main pygame.error: font not initialized"

我不确定我是否正确实施了def update(self)

from random import randrange, choice
import pygame
import sys
from pygame.locals import *

FR = 30
SIZE = 640, 480
BGCOLOR = (255,255,255)
NODECOLOR = (255,0,255)
NODESIZE = 25,25
GRIDSPACING = 50
MAXTRIES = 1000
STARTINGNODES = 4
TEXTCOLOR = (0,0,0)
BASICFONTSIZE = 20

class Graph(object):
    def __init__(self):
        self.nodes = set()
        # record positions of each node, so that we can check for overlaps
        self.positions = dict()

    def add(self, node):
        count = 0
        added = False
        # try to add node at some random location -
        while not added:
            x, y = (randrange(0, SIZE[0], GRIDSPACING),
                        randrange(0, SIZE[1], GRIDSPACING))
            if not (x,y) in self.positions:
                added = True
                self.nodes.add(node)
                node.setpos((x,y), self)
            count += 1
            if count >= MAXTRIES:
                raise ValueError("Could not alocate space for node representation")

    def update(self):
        SCREEN.fill(BGCOLOR)
        for node in self.nodes:
            pygame.draw.rect(SCREEN, node.color, node.rect)
            textSurf = BASICFONT.render(str(count), True, TEXTCOLOR)
            textRect = textSurf.get_rect()
            textRect.center = int(SIZE[0] / 2), int(SIZE[1] / 2)
            DISPLAYSURF.blit(textSurf, textRect)
            for neighbor in node.neighbors:
                pygame.draw.line(SCREEN, NODECOLOR,node.rect.center, neighbor.rect.center)

class Node(object):
    # Class variable, incremented with each
    # instance so that each node has a unique ID that
    # can be used as its hash:
    creation_counter = 0
    def __init__(self):
        self.id = self.__class__.creation_counter
        self.__class__.creation_counter += 1
        self.rect = None
        self.color = NODECOLOR
        self.neighbors = set()

    def setpos(self, pos, graph = None):
        if self.rect and graph:
            # remove self from previous position in the graph:
            graph.positions.pop(self.rect.topleft, None)
        self.rect = pygame.Rect(pos[0], pos[1],NODESIZE[0], NODESIZE[1])
        if graph:
            graph.positions[pos] = self

    def  __hash__(self):
        return self.id


def create_graph():
    # create new graph and populate nodes:
    graph = Graph()
    # locallist for adding neighbors:
    nodes = []
    print(nodes)
    for i in range(STARTINGNODES):
        node = Node()
        graph.add(node)
    return graph

def init():
    global SCREEN
    pygame.init()
    SCREEN = pygame.display.set_mode(SIZE)

def quit():
    pygame.quit()

def main():
    global BASICFONT
    BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)
    graph = create_graph()
    selected = None
    try:
        init()
        while True:
            graph.update()
            pygame.event.pump()
            # Exit the mainloop at any time the "ESC" key is pressed
            if pygame.key.get_pressed()[pygame.K_ESCAPE]:
                break
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos
                    # round down x,y to multiples of NODESIZE
                    x -= x % NODESIZE[0]
                    y -= y % NODESIZE[1]
                    pygame.draw.rect(SCREEN, (0,0,255), (x,y) + NODESIZE)
                    if (x,y) in graph.positions:
                        node = graph.positions[x,y]
                        if selected:
                            print selected.id, node.id
                            if selected is node:
                                selected = None
                                node.color = NODECOLOR
                            elif selected not in node.neighbors:
                                selected.neighbors.add(node)
                                node.neighbors.add(selected)
                            else:
                                selected.neighbors.remove(node)
                                node.neighbors.remove(selected)
                        else:
                            node.color = (0,0,0)
                            selected = node
                    elif selected:
                        selected.setpos((x,y), graph)
                elif event.type == pygame.MOUSEMOTION and event.buttons[0] and selected:
                    x, y = event.pos
                    # round down x,y to multiples of NODESIZE
                    x -= x % NODESIZE[0]
                    y -= y % NODESIZE[1]
                    selected.setpos((x,y), graph)

            pygame.display.flip()
            pygame.time.delay(FR)
    finally:
        quit()


if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

好吧,现在我在屏幕中间有一个大1 ...

我收到了这个错误,因为我在“init()”之前放了“BASICFONT =”...有时我不认为

现在我如何解决这个“1”问题?

from random import randrange, choice
import pygame
import sys
from pygame.locals import *

FR = 30
SIZE = 640, 480
BGCOLOR = (255,255,255)
NODECOLOR = (255,0,255)
NODESIZE = 25,25
GRIDSPACING = 50
MAXTRIES = 1000
STARTINGNODES = 4
TEXTCOLOR = (0,0,0)
BASICFONTSIZE = 20

class Graph(object):
    def __init__(self):
        self.nodes = set()
        # record positions of each node, so that we can check for overlaps
        self.positions = dict()

    def add(self, node):
        global count
        count = 0
        added = False
        # try to add node at some random location -
        while not added:
            x, y = (randrange(0, SIZE[0], GRIDSPACING),
                        randrange(0, SIZE[1], GRIDSPACING))
            if not (x,y) in self.positions:
                added = True
                self.nodes.add(node)
                node.setpos((x,y), self)
            count += 1
            if count >= MAXTRIES:
                raise ValueError("Could not alocate space for node representation")

    def update(self):
        SCREEN.fill(BGCOLOR)
        for node in self.nodes:
            pygame.draw.rect(SCREEN, node.color, node.rect)
            textSurf = BASICFONT.render(str(count), True, TEXTCOLOR)
            textRect = textSurf.get_rect()
            textRect.center = int(SIZE[0] / 2), int(SIZE[1] / 2)
            SCREEN.blit(textSurf, textRect)
            for neighbor in node.neighbors:
                pygame.draw.line(SCREEN, NODECOLOR,node.rect.center, neighbor.rect.center)

class Node(object):
    # Class variable, incremented with each
    # instance so that each node has a unique ID that
    # can be used as its hash:
    creation_counter = 0
    def __init__(self):
        self.id = self.__class__.creation_counter
        self.__class__.creation_counter += 1
        self.rect = None
        self.color = NODECOLOR
        self.neighbors = set()

    def setpos(self, pos, graph = None):
        if self.rect and graph:
            # remove self from previous position in the graph:
            graph.positions.pop(self.rect.topleft, None)
        self.rect = pygame.Rect(pos[0], pos[1],NODESIZE[0], NODESIZE[1])
        if graph:
            graph.positions[pos] = self

    def  __hash__(self):
        return self.id


def create_graph():
    # create new graph and populate nodes:
    graph = Graph()
    # locallist for adding neighbors:
    nodes = []
    print(nodes)
    for i in range(STARTINGNODES):
        node = Node()
        graph.add(node)
    return graph

def init():
    global SCREEN
    pygame.init()
    SCREEN = pygame.display.set_mode(SIZE)

def quit():
    pygame.quit()

def main():
    global BASICFONT

    graph = create_graph()
    selected = None
    try:
        init()
        BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE)
        while True:
            graph.update()
            pygame.event.pump()
            # Exit the mainloop at any time the "ESC" key is pressed
            if pygame.key.get_pressed()[pygame.K_ESCAPE]:
                break
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos
                    # round down x,y to multiples of NODESIZE
                    x -= x % NODESIZE[0]
                    y -= y % NODESIZE[1]
                    pygame.draw.rect(SCREEN, (0,0,255), (x,y) + NODESIZE)
                    if (x,y) in graph.positions:
                        node = graph.positions[x,y]
                        if selected:
                            print selected.id, node.id
                            if selected is node:
                                selected = None
                                node.color = NODECOLOR
                            elif selected not in node.neighbors:
                                selected.neighbors.add(node)
                                node.neighbors.add(selected)
                            else:
                                selected.neighbors.remove(node)
                                node.neighbors.remove(selected)
                        else:
                            node.color = (0,0,0)
                            selected = node
                    elif selected:
                        selected.setpos((x,y), graph)
                elif event.type == pygame.MOUSEMOTION and event.buttons[0] and selected:
                    x, y = event.pos
                    # round down x,y to multiples of NODESIZE
                    x -= x % NODESIZE[0]
                    y -= y % NODESIZE[1]
                    selected.setpos((x,y), graph)

            pygame.display.flip()
            pygame.time.delay(FR)
    finally:
        quit()


if __name__ == "__main__":
    main()