77
88
99class Game :
10+ """Manages the gameplay logic and its user interactions."""
1011 def __init__ (self ):
1112 self .display = Display ()
1213 self .snake = Snake ()
@@ -33,6 +34,11 @@ def game_loop(self):
3334 pygame .quit ()
3435
3536 def is_collision (self ):
37+ """Checks if the snake has collided with the boundary or with itself.
38+
39+ Returns:
40+ bool: True if a collision is detected, False otherwise.
41+ """
3642 # Snake hits boundary
3743 if (
3844 self .snake .head .x > self .display .width - self .snake .block_size
@@ -65,6 +71,7 @@ def get_user_input(self):
6571 self .snake .direction = Direction .DOWN
6672
6773 def play_step (self ):
74+ """Executes one step through the game."""
6875 self .get_user_input ()
6976 self .snake .move (self .snake .direction )
7077 if self .snake .head == self .food :
@@ -79,6 +86,7 @@ def play_step(self):
7986 return game_over , self .score
8087
8188 def place_food (self ):
89+ """Randomly places the food on the screen."""
8290 x = random .randint (0 , (
8391 self .display .width - GameSettings .BLOCK_SIZE ) // GameSettings .BLOCK_SIZE ) * GameSettings .BLOCK_SIZE
8492 y = random .randint (0 , (
@@ -88,6 +96,7 @@ def place_food(self):
8896 self .place_food ()
8997
9098 def play_again (self ):
99+ """Asks the user to play again or quit the game."""
91100 while True :
92101 for event in pygame .event .get ():
93102 if event .type == pygame .QUIT :
@@ -99,12 +108,14 @@ def play_again(self):
99108 return True
100109
101110 def restart_game (self ):
111+ """Resets the state of the game."""
102112 self .snake = Snake ()
103113 self .score = 0
104114 self .place_food ()
105115 self .high_score = self .load_high_score ()
106116
107117 def load_high_score (self ):
118+ """Loads the high score from a JSON file."""
108119 try :
109120 with open ('high_score.json' , 'r' ) as file :
110121 data = json .load (file )
@@ -113,6 +124,7 @@ def load_high_score(self):
113124 return 0
114125
115126 def update_high_score (self , new_score ):
127+ """Updates the high score in the JSON file if the new score is greater than the current high score."""
116128 high_score = self .load_high_score ()
117129 if new_score > high_score :
118130 data = {"high_score" : new_score }
0 commit comments