my Rect stays for 1 frame created in 'for in' loop Pygame

my Rect stays for 1 frame created in 'for in' loop Pygame

Content Index :

my Rect stays for 1 frame created in 'for in' loop Pygame
Tag : python , By : CodeOfficer
Date : November 29 2020, 04:01 AM

To fix this issue You need to somehow keep track of which rect you already clicked.
There are of course endless ways to do this. One way is to use a custom class instead of a simple Rect so we can easily keep track of the state of each "row".
import pygame

class Row:
    def __init__(self, rect):
        self.rect = rect
        self.clicked = False

def main():
    quit = False
    screen = pygame.display.set_mode((230, 230))
    clock = pygame.time.Clock()

    rows = [
        Row(pygame.Rect(10, 10, 100, 100)),
        Row(pygame.Rect(10, 120, 100, 100)),
        Row(pygame.Rect(120, 10, 100, 100)),
        Row(pygame.Rect(120, 120, 100, 100))

    while not quit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
            if event.type == pygame.MOUSEBUTTONDOWN:
                for row in (row for row in rows if row.rect.collidepoint(event.pos)):
                    row.clicked = True

        moupos = pygame.mouse.get_pos()
        for row in rows:
            if row.clicked:
                color = pygame.Color('orange')
                color = pygame.Color('green') if row.rect.collidepoint(moupos) else pygame.Color('dodgerblue')
            pygame.draw.rect(screen, color, row.rect)


if __name__ == '__main__':

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How do I test when Rect collides with Rect | Python | Pygame

Tag : python , By : Hadley
Date : March 29 2020, 07:55 AM
around this issue Store the two Rects as variables, and use pygame.Rect.colliderect() to test if they overlap.
For instance:
rect1 = Rect(0,0,100,100)
rect2 = Rect(90,90,100,100)

collideTest = rect1.colliderect(rect2)

pygame.draw.rect TypeError: Rect argument is invalid

Tag : python , By : stan
Date : March 29 2020, 07:55 AM
I wish did fix the issue. pygame.draw.rect() expects pygame.Rect() object not tuple (x, y, w, h)
So keep size and position as pygame.Rect()
self.rect = pygame.Rect()
self.rect.x = x
self.rect.y = y
self.rect.width = w
self.rect.height = h
self.rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(screen, black, self.rect, 4)

screen.blit(self.image, self.rect)
if self.rect.collidepoint(self.mouse):
if self.x+self.w > self.mouse[0] > self.x and self.y+self.h > self.mouse[1] > self.y:
self.textRect.center = self.rect.center
self.textRect.center = ( (self.x+int(self.w/2)), (self.y+int(self.h/2)) )

pygame.Rect.move_ip() not updating rect attribute

Tag : python , By : Paul McKee
Date : March 29 2020, 07:55 AM
Any of those help You've to traverse the snakes body in reverse order in the method movement. For each part of the body, copy the position of the previous part. The head part gets the current position of the snake:
class Snake(object):
    # [...]

    def movement(self):
        if self.direction == 'right':
            self.move = (self.speed,0)
        elif self.direction == 'left':
            self.move = (-self.speed,0)
        elif self.direction == 'up':
            self.move = (0,-self.speed)
        elif self.direction == 'down':
            self.move = (0,self.speed)


        for i in range(len(self.body)-1, 0, -1):
            self.body[i].rect.center = self.body[i-1].rect.center
        if self.body:
            self.body[0].rect.center = self.rect.center
class Snake(object):
    # [...]

    def add_segment(self,food):
        if len(self.body) == 0 or self.rect.colliderect(food.rect):
            snake_segment = Snake(GREEN,RECTANGLE_WIDTH,RECTANGLE_HEIGHT)
            snake_segment.rect.center = self.rect.center
class Snake(object):
    # [...]

    def draw_snake(self):
        for snake_segment in self.body:

Pygame draw rect following another rect based on their coordinates (ie snake game)

Tag : python , By : phatfish
Date : March 29 2020, 07:55 AM
should help you out You need a list of the snakes positions. The position of each element of the snake is an element of the list:
snakepos = [[startX, startY]]
for i in range(len(snakepos)-1, 0, -1):
    snakepos[i] = snakepos[i-1][:]
snakepos[0][0] += moveX
snakepos[0][1] += moveY
snakepos.insert(0, [snakepos[0]+moveX, snakepos[1]+moveY])
del snakepos[-1]
for i in range(1, len(snakepos)):
    pygame.draw.rect(screen, yellow, [snakepos[i], (width, height)])
snake = pygame.draw.rect(screen, white, [snakepos[0], (width, height)])

Pygame Rect center can't overwrite Rect's left

Tag : python , By : Atanas
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • need of maximum value in int
  • a list of several tuples, how to extract the same of the first two elements in the small tuple in the large tuple
  • Display image of 2D Sinewaves in 3D
  • how to prevent a for loop from overwriting a dictionary?
  • How To Fix: RuntimeError: size mismatch in pyTorch
  • Concatenating two Pandas DataFrames while maintaining index order
  • Why does this not run into an infinite loop?
  • Python Multithreading no current event loop
  • Element Tree - Seaching for specific element value without looping
  • Ignore Nulls in pandas map dictionary
  • How do I get scrap data from web pages using beautifulsoup in python
  • Variable used, golobal or local?
  • I have a regex statement to pull all numbers out of a text file, but it only finds 77 out of the 81 numbers in the file
  • How do I create a dataframe of jobs and companies that includes hyperlinks?
  • Detect if user has clicked the 'maximized' button
  • Does flask_login automatically set the "next" argument?
  • Indents in python 3
  • How to create a pool of threads
  • Pandas giving IndexError on one dataframe but not on another similar dataframe
  • Django Rest Framework - Testing client.login doesn't login user, ret anonymous user
  • Running dag without dag file in airflow
  • Filling across a specified dimension of a numpy array
  • Python populating dataframe in pandas from text files
  • How to interpolate a single ("non-piecewise") cubic spline from a set of data points?
  • Divide 2 integers (leetcode 29) - recursion issue
  • Can someone explain why do I get this output in Python?
  • How do I scrape pdf and html from search results without obvious url
  • Is there a way to automatically make a "collage" of plots with matplotlib?
  • How to combine multiple rows in pandas with shared column values
  • How do I get LOAD_CLASSDEREF instruction after dis.dis?
  • Django - How to add items to Bootstrap dropdown?
  • Linear Regression - Does the below implementation of ridge regression finding coefficient term using gradient method is
  • How to drop all rows in pandas dataframe with negative values?
  • Most Efficient Way to Find Closest Date Between 2 Dataframes
  • Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments
  • Looping through a function
  • Create a plot for each unique ID
  • a thread python with 'while' got another thread never start
  • Solution from SciPy solve_ivp contains oscillations for a system of first-order ODEs
  • trigger python events driven by selenium controlled browser
  • Passing line-edits to a contextmanager to set validators
  • Python: globals().items() iterations try to change a dict
  • Is it possible to specify starting values for each parameter (instead of bounds) for scipy's differential evolution?
  • why datetime.now() and constructed datetime using all fields(like year,month...) of now has big timedelta?
  • MySQL multiple table UPDATE query using sqlalchemy core?
  • find if a semantic version is superset of of another version python
  • Type checking against dynamically created objects
  • Struggling with simple reverse function
  • Is there a function for finding the midpoint of n points on sklearn.neighbors.NearestNeighbors?
  • How to set max number of tweets to fetch
  • PYTHON 3.7.4 NOT USING SQLITE 3.29.0
  • How to replace Nan value with zeros in a numpy array?
  • How to speed up calculating variance among sparse matrix
  • cupy code is not fast enough compared with numpy
  • How to count frequency of select values in Python pandas dataframe
  • Scrape Span Text from Google
  • Python watchdog, watch a directory and rename file on event.modification
  • Filtering rows in DataFrame with dependent conditions
  • How to check if a character is a not a part of number or URL in string?
  • Compare corresponding elements of a list
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com