I'm new to OOP and trying to get the gist of using Classes and Methods. In this particular case, I've used a class to create two red nodes and managed to use MOUSEBUTTONDOWN with my class.
However, when I try to use a MOUSEBUTTONDOWN event to draw a line, nothing seems to happen. I've
used test print statements in multiple places to ensure that I'm "reaching" my class and that
the method is executing. Nothing, however, can seem to make my red line appear.
I've also moved the draw statement out of the method to near the end of my game loop and it appears correctly.
What am I misunderstanding about classes and methods?
import pygame
class Rnode():
def __init__(self, x, y, image_rednode):
self.x = x
self.y = y
self.image_rednode = image_rednode
self.rect = self.image_rednode.get_rect()
self.rect.topleft = (x, y)
self.clicked = False
self.wired = False
# draw node line
def put(self):
screen.blit(self.image_rednode, (self.x, self.y))
#get mouse position
pos = pygame.mouse.get_pos()
#check mouseover and clicked
if self.rect.collidepoint(pos):
if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
self.clicked = True
print('gotcha' + str(self))
self.wired = True
if pygame.mouse.get_pressed()[0] == 0:
self.clicked = False
def draw_line(self):
if pygame.mouse.get_pressed()[0]:
self.pos = pygame.mouse.get_pos()
pygame.draw.line(screen,red,(self.x + 15, self.y + 15),(self.pos), 3)
# these are the colors
green = (48, 141, 70)
grey = (211, 211, 211)
lime = (201, 223, 202)
purplish = (116,137,192)
orange = (234,168,0)
brown = (59,47,47)
blue = (0,91,150)
red = (255,8,0)
screen = pygame.display.set_mode((1280, 720))
pygame.display.set_caption('Classy, Baby!')
running = 1
xb = pygame.image.load(r'xb7white.png').convert_alpha()
rednode = pygame.image.load('redhole.svg').convert_alpha()
rednode = pygame.transform.scale(rednode, (100, 100))
# make node instances
r1 = Rnode(300, 300, rednode)
r2 = Rnode(500, 300, rednode)
while running:
screen.fill((0, 0, 0))
event = pygame.event.poll()
if event.type == pygame.QUIT:
running = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
# if event.type == pygame.MOUSEBUTTONDOWN: # if the user pressed a mouse button
# pos = pygame.mouse.get_pos() # get the mouse pos
# if g1.rect.collidepoint(pos):
r1.put()
r2.put()
if r1.wired:
r1.draw_line()
pygame.display.flip()
