How do I test when Rect collides with Rect | Python | Pygame
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
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)
self.rect.move_ip(self.move)
self.rect.clamp_ip(SCREEN.get_rect())
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
self.body.append(snake_segment)
class Snake(object):
# [...]
def draw_snake(self):
for snake_segment in self.body:
snake_segment.blit()
|
Pygame draw rect following another rect based on their coordinates (ie snake game)
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]]
snakepos.append(snakepos[-1][:])
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
Date : March 29 2020, 07:55 AM
|