【问题标题】:pygame text in rect ERROR矩形错误中的pygame文本
【发布时间】:2017-10-20 21:56:22
【问题描述】:

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

"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()

【问题讨论】:

    标签: python user-interface graph pygame


    【解决方案1】:

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

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

    现在我如何解决这个“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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-19
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多