Worm eats food
This is a post in the
Worm series.
Other posts in this series:
- May 02, 2023 - Basic Pygame game structure
- May 03, 2023 - Add grid lines and Kinematic objects
- May 21, 2023 - Creating and Moving our player
- May 22, 2023 - Worm eats food
- May 24, 2023 - Grid Movement
- May 30, 2023 - Screen wrap & Detect edges
Food
The food will be placed in a random position initially. When the worm head passes over it we simulate eating and placing new food by simply placing the food at a new position using random.
It is cheaper on resource space than destroying and re-creating the object as a new object.
import random
Change the way “GameObject” places itself.
def __init__(self, img_name, initial_pos):
self.img = pygame.image.load(img_name)
self.img = pygame.transform.scale_by(self.img, 0.5 )
self.rect = self.img.get_rect()
self.set_pos(initial_pos)
def set_pos(self, pos):
self.rect.center = pos
Create a food object that repositions not moves. We set it off-screen to start.
class Food(GameObject):
def __init__(self):
super().__init__("assets/food/tile_coin.png", (-1,-1))
def get_random_pos(self) -> tuple[int, int]:
x = random.randrange(0, int(width/40)) * 40 + 20
y = random.randrange(0, int(height/40)) * 40 + 20
return (x,y)
def reposition(self):
pos = self.get_random_pos()
self.set_pos(pos)
Then we create it immediately after creating the player
food = Food()
food.reposition()
Then we draw it immediately before the player draw as we want it to appear beneath when we eat it.
food.draw()
Eating food. I had to look at the docs for collisions
Place this code below the “player.move” in the game loop
if Rect.collidepoint( food.rect, player.rect.center ):
food.reposition()
see commit “worm eats food” in the source code repository mentioned at the start of this series.
I test the player center against the food rect.
To experiment you can try other things, like center against center and see if it works at faster speeds (placement of the character isn’t always on center at the end of move). Weird visual effects if you use rect to rect.
TIP: Try slowing the player down to 0.1 to see what is happening.
If you give it a play test you will see the food appear on a different tile each time we start the game, and then move to another random position when the center of player move over the food.
This method is far from perfect as you can place the food under the worm etc.
Next we need to implement grid movement.
Previous Next