Python and Pygame Loops not incrementing

Viewed 47

Sorry if this is a really dumb question, but I'm a beginner and trying to code a little game with Python and Pygame.

I'm trying to compare an array of possible positions on the screen to the users mouse position, by creating a def get_square_under_mousex() then looping through each member of the array using a for loop until it finds a match.

def get_square_under_mousex():
    j= 0
    if pygame.MOUSEBUTTONUP:
        x, y = pygame.mouse.get_pos()
        for i in range(0, 14):
            if POSITIONy1[i] < x < POSITIONy1[i+1]:
                return i
            else:
                i+=1
                print("this is x", POSITIONx1[i])
            return i

def get_square_under_mousey():
    j = 0
    if pygame.MOUSEBUTTONUP:
        x, y = pygame.mouse.get_pos()
        for j in range(0, 9):
            if POSITIONy1[j] < y < POSITIONy1[j+1]:
                return j
            else:
                j+=1
                print("this is y",POSITIONy1[j])
            return j

When I run the program both of my for loops for x and y never get above 1, I have a feeling that it has to do with the main looping over it before the loop can get above 1, but I don't know how to fix that or if that's even what the problem is.

Also, when I run the game, the sprite moves regardless of the mouse being clicked or not and will move around when i move the mouse but only within the coordinates that match 1 in the array.

Any help would be much appreciated to point me in the right direction, sorry if this is stupid.

import pygame
import os
import time

pygame.init()

#asset folder
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')

#Variables
WHITE = ( 255, 255, 255)
BLACK = (35, 39, 42)
drag = 0
position1 = 0
position2 = 0
width = 600
height = 800 
POSITIONx1 = [75, 123, 171, 219, 267, 315, 363, 411, 459, 507, 555, 603, 651, 699, 747]
POSITIONy1 = [175, 223, 271, 319, 367, 415, 463, 511, 559, 607]

print(POSITIONy1[1])
x1 = 75
x2 = 730
y1 = 175
y2 = 580

#change highlighting positions to creating grid on floor for possible spaces,
#instead highlight the sprite

#Game Window
size = (height, width)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("THE HARVESTOR")

#Sprite(1)
plant_img1 = pygame.image.load(os.path.join(img_folder, 'plant1.png')).convert_alpha()
plant_img2 = pygame.image.load(os.path.join(img_folder, 'plant2.png')).convert_alpha()
plant_img3 = pygame.image.load(os.path.join(img_folder, 'plant3.png')).convert_alpha()
desk_img = pygame.image.load(os.path.join(img_folder, 'background.png')).convert_alpha()
outline_img = pygame.image.load(os.path.join(img_folder, 'outline.png')).convert_alpha()
background = pygame.transform.scale(desk_img, (800, 800))

# The loop will carry on until the user exit the game (e.g. clicks the close button).
carryOn = True

# The clock will be used to control how fast the screen updates
all_sprites = pygame.sprite.Group()

def get_square_under_mousex():
   j= 0
   if pygame.MOUSEBUTTONUP:
       x, y = pygame.mouse.get_pos()
       for i in range(0, 14):
           if POSITIONy1[i] < x < POSITIONy1[i+1]:
               return i
           else:
               i+=1
               print("this is x", POSITIONx1[i])
           return i

def get_square_under_mousey():
   j = 0
   if pygame.MOUSEBUTTONUP:
       x, y = pygame.mouse.get_pos()
       for j in range(0, 9):
           if POSITIONy1[j] < y < POSITIONy1[j+1]:
               return j
           else:
               j+=1
               print("this is y",POSITIONy1[j])
           return j

class plant(pygame.sprite.Sprite):
   layer = 1
   def __init__(self, width, height):
       pygame.sprite.Sprite.__init__(self)
       self.image = pygame.Surface((width,height))
       self.images = []
       self.images.append(plant_img1)
       self.images.append(plant_img2)
       self.images.append(plant_img3)
       self.index = 0
       self.image = self.images[self.index]
       self.rect = pygame.Rect(5, 5, 48, 48)
       self.image = pygame.transform.scale(self.image, (120, 120))
       self.rect = self.image.get_rect()
       #self.rect.center = (800 / 2, 600 / 2)  
       all_sprites.add(self, layer = self.layer)   

   def update(self):
       if (drag == 1):
           self.rect.center = pygame.mouse.get_pos()
       if (position1 == 1):
           self.rect = self.image.get_rect()
           self.rect.y = POSITIONy1[get_square_under_mousey()] #UPDATED PLANT PLACEMENT AFTER TOUCHING OUTLINE
           #print(self.rect.y)
           self.rect.x = POSITIONx1[get_square_under_mousex()]
           #print(self.rect.x)
       if (position1 == 2):
           self.rect = self.image.get_rect()
           self.rect.y = 450 #MISSED OUTLINE PLACEMENT
           self.rect.x = 50

class outline(pygame.sprite.Sprite):
   layer = 2
   def __init__(self):
       pygame.sprite.Sprite.__init__(self)
       self.image = pygame.Surface((width,height))
       self.image = outline_img
       self.image = pygame.transform.scale(self.image, (120, 120))
       self.rect = self.image.get_rect()
       self.rect.y = 190 #OUTLINE POSITION
       self.rect.x = 340
       all_sprites.add(self, layer = self.layer)

   def update(self):
       1 == 1

clock = pygame.time.Clock()

all_sprites = pygame.sprite.LayeredUpdates()

plant = plant(50, 50)
outline = outline()
all_sprites.add(plant)

# -------- Main Program Loop -----------
while carryOn:
   # --- Main event loop
   spritegroup = pygame.sprite.RenderPlain()
   clock = pygame.time.Clock()
  
  # --- getting mouse pos ----
   x, y = pygame.mouse.get_pos()
   #print(x, y)
   
   all_sprites.update()
   screen.fill(BLACK)
   screen.blit(background, (0,0))
   
   all_sprites.draw(screen)

   # ---- EVENT LOOP ---
   for event in pygame.event.get(): # User did something
       if event.type == pygame.QUIT: # If user clicked close
           pygame.quit()
           carryOn = False # Flag that we are done so we exit this loop
       if event.type == pygame.MOUSEBUTTONDOWN:
           if plant.rect.collidepoint(pygame.mouse.get_pos()):
               all_sprites.add(outline)
               outline.rect.collidepoint(pygame.mouse.get_pos())
               drag = 1
               position1 = 0
       if event.type == pygame.MOUSEBUTTONUP:
           if plant.rect.collidepoint(pygame.mouse.get_pos()):
               position1 = 1
               #print("true")
               drag = 0
               outline.kill()
       #elif event.type == pygame.MOUSEBUTTONUP:
       #   if plant.rect.collidepoint(pygame.mouse.get_pos()):
       #       position1 = 2
       #       drag = 0
       #   outline.kill()

   pygame.display.update()```
1 Answers

Your indent with return is wrong. return will be executed after the first loop iteration. I suggest to change the code as follows.

def get_square_under_mousex():
    if not pygame.MOUSEBUTTONUP:
        return -1

    x, y = pygame.mouse.get_pos()
    for i in range(0, 14):
        if POSITIONy1[i] <= x < POSITIONy1[i+1]:
            return i

    # if the position was not found
    return -1

def get_square_under_mousey():
    if not pygame.MOUSEBUTTONUP:
        return -1 # code for not satisfying this condition

    x, y = pygame.mouse.get_pos()
    for j in range(0, 9):
        if POSITIONy1[j] <= y < POSITIONy1[j+1]:
            return j
    
    # if the position was not found
    return -1

UPD. You don't consider the squares that start from 0, is it correct? Or should POSITIONx1 and POSITIONy1 be

POSITIONx1 = [0, 75, 123, 171, 219, 267, 315, 363, 411, 459, 507, 555, 603, 651, 699, 747]
POSITIONy1 = [0, 175, 223, 271, 319, 367, 415, 463, 511, 559, 607]

Similarly, you may want to address the furthest end of squares.

Related