-1

So, I'm making my first game in pygame, and have done OK up to this point. I've been looking at many tutorials but they only show me how to move the object using keys. I just can't make my object move randomly in random directions. Can I please get some help?

import pygame
import random

#create display
screen_h = 500
screen_w = 500

points = 0


bombplacex = random.randint(1,325)
bombplacey = random.randint(1,325)
strawplacex = random.randint(1,325)
strawplacey = random.randint(1,325)
pepperplacex = random.randint(1,325)
pepperplacey = random.randint(1,325)

screen = pygame.display.set_mode((screen_h, screen_w))
pygame.display.set_caption('Button')

# load button image
bomb_img = pygame.image.load('bomb.png').convert_alpha()
straw_img = pygame.image.load('strawberry-png.png').convert_alpha()
pepper_img = pygame.image.load('green pepper.png').convert_alpha()
# button class
class Button():
    def __init__(self, x, y, image, scale):
        width = image.get_width()
        height = image.get_height()
        self.image = pygame.transform.scale(image, (int(width * scale),int(height * scale)))
        self.rect = self.image.get_rect()
        self.rect.topleft = (x,y)
        self.clicked = False

    def draw(self):
        action = False

# get mouse position
        position = pygame.mouse.get_pos()

# check mouseover and click conditions
        if self.rect.collidepoint(position):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False:
                self.clicked = True
                action = True

        if pygame.mouse.get_pressed()[0] == 0:
            self.clicked = False

# draw button on screen
        screen.blit(self.image, (self.rect.x, self.rect.y))

        return action

# create button instances
bomb_button = Button(bombplacex, bombplacey, bomb_img, 0.25)
strawberry_button = Button( strawplacex, strawplacey, straw_img,0.15)
pepper_button = Button(pepperplacex,pepperplacey,pepper_img,0.15)

#game loop
run = True
while run:
    screen.fill((153, 50, 204))
# if the bomb is clicked the game will end and if the strawberry is clicked a point will be added.

    if bomb_button.draw() == True:
        print('GAME OVER')
        run = False
    elif strawberry_button.draw() == True:
        points = points + 1
        print('You have',points,'points')
    elif pepper_button.draw() == True:
        points = points + 1
        print('You have',points,'points')

#event handler
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    pygame.display.update()
pygame.quit()
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • 1
    You have a loop updating everything on each iteration, just increase/decrease your character's coordinates randomly here – Marius ROBERT Jun 06 '22 at 13:24

1 Answers1

0

You're close to implementing your own Sprite class. You should subclass the PyGame sprite and use sprite Groups, it will make your life easier and is worth the investment.

A sprite needs an update() function that is called each game loop iteration so that's where your movement logic would need to be. If wanted to adjust the x and y positions by a random amount you could do something like:

class ShiftyBlock(pygame.sprite.Sprite):
    def __init__(self, size, pos):
        pygame.sprite.Sprite.__init__(self)
        self.size = size
        self.image = pygame.Surface([size[0], size[1]])
        self.image.fill(pygame.color.Color("blueviolet"))
        self.rect = self.image.get_rect()
        self.rect[0] = pos[0]
        self.rect[1] = pos[1]
        
    def update(self):
        """ shift randomly - Note doesn't check screen boundaries"""
        self.rect.x += random.randint(-5,5)
        self.rect.y += random.randint(-5,5)

But perhaps this isn't the random movement you're after.

Here's a block that starts going in a random direction when created and only changes when it bounces off a wall.

class BouncyBlock(pygame.sprite.Sprite):
    def __init__(self, size, pos):
        pygame.sprite.Sprite.__init__(self)
        self.size = size
        self.image = pygame.Surface([size[0], size[1]])
        self.image.fill(pygame.color.Color("darkgreen"))
        self.rect = self.image.get_rect()
        self.rect[0] = pos[0]
        self.rect[1] = pos[1]
        # initialise speed on creation
        self.speedx = random.randint(-5, 5)
        self.speedy = random.randint(-5, 5)

    def update(self):
        # simplistic bounds checking
        width, height = screen.get_size()
        if not 0 < self.rect.x < width:
            self.speedx *= -1 # reverse direction
        self.rect.x += self.speedx

        if not 0 < self.rect.y < height:
            self.speedy *= -1 # reverse direction
        self.rect.y += self.speedy

These sprites will look like:

moving blocks

Full example code:

import pygame
import random

screen = pygame.display.set_mode((500,500))
pygame.init()
sprite_list = pygame.sprite.Group()


class ShiftyBlock(pygame.sprite.Sprite):
    def __init__(self, size, pos):
        pygame.sprite.Sprite.__init__(self)
        self.size = size
        self.image = pygame.Surface([size[0], size[1]])
        self.image.fill(pygame.color.Color("blueviolet"))
        self.rect = self.image.get_rect()
        self.rect[0] = pos[0]
        self.rect[1] = pos[1]

    def update(self):
        """ shift randomly - Note doesn't check screen boundaries"""
        self.rect.x += random.randint(-5,5)
        self.rect.y += random.randint(-5,5)

class BouncyBlock(pygame.sprite.Sprite):
    def __init__(self, size, pos):
        pygame.sprite.Sprite.__init__(self)
        self.size = size
        self.image = pygame.Surface([size[0], size[1]])
        self.image.fill(pygame.color.Color("darkgreen"))
        self.rect = self.image.get_rect()
        self.rect[0] = pos[0]
        self.rect[1] = pos[1]
        # initialise speed on creation
        self.speedx = random.randint(-5, 5)
        self.speedy = random.randint(-5, 5)

    def update(self):
        # simplistic bounds checking
        width, height = screen.get_size()
        if not 0 < self.rect.x < width:
            self.speedx *= -1 # reverse direction
        self.rect.x += self.speedx

        if not 0 < self.rect.y < height:
            self.speedy *= -1 # reverse direction
        self.rect.y += self.speedy

for _ in range(5):
    block = ShiftyBlock((80,random.randint(40,100)), (random.randint(100,400),random.randint(100,400)))
    sprite_list.add(block)

for _ in range(4):
    block = BouncyBlock((80,random.randint(40,100)), (random.randint(100,400),random.randint(100,400)))
    sprite_list.add(block)

run = True
clock = pygame.time.Clock()
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    screen.fill(pygame.Color("white"))
    sprite_list.update()
    sprite_list.draw(screen)
    pygame.display.update()
    clock.tick(60)  # limit to 60 FPS

pygame.quit()
import random
  • 3,054
  • 1
  • 17
  • 22