From 68cbdec46a4d7fbbd4d246a611054c9477ef6d4c Mon Sep 17 00:00:00 2001 From: ran4om Date: Sun, 15 Mar 2026 10:23:54 +0100 Subject: [PATCH] Fix pygame examples for Python 3 compatibility - snake.py: Fix integer division (//) - snake2.py: Fix integer division and variable naming bug in check_eat_blueberry - lunarlander.py: Fix Python 2 syntax, add fallback graphics for missing images --- lunarlander.py | 173 ++++++++++++++++++++++++++++++------------------- snake.py | 67 +++++++++++-------- snake2.py | 114 +++++++++++++++++--------------- 3 files changed, 209 insertions(+), 145 deletions(-) diff --git a/lunarlander.py b/lunarlander.py index 85d20f7..09d1b57 100644 --- a/lunarlander.py +++ b/lunarlander.py @@ -8,56 +8,60 @@ import math from pygame.locals import RLEACCEL, QUIT, K_r, K_SPACE, K_UP, K_LEFT, K_RIGHT -#from pygame.locals import * +# from pygame.locals import * FPS = 80 pygame.init() -fpsClock=pygame.time.Clock() +fpsClock = pygame.time.Clock() SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600 -ARENA_WIDTH, ARENA_HEIGHT = 10 * SCREEN_WIDTH, 10 * SCREEN_HEIGHT +ARENA_WIDTH, ARENA_HEIGHT = 10 * SCREEN_WIDTH, 10 * SCREEN_HEIGHT screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) surface = pygame.Surface(screen.get_size()) surface = surface.convert() -surface.fill((255,255,255)) +surface.fill((255, 255, 255)) clock = pygame.time.Clock() pygame.key.set_repeat(1, 1) -def load_image(name, colorkey=None): - fullname = os.path.join('lunarlander', name) + +def load_image(name, colorkey=None, fallback_color=(200, 200, 200)): + fullname = os.path.join("lunarlander", name) try: image = pygame.image.load(fullname) - except pygame.error, message: - print 'Cannot load image:', fullname - raise SystemExit(message) + except pygame.error as message: + print("Cannot load image:", fullname, "- using fallback") + image = pygame.Surface((50, 50), pygame.SRCALPHA) + pygame.draw.polygon(image, fallback_color, [(25, 0), (50, 50), (0, 50)]) image = image.convert() if colorkey is not None: if colorkey is -1: - colorkey = image.get_at((0,0)) + colorkey = image.get_at((0, 0)) image.set_colorkey(colorkey, RLEACCEL) return image, image.get_rect() + class V(object): """ A simple class to keep track of vectors, including initializing from Cartesian and polar forms. """ + def __init__(self, x=0, y=0, angle=None, magnitude=None): self.x = x self.y = y - if (angle is not None and magnitude is not None): + if angle is not None and magnitude is not None: self.x = magnitude * math.sin(math.radians(angle)) self.y = magnitude * math.cos(math.radians(angle)) @property def magnitude(self): - return math.sqrt(self.x ** 2 + self.y ** 2) - + return math.sqrt(self.x**2 + self.y**2) + @property def angle(self): if self.y == 0: @@ -80,27 +84,36 @@ def rotate(self, angle): self.y = self.x * s + self.y * c def __str__(self): - return "X: %.3d Y: %.3d Angle: %.3d degrees Magnitude: %.3d" % (self.x, self.y, self.angle, self.magnitude) + return "X: %.3d Y: %.3d Angle: %.3d degrees Magnitude: %.3d" % ( + self.x, + self.y, + self.angle, + self.magnitude, + ) + class Lander(pygame.sprite.DirtySprite): """ Our intrepid lunar lander! """ + def __init__(self): - self.image, self.rect = load_image('lander.jpg', -1) - + self.image, self.rect = load_image("lander.jpg", -1, (200, 200, 200)) + self.original = self.image - self.original_flame, self.flame_rect = load_image('lander_flame.jpg', -1) - + self.original_flame, self.flame_rect = load_image( + "lander_flame.jpg", -1, (255, 100, 0) + ) + self.mass = 10 - self.orientation = 0.0 # - self.rect.topleft = ((SCREEN_WIDTH / 2), 20) # The starting point. - self.engine_power = 2 # The power of the engine. - self.velocity = V(0.0,0.0) # Starting velocity. - self.landed = False # Have we landed yet? - self.intact = True # Is the ship still shipshape? - self.fuel = 100 # Units of fuel - self.boosting = 0 # Are we in "boost" mode? (show the flame graphic) + self.orientation = 0.0 # + self.rect.topleft = ((SCREEN_WIDTH // 2), 20) # The starting point. + self.engine_power = 2 # The power of the engine. + self.velocity = V(0.0, 0.0) # Starting velocity. + self.landed = False # Have we landed yet? + self.intact = True # Is the ship still shipshape? + self.fuel = 100 # Units of fuel + self.boosting = 0 # Are we in "boost" mode? (show the flame graphic) return super(pygame.sprite.DirtySprite, self).__init__() def update_image(self): @@ -120,9 +133,10 @@ def rotate(self, angle): def boost(self): """ - Provide a boost to our craft's velocity in whatever orientation we're currently facing. + Provide a boost to our craft's velocity in whatever orientation we're currently facing. """ - if not self.fuel: return + if not self.fuel: + return self.velocity += V(magnitude=self.engine_power, angle=self.orientation) self.fuel -= 1 if self.landed: @@ -130,16 +144,19 @@ def boost(self): np = self.rect.move(0, -5) self.rect = np self.boosting = 3 - + def physics_update(self): if not self.landed: - self.velocity += V(magnitude=.5, angle=180) + self.velocity += V(magnitude=0.5, angle=180) def ok_to_land(self): - return (self.orientation < 10 or self.orientation > 350) and self.velocity.magnitude < 5 + return ( + self.orientation < 10 or self.orientation > 350 + ) and self.velocity.magnitude < 5 def check_landed(self, surface): - if self.landed: return + if self.landed: + return if hasattr(surface, "radius"): collision = pygame.sprite.collide_circle(self, surface) else: @@ -151,35 +168,57 @@ def check_landed(self, surface): else: # Hard landing, kaboom! self.intact = False - self.velocity = V(0.0,0.0) # In any case, we stop moving. + self.velocity = V(0.0, 0.0) # In any case, we stop moving. def update(self): - self.physics_update() # Iterate physics + self.physics_update() # Iterate physics if self.boosting: self.boosting -= 1 # Tick over engine time self.update_image() np = self.rect.move(self.velocity.x, -1 * self.velocity.y) self.rect = np self.dirty = True - + def explode(self, screen): - for i in range(random.randint(20,40)): - pygame.draw.line(screen, - (random.randint(190, 255), - random.randint(0,100), - random.randint(0,100)), - self.rect.center, - (random.randint(0, SCREEN_WIDTH), - random.randint(0, SCREEN_HEIGHT)), - random.randint(1,3)) + for i in range(random.randint(20, 40)): + pygame.draw.line( + screen, + ( + random.randint(190, 255), + random.randint(0, 100), + random.randint(0, 100), + ), + self.rect.center, + (random.randint(0, SCREEN_WIDTH), random.randint(0, SCREEN_HEIGHT)), + random.randint(1, 3), + ) def stats(self): - return "Position: [%.2d,%.2d] Velocity: %.2f m/s at %.3d degrees Orientation: %.3d degrees Fuel: %d Status: [%s]" % (self.rect.top, self.rect.left, self.velocity.magnitude, self.velocity.angle, self.orientation, self.fuel, ("Crashed" if not self.intact else ("Landed" if self.landed else ("OK to Land" if self.ok_to_land() else "Not OK")))) + return ( + "Position: [%.2d,%.2d] Velocity: %.2f m/s at %.3d degrees Orientation: %.3d degrees Fuel: %d Status: [%s]" + % ( + self.rect.top, + self.rect.left, + self.velocity.magnitude, + self.velocity.angle, + self.orientation, + self.fuel, + ( + "Crashed" + if not self.intact + else ( + "Landed" + if self.landed + else ("OK to Land" if self.ok_to_land() else "Not OK") + ) + ), + ) + ) class Moon(pygame.sprite.DirtySprite): def __init__(self): - self.width = SCREEN_WIDTH+20 + self.width = SCREEN_WIDTH + 20 self.height = 20 self.image = pygame.Surface((self.width, self.height)) self.rect = pygame.Rect(-10, SCREEN_HEIGHT - 20, SCREEN_WIDTH + 20, 20) @@ -193,41 +232,41 @@ def __init__(self): self.radius = self.diameter / 2 self.x_pos = random.randint(0, SCREEN_WIDTH) self.image = pygame.Surface((self.diameter, self.diameter)) - #self.image.fill((255,255,255,128)) - pygame.draw.circle(self.image, (128,128,128), (self.radius, self.radius), self.radius) - self.rect = pygame.Rect(self.x_pos, SCREEN_HEIGHT - (20 + self.radius), - self.diameter, self.diameter) + # self.image.fill((255,255,255,128)) + pygame.draw.circle( + self.image, (128, 128, 128), (self.radius, self.radius), self.radius + ) + self.rect = pygame.Rect( + self.x_pos, SCREEN_HEIGHT - (20 + self.radius), self.diameter, self.diameter + ) self.image = self.image.convert() self.landing_ok = False self.dirty = False return super(pygame.sprite.DirtySprite, self).__init__() - -def initialize(): + +def initialize(): lander = Lander() moon = Moon() sprites = [lander] - boulders = [Boulder() for i in range(random.randint(2,5))] + boulders = [Boulder() for i in range(random.randint(2, 5))] sprites.extend(boulders) sprites.append(moon) return lander, moon, boulders, pygame.sprite.RenderPlain(sprites) -if __name__ == '__main__': - +if __name__ == "__main__": lander, moon, boulders, allsprites = initialize() while True: - pygame.event.pump() keys = pygame.key.get_pressed() for event in pygame.event.get(): - if event.type == QUIT: pygame.quit() sys.exit() - + if keys[K_r]: lander, moon, boulders, allsprites = initialize() elif keys[K_SPACE] or keys[K_UP]: @@ -241,7 +280,7 @@ def initialize(): for boulder in boulders: lander.check_landed(boulder) - surface.fill((255,255,255)) + surface.fill((255, 255, 255)) font = pygame.font.Font(None, 14) @@ -249,7 +288,7 @@ def initialize(): textpos = text.get_rect() textpos.centerx = SCREEN_WIDTH / 2 surface.blit(text, textpos) - screen.blit(surface, (0,0)) + screen.blit(surface, (0, 0)) allsprites.update() allsprites.draw(screen) @@ -257,17 +296,19 @@ def render_center_text(surface, screen, txt, color): font2 = pygame.font.Font(None, 36) text = font2.render(txt, 1, color) textpos = text.get_rect() - textpos.centerx = SCREEN_WIDTH / 2 - textpos.centery = SCREEN_HEIGHT / 2 + textpos.centerx = SCREEN_WIDTH // 2 + textpos.centery = SCREEN_HEIGHT // 2 surface.blit(text, textpos) - screen.blit(surface, (0,0)) + screen.blit(surface, (0, 0)) if lander.landed: if not lander.intact: lander.explode(screen) - #render_center_text(surface, screen, "Kaboom! Your craft is destroyed.", (255,0,0)) + # render_center_text(surface, screen, "Kaboom! Your craft is destroyed.", (255,0,0)) else: - render_center_text(surface, screen, "You landed successfully!", (0,255,0)) + render_center_text( + surface, screen, "You landed successfully!", (0, 255, 0) + ) pygame.display.flip() pygame.display.update() @@ -277,4 +318,4 @@ def render_center_text(surface, screen, txt, color): pygame.display.flip() pygame.display.update() - fpsClock.tick(FPS) # and tick the clock. + fpsClock.tick(FPS) # and tick the clock. diff --git a/snake.py b/snake.py index edbacf9..168e339 100644 --- a/snake.py +++ b/snake.py @@ -9,42 +9,44 @@ FPS = 15 pygame.init() -fpsClock=pygame.time.Clock() +fpsClock = pygame.time.Clock() SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) surface = pygame.Surface(screen.get_size()) surface = surface.convert() -surface.fill((255,255,255)) +surface.fill((255, 255, 255)) clock = pygame.time.Clock() pygame.key.set_repeat(1, 40) -GRIDSIZE=10 -GRID_WIDTH = SCREEN_WIDTH / GRIDSIZE -GRID_HEIGHT = SCREEN_HEIGHT / GRIDSIZE -UP = (0, -1) -DOWN = (0, 1) -LEFT = (-1, 0) +GRIDSIZE = 10 +GRID_WIDTH = SCREEN_WIDTH // GRIDSIZE +GRID_HEIGHT = SCREEN_HEIGHT // GRIDSIZE +UP = (0, -1) +DOWN = (0, 1) +LEFT = (-1, 0) RIGHT = (1, 0) - -screen.blit(surface, (0,0)) + +screen.blit(surface, (0, 0)) + def draw_box(surf, color, pos): r = pygame.Rect((pos[0], pos[1]), (GRIDSIZE, GRIDSIZE)) pygame.draw.rect(surf, color, r) + class Snake(object): def __init__(self): self.lose() - self.color = (0,0,0) + self.color = (0, 0, 0) def get_head_position(self): return self.positions[0] def lose(self): self.length = 1 - self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] + self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) def point(self, pt): @@ -56,60 +58,70 @@ def point(self, pt): def move(self): cur = self.positions[0] x, y = self.direction - new = (((cur[0]+(x*GRIDSIZE)) % SCREEN_WIDTH), (cur[1]+(y*GRIDSIZE)) % SCREEN_HEIGHT) + new = ( + ((cur[0] + (x * GRIDSIZE)) % SCREEN_WIDTH), + (cur[1] + (y * GRIDSIZE)) % SCREEN_HEIGHT, + ) if len(self.positions) > 2 and new in self.positions[2:]: self.lose() else: self.positions.insert(0, new) if len(self.positions) > self.length: self.positions.pop() - + def draw(self, surf): for p in self.positions: draw_box(surf, self.color, p) + class Apple(object): def __init__(self): - self.position = (0,0) - self.color = (255,0,0) + self.position = (0, 0) + self.color = (255, 0, 0) self.randomize() def randomize(self): - self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) + self.position = ( + random.randint(0, GRID_WIDTH - 1) * GRIDSIZE, + random.randint(0, GRID_HEIGHT - 1) * GRIDSIZE, + ) def draw(self, surf): draw_box(surf, self.color, self.position) + def check_eat(snake, apple): if snake.get_head_position() == apple.position: snake.length += 1 apple.randomize() -class Rock (object): +class Rock(object): def __init__(self): - self.position = (0,0) - self.color = (160,80,30) + self.position = (0, 0) + self.color = (160, 80, 30) self.randomize() def randomize(self): - self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) + self.position = ( + random.randint(0, GRID_WIDTH - 1) * GRIDSIZE, + random.randint(0, GRID_HEIGHT - 1) * GRIDSIZE, + ) def draw(self, surf): draw_box(surf, self.color, self.position) + def check_smash(snake, rock): if snake.get_head_position() == rock.position: snake.lose() - -if __name__ == '__main__': +if __name__ == "__main__": snake = Snake() apple = Apple() rock = Rock() while True: - for event in pygame.event.get(): if event.type == QUIT: pygame.quit() @@ -124,8 +136,7 @@ def check_smash(snake, rock): elif event.key == K_RIGHT: snake.point(RIGHT) - - surface.fill((255,255,255)) + surface.fill((255, 255, 255)) snake.move() check_eat(snake, apple) check_smash(snake, rock) @@ -137,8 +148,8 @@ def check_smash(snake, rock): textpos = text.get_rect() textpos.centerx = 20 surface.blit(text, textpos) - screen.blit(surface, (0,0)) + screen.blit(surface, (0, 0)) pygame.display.flip() pygame.display.update() - fpsClock.tick(FPS + snake.length/3) + fpsClock.tick(FPS + snake.length / 3) diff --git a/snake2.py b/snake2.py index bb8baa5..35981d1 100644 --- a/snake2.py +++ b/snake2.py @@ -6,43 +6,43 @@ from pygame.locals import * snap_time = 0 -#rainbow_berry_effects = 0 +# rainbow_berry_effects = 0 FPS = 15 pygame.init() -fpsClock=pygame.time.Clock() +fpsClock = pygame.time.Clock() SCREEN_WIDTH, SCREEN_HEIGHT = 800, 800 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32) surface = pygame.Surface(screen.get_size()) surface = surface.convert() -surface.fill((255,255,255)) +surface.fill((255, 255, 255)) clock = pygame.time.Clock() pygame.key.set_repeat(1, 40) -GRIDSIZE=10 -GRID_WIDTH = SCREEN_WIDTH / GRIDSIZE -GRID_HEIGHT = SCREEN_HEIGHT / GRIDSIZE -UP = (0, -1) -DOWN = (0, 1) -LEFT = (-1, 0) +GRIDSIZE = 10 +GRID_WIDTH = SCREEN_WIDTH // GRIDSIZE +GRID_HEIGHT = SCREEN_HEIGHT // GRIDSIZE +UP = (0, -1) +DOWN = (0, 1) +LEFT = (-1, 0) RIGHT = (1, 0) BERRY_TYPES = 5 -screen.blit(surface, (0,0)) +screen.blit(surface, (0, 0)) def draw_box(surf, color, pos): r = pygame.Rect((pos[0], pos[1]), (GRIDSIZE, GRIDSIZE)) pygame.draw.rect(surf, color, r) + class Snake(object): def __init__(self): self.lose() - self.color = (0,0,0) + self.color = (0, 0, 0) self.snap_time = 0 - def get_head_position(self): return self.positions[0] @@ -50,7 +50,7 @@ def lose(self): print('You have lost. The game will restart shortly. Press "q" to quit') time.sleep(2.5) self.length = 1 - self.positions = [((SCREEN_WIDTH / 2), (SCREEN_HEIGHT / 2))] + self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))] self.direction = random.choice([UP, DOWN, LEFT, RIGHT]) def point(self, pt): @@ -72,7 +72,10 @@ def move(self): speed = 2 # print("timer is on " + str(cur_time) + str(self.snap_time)) - new = (((cur[0]+(x*speed*GRIDSIZE)) % SCREEN_WIDTH), (cur[1]+(y*speed*GRIDSIZE)) % SCREEN_HEIGHT) + new = ( + ((cur[0] + (x * speed * GRIDSIZE)) % SCREEN_WIDTH), + (cur[1] + (y * speed * GRIDSIZE)) % SCREEN_HEIGHT, + ) if len(self.positions) > 2 and new in self.positions[2:]: self.lose() else: @@ -84,97 +87,107 @@ def draw(self, surf): for p in self.positions: draw_box(surf, self.color, p) + class Apple(object): def __init__(self): - self.position = (0,0) - self.color = (255,0,0) + self.position = (0, 0) + self.color = (255, 0, 0) self.randomize() def randomize(self): - self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) + self.position = ( + random.randint(0, GRID_WIDTH - 1) * GRIDSIZE, + random.randint(0, GRID_HEIGHT - 1) * GRIDSIZE, + ) def draw(self, surf): draw_box(surf, self.color, self.position) + def check_eat_apple(snake, apple): if snake.get_head_position() == apple.position: snake.length += 1 apple.randomize() + class Blueberry(object): def __init__(self): - self.position = (0,0) - self.color = (0,0,255) + self.position = (0, 0) + self.color = (0, 0, 255) self.randomize() def randomize(self): - self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) + self.position = ( + random.randint(0, GRID_WIDTH - 1) * GRIDSIZE, + random.randint(0, GRID_HEIGHT - 1) * GRIDSIZE, + ) def draw(self, surf): draw_box(surf, self.color, self.position) -def check_eat_blueberry(snake, Blueberry): + +def check_eat_blueberry(snake, blueberry): if snake.get_head_position() == blueberry.position: - #start timer for 5-10 seconds + # start timer for 5-10 seconds snake.snap_time = time.time() print("""You have eaten a blueberry. Your speed will be doubled for the next 5 seconds. _______________________________________________________""") time.sleep(1) snake.length += 5 - Blueberry.randomize() - - + blueberry.randomize() -class Rock (object): +class Rock(object): def __init__(self): - self.position = (0,0) - self.color = (160,80,30) + self.position = (0, 0) + self.color = (160, 80, 30) self.randomize() def randomize(self): - self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, - random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) + self.position = ( + random.randint(0, GRID_WIDTH - 1) * GRIDSIZE, + random.randint(0, GRID_HEIGHT - 1) * GRIDSIZE, + ) def draw(self, surf): draw_box(surf, self.color, self.position) + def check_smash_rock(snake, rock): if snake.get_head_position() == rock.position: snake.lose() -class Thorns (object): +class Thorns(object): def __init__(self): - self.position = (0,0) - self.color = (50,135,50) + self.position = (0, 0) + self.color = (50, 135, 50) self.randomize() def randomize(self): - self.position = (random.randint(0, GRID_WIDTH-1) * GRIDSIZE, - random.randint(0, GRID_HEIGHT-1) * GRIDSIZE) + self.position = ( + random.randint(0, GRID_WIDTH - 1) * GRIDSIZE, + random.randint(0, GRID_HEIGHT - 1) * GRIDSIZE, + ) def draw(self, surf): draw_box(surf, self.color, self.position) + def check_smash_thorns(snake, thorns): if snake.get_head_position() == thorns.position: snake.lose() - - - - -if __name__ == '__main__': - #snake +if __name__ == "__main__": + # snake snake = Snake() - #fruits + # fruits apple = Apple() blueberry = Blueberry() - #obstacles + # obstacles rock = Rock() thorns = Thorns() @@ -195,32 +208,31 @@ def check_smash_thorns(snake, thorns): elif event.key == K_q: sys.exit() - - surface.fill((255,255,255)) + surface.fill((255, 255, 255)) snake.move() - #checking for collision + # checking for collision check_eat_apple(snake, apple) check_eat_blueberry(snake, blueberry) check_smash_thorns(snake, thorns) check_smash_rock(snake, rock) - #drawing everything + # drawing everything snake.draw(surface) apple.draw(surface) blueberry.draw(surface) rock.draw(surface) thorns.draw(surface) - #displaying the score + # displaying the score font = pygame.font.Font(None, 36) text = font.render(str(snake.length), 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = 20 surface.blit(text, textpos) - screen.blit(surface, (0,0)) + screen.blit(surface, (0, 0)) - #updating the screen + # updating the screen pygame.display.flip() pygame.display.update() - fpsClock.tick(FPS + snake.length/3) + fpsClock.tick(FPS + snake.length / 3)