How to Add Randomly Moving Objects Using Python's Arcade Library

Make your arcade game more fun by adding randomly moving objects. Here are detailed instructions.

But randomly moving objects can bring interesting and unpredictable to the game. It makes them more engaging and challenging. Python's Arcade library provides a simple and efficient way to combine randomly moving objects in the game.

Create a simple game

Before you start, make sure you have pip installed on your device. Use this command to install the arcade library:

pip install arcade

Then create a window using the class arcade.Window and set the background color to white.

Position the player in the center of the screen horizontally and add a small gap at the top. You can control the player's movements with the arrow keys.

Here is the basic game code in this example:

import arcade SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 PLAYER_RADIUS = 15 class MyGame(arcade.Window): def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.WHITE) self.player_x = SCREEN_WIDTH // 2 self.player_y = PLAYER_RADIUS + 10 def on_draw(self): arcade.start_render() arcade.draw_circle_filled(self.player_x, self.player_y, PLAYER_RADIUS, arcade.color.BLUE) def update(self, delta_time): pass def on_key_press(self, key, modifiers): if key == arcade.key.LEFT: self.player_x -= 5 elif key == arcade.key.RIGHT: self.player_x += 5 if __name__ == "__main__": game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT) arcade.run()

More objects

To add random moving objects to the game, create a list containing the objects' locations and update them every frame. You can also use sprites as objects.

In the game code, add a list of object names containing the positions of randomly moving objects. Then generate number of objects ( NUM_OBJECTS ) with random x and y coordinates in lines that enclose the screen. This object is drawn in a red circle using the arcade.draw_circle_filled function .

import arcade import random SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 PLAYER_RADIUS = 15 OBJECT_RADIUS = 10 NUM_OBJECTS = 10 class MyGame(arcade.Window): def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.WHITE) self.player_x = SCREEN_WIDTH // 2 self.player_y = PLAYER_RADIUS + 10 self.objects = [] for _ in range(NUM_OBJECTS): x = random.randint(0, SCREEN_WIDTH) y = random.randint(0, SCREEN_HEIGHT) self.objects.append((x, y)) def on_draw(self): arcade.start_render() arcade.draw_circle_filled(self.player_x, self.player_y, PLAYER_RADIUS, arcade.color.BLUE) for obj in self.objects: x, y = obj arcade.draw_circle_filled(x, y, OBJECT_RADIUS, arcade.color.RED) def update(self, delta_time): pass def on_key_press(self, key, modifiers): if key == arcade.key.LEFT: self.player_x -= 5 elif key == arcade.key.RIGHT: self.player_x += 5 if __name__ == "__main__": game = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT) arcade.run()

Result:

How to Add Randomly Moving Objects Using Python's Arcade Library Picture 1How to Add Randomly Moving Objects Using Python's Arcade Library Picture 1

Random motion algorithm implementation

To make objects move randomly, update their position in the update method using a random movement algorithm.

Loop through each object and generate random values ​​for dx and dy , representing the change in the x and y coordinates . Then update the position of the object by adding these values. Here is the edited code:

def update(self, delta_time): for i in range(NUM_OBJECTS): x, y = self.objects[i] dx = random.randint(-5, 5) dy = random.randint(-5, 5) x += dx y += dy self.objects[i] = (x, y)

Result:

How to Add Randomly Moving Objects Using Python's Arcade Library Picture 2How to Add Randomly Moving Objects Using Python's Arcade Library Picture 2

The object moves towards the player

To add more interaction, make the object move towards the player. You can achieve this by calculating the direction vector between the object and the player, and adjusting the position of the object accordingly.

To do this, calculate the difference in x & y coordinates between the object and the player. By normalizing these data, you have a direction vector. Then multiply this vector by the speed factor (3 in the example) and add it to the object's position. This is the update method that is updated.

def update(self, delta_time): for i in range(NUM_OBJECTS): x, y = self.objects[i] dx = self.player_x - x dy = self.player_y - y distance = math.sqrt(dx ** 2 + dy ** 2) dx /= distance dy /= distance x += dx * 3 y += dy * 3 self.objects[i] = (x, y)

Result:

How to Add Randomly Moving Objects Using Python's Arcade Library Picture 3How to Add Randomly Moving Objects Using Python's Arcade Library Picture 3

 

Objects begin to move when the player enters the surrounding area

To add impetus, edit the code so that the object starts moving only when the player enters the surrounding area. Add code for player movement and define radius for active object.

def update(self, delta_time): for i in range(NUM_OBJECTS): x, y = self.objects[i] dx = self.player_x - x dy = self.player_y - y distance = math.sqrt(dx ** 2 + dy ** 2) if distance < 100: # Adjust the radius as needed dx /= distance dy /= distance x += dx * 3 y += dy * 3 self.objects[i] = (x, y)

Collision detection and interaction

Now adds player-object collision detection and determines behavior when a collision occurs. Edit the update method to handle collisions:

def update(self, delta_time): for i in range(NUM_OBJECTS): x, y = self.objects[i] dx = self.player_x - x dy = self.player_y - y distance = math.sqrt(dx ** 2 + dy ** 2) if distance < PLAYER_RADIUS + OBJECT_RADIUS: # if collision occurred, handle it here self.objects.pop(i) self.objects.append((random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT))) elif distance < 100: dx /= distance dy /= distance x += dx * 3 y += dy * 3 self.objects[i] = (x, y)

Random balance

To create a balanced gameplay experience, it's important that you tweak the random movement and appearance of objects. Here are some examples of how you can tweak the code to achieve better balance in the game:

Limit the maximum speed

To prevent the subject from moving too fast, you can introduce a maximum speed limit. Edit the update method to include speed limits:

 for i in range(NUM_OBJECTS): x, y = self.objects[i] dx = self.player_x - x dy = self.player_y - y distance = math.sqrt(dx ** 2 + dy ** 2) if distance < PLAYER_RADIUS + OBJECT_RADIUS: self.objects.pop(i) self.objects.append((random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT))) elif distance < 100: dx /= distance dy /= distance speed = 3 # Adjust the speed value as needed dx = min(max(dx * speed, -MAX_SPEED), MAX_SPEED) dy = min(max(dy * speed, -MAX_SPEED), MAX_SPEED) x += dx y += dy self.objects[i] = (x, y)

Control the spawn rate

You can also control the rate at which new objects appear in the game. Adjust the code to include a delay between the creation of new objects:

import time class MyGame(arcade.Window): def __init__(self, width, height): super().__init__(width, height) arcade.set_background_color(arcade.color.WHITE) self.player_x = SCREEN_WIDTH // 2 self.player_y = PLAYER_RADIUS + 10 self.objects = [] self.last_spawn_time = time.time() def update(self, delta_time): # control the spawning rate here if time.time() - self.last_spawn_time > SPAWN_DELAY: if len(self.objects) < MAX_OBJECTS: self.objects.append((random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT))) self.last_spawn_time = time.time() for i in range(len(self.objects)): x, y = self.objects[i] dx = self.player_x - x dy = self.player_y - y distance = math.sqrt(dx ** 2 + dy ** 2) if distance < PLAYER_RADIUS + OBJECT_RADIUS: self.objects.pop(i) self.objects.append((random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT))) elif distance < 100: dx /= distance dy /= distance x += dx * 3 y += dy * 3 self.objects[i] = (x, y)

Adjust the SPAWN_DELAY and MAX_OBJECTS values ​​to find the right balance for the game. A long delay or a smaller maximum number of objects will make the game less crowded. Conversely, a shorter delay or a larger maximum number of objects will increase the difficulty of the game.

Here's how to add random moving objects to a game created with Python . Hope the article is useful to you.

5 ★ | 1 Vote