Friday, December 15, 2023

Unique

 Worked through the Codemy tuto for this week. Learning how

to generate multiple Sprites. These use the draw(0 function to go

to the screen.

                                                       


Asked Chatgpt for unique sprite positions; got the following code:

import random
import pygame

class Sprite(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color):
        super().__init__()
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.rect = pygame.Rect(x, y, width, height)

    def update(self):
        pass

sprite_group = pygame.sprite.Group()
used_positions = set()

for i in range(5):
    while True:
        x = random.randrange(0, 800, 30)
        y = random.randrange(0, 600, 30)
        if (x, y) not in used_positions:
            used_positions.add((x, y))
            break
    sprite = Sprite(x, y, 30, 30, (255, 0, 0))
    sprite_group.add(sprite)

# Example usage
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    sprite_group.update()
    sprite_group.draw(window)
    pygame.display.flip()

It's actually very clever. A set can never have any repeats!!

                                                 *     *     *

Not sure about this approach...


                                                                                     


                                                                          *     *     *
Do I believe in magic?? A little checking showed me that my code - above - was

only doing half the job ie adding a new value to the set. My new code - yo Chatgpt - 

does it all:

                                                                                

                                                                               

No comments: