Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära Setting a Game | Snake Game
Building a Classic Snake Game

book
Setting a Game

Initializing the Game

Our goal is to set up the initial conditions and parameters necessary for managing the game state and its various elements.

To kickstart the development of our Snake Game, we need to establish the Game class. This class will serve as the central hub for managing the game's state and orchestrating interactions between its components. Let's delve into the initialization process:

Parameter
Description
FieldSpecifies the dimensions of the game field, forming the grid where the 🐍 and 🍎 move.
SpeedDetermines the rate at which the game progresses ⏩.
RunningIndicates whether the game is currently active 🏃‍♂️.

Field, speed and running

In our Snake and Fruit classes, we've frequently referenced a field variable. Now, it's crucial to incorporate the field upon which other variables rely. This field will be passed as a parameter, allowing us to customize the game field size as needed. However, the default dimensions will be set to (15, 15), meaning there are 15 rows and 15 columns.

The speed attribute dictates the rate at which our game updates, while the running attribute indicates whether the game is currently running smoothly and if the snake is still alive. If the snake dies, the running attribute will be set to false. We'll implement this functionality later.

Snake and Fruit variables

We will add snake and a fruit that we carefully shaped before

py
self.fruit = Fruit(
field = self.field,
sprite = 'x'
)

self.snake = Snake(
field = self.field,
sprite = '*'
)

As you can see, the process is quite straightforward, owing to the classes we've created. You have the freedom to adjust the symbols representing the snake's body and fruit to align with your preferences.

Note

With these parameters, we've created a versatile version of the Snake Game. You can use frameworks to enhance graphics, add sound effects, or introduce multiplayer functionality. The modular design allows easy integration of new features, empowering you to customize the game to your liking.

Uppgift

Swipe to start coding

  • Define Game class.
  • Implement __init__ for the game class.

Lösning

class Game:
def __init__(self, field=(15,15), speed=0.1):
self.field = field
self.speed = speed
self.running = True

self.fruit = Fruit(
field = self.field,
sprite = 'x'
)

self.snake = Snake(
field = self.field,
sprite = '*'
)

Mark tasks as Completed
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 8

Fråga AI

expand
ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

some-alt