【问题标题】:Python and Pygame Loops not incrementingPython 和 Pygame 循环不递增
【发布时间】:2020-10-16 17:24:38
【问题描述】:

对不起,如果这是一个非常愚蠢的问题,但我是一个初学者,正在尝试使用 Python 和 Pygame 编写一个小游戏。

我正在尝试将屏幕上的可能位置数组与用户鼠标位置进行比较,方法是创建一个def get_square_under_mousex() ,然后使用 for 循环遍历数组的每个成员,直到找到匹配项。

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

当我为 x 和 y 运行程序时,我的 for 循环都不会超过 1,我有一种感觉,这与在循环可以超过 1 之前的主循环有关,但我没有知道如何解决这个问题,或者这就是问题所在。

另外,当我运行游戏时,无论是否点击鼠标,精灵都会移动,并且当我移动鼠标时,精灵会四处移动,但只会在数组中匹配 1 的坐标内移动。

非常感谢任何帮助指出我正确的方向,如果这是愚蠢的,对不起。

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

【问题讨论】:

    标签: python python-3.x pygame


    【解决方案1】:

    return 的缩进是错误的。 return 将在第一次循环迭代后执行。我建议将代码更改如下。

    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。你不考虑从0开始的正方形,对吗?或者POSITIONx1POSITIONy1应该是

    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]
    

    同样,您可能想要解决正方形的最远端。

    【讨论】:

    • 非常感谢这项工作!我只需要将POSITIONy1[i] &lt;= x &lt; POSITIONy1[i+1] 更改为POSITIONx1[i] &lt;= x &lt; POSITIONx1[i+1]
    • 那么对于if not pygame.MOUSEBUTTONUP return -1,-1 是否只是重新启动循环?
    • 我用 -1 表示出现问题。您可以使用其他值,例如 None 或 -2 来指定究竟出了什么问题——这取决于上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多