1- import pygame
21import turtle
32import time
43from constants import SCREEN_WIDTH , SCREEN_HEIGHT , COLLISION_DISTANCE , SLEEP_TIME
54from snake import Snake
65from food import Food
76from scoreboard import Scoreboard
87
8+ try :
9+ import pygame
10+ pygame_installed = True
11+ except ImportError :
12+ pygame_installed = False
13+ print ("⚠️ Warning: pygame module not found. Game will run without sound effects." )
914
1015class SnakeGame :
1116 def __init__ (self ):
@@ -29,9 +34,15 @@ def __init__(self):
2934 self .scoreboard = Scoreboard ()
3035
3136 # Sound setup
32- pygame .mixer .init ()
33- self .eat_sound = pygame .mixer .Sound ("sounds/Apple_Eating.mp3" )
34- self .gameover_sound = pygame .mixer .Sound ("sounds/Game_over.mp3" )
37+ self .pygame_installed = pygame_installed
38+ if self .pygame_installed :
39+ try :
40+ pygame .mixer .init ()
41+ self .eat_sound = pygame .mixer .Sound ("sounds/Apple_Eating.mp3" )
42+ self .gameover_sound = pygame .mixer .Sound ("sounds/Game_over.mp3" )
43+ except Exception as e :
44+ print (f"⚠️ Warning: Could not initialize pygame mixer: { e } " )
45+ self .pygame_installed = False
3546
3647 # Keyboard bindings
3748 self .screen .listen ()
@@ -83,7 +94,8 @@ def run(self):
8394
8495 # Boundary collision
8596 if self .snake .check_boundary_collision ():
86- self .gameover_sound .play ()
97+ if self .pygame_installed :
98+ self .gameover_sound .play ()
8799 self .snake .reset ()
88100 self .scoreboard .reset ()
89101 self .delay = SLEEP_TIME
@@ -95,7 +107,8 @@ def run(self):
95107 self .snake .add_part ()
96108
97109 self .scoreboard .increase ()
98- self .eat_sound .play ()
110+ if self .pygame_installed :
111+ self .eat_sound .play ()
99112
100113 # Level system
101114 if self .scoreboard .score % 5 == 0 :
@@ -113,7 +126,8 @@ def run(self):
113126
114127 # Self collision
115128 if self .snake .check_self_collision ():
116- self .gameover_sound .play ()
129+ if self .pygame_installed :
130+ self .gameover_sound .play ()
117131 self .snake .reset ()
118132 self .scoreboard .reset ()
119133 self .delay = SLEEP_TIME
0 commit comments