Found 32 repositories(showing 30)
Winter091
~80% Copy of Super Mario Bros 1-1 with Pygame
Kyuchumimo
A set of functions from TIC-80 tiny computer 0.90.1723 platform ported to Pygame-ce
Fenixin
"You only get one! (match)" (YOGOM) is designed as a classic arcade of 80's, a fast paced platformer with original gameplay and ambiance. Made in python and pygame.
from pygame import * class GameSprite(sprite.Sprite): def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed): sprite.Sprite.__init__(self) self.image = transform.scale(image.load(player_image), (size_x, size_y)) self.speed = player_speed self.ret = self.image.get_rect() self.rect.x = player_x self.rect.y = player_y class Player(GameSprite): def update_r(self): keys = key. get_pressed() if keys[K_UP] and self.rect.x > 5: self.rect.y -= self.speed if keys[R_DOWN] and self.rect.x < win_width - 80: self.rect.y += self.speed def update_l(self): keys = key. get_pressed() if keys[K_w] and self.rect.x > 5: self.rect.y -= self.speed if keys[R_s] and self.rect.x < win_width - 80: self.rect.y += self.speed back( 200, 255, 255) win_width = 600 win_height = 500 window = display.set_mode((win_width, win_height)) window.fill(back) game = True finish = False clock = time.Clock() FPS = 60 racket1 = Player('racket.png', 30, 200, 4, 50, 150) racket2 = Player('racket.png', 520, 200, 4, 50, 150) ball = GameSprite('tenis_ball.png'. 200, 200, 4, 50, 50) while game: for e in event.get(): if e.type == QUIT: game.False if finish != True: window.fill(back) racket1.update_l() racket2.update_r() racket1.reset() racket2.reset() ball.reset display.update() clock.tick(FPS)
eduardoscarpa
An intelligent agent for Ludo using Reinforcement Learning (Q-learning, SARSA, Double variants). Built with Pygame, it achieved over 80% win rates. Includes rule formalization, state design, and algorithm comparison.
Dreamlocked
Soduku in pygame, up to 80%
JulianMass
Interactive trivia game built with Pygame featuring scoring, lives system, and leaderboard
PyGamer80
Config files for my GitHub profile.
KallamSamad
A classic 80's game made using pygame
ellenheinz
Famoso joguinho da década de 80 utilizando Pygame.
kandi1clickkits
~80% Copy of Super Mario Bros 1-1 with Pygame
FMock
Python and Pygame based game reminiscent of an 80's video game
nickbuker
A simple implementation of the classic 80's game Asteroids using pygame.
CEDipEngineering
Recreação simplificada do jogo Asteroids da década de 80, com a biblioteca pygame.
stoledo85
Projeto de construção de um jogo dos anos 80 usando a biblioteca Pygame
claudiadevis
Réplica del juego clásico de los ladrillos de los años 80 en Python con Pygame
fustte
Réplica del juego clásico de los ladrillos de los años 80 en Python con pygame
tonybolanyo
Réplica de los ladrillos del juego clásico de los ladrillos de los años 80 en pyton con pygame
brandao-m
Jogo arcade vertical inspirado nos clássicos shoot 'em up dos anos 80 e 90, desenvolvido em Python com Pygame.
jamesl33
pyinvaiders is a clone of the popular space shooter game from the 80's, it is written in Python and utilises Pygame
LucasChiodin
Volvió el cásico de los 80! Con una version nueva con la biblioteca de Python, Pygame. Disfrutá esta nueva version personalizada de la generacion Y
AlfCan-dev
An intelligent agent for Ludo using Reinforcement Learning (Q-learning, SARSA, Double variants). Built with Pygame, it achieved over 80% win rates. Includes rule formalization, state design, and algorithm comparison.
Dendrey
Попытка написать игру Уголки (https://ru.wikipedia.org/wiki/%D0%A3%D0%B3%D0%BE%D0%BB%D0%BA%D0%B8_(%D0%B8%D0%B3%D1%80%D0%B0) на Python с использованием билиотеки pygame
LilTopp
import pickle import pygame import os from pygame import mixer from os import path pygame.font.init() pygame.mixer.init() # Version----------------- Version = "1.0" # SetupWindow----------------- HEIGHT, WIDTH = 800, 800 WIN = pygame.display.set_mode((HEIGHT, WIDTH)) pygame.display.set_caption("Game") display = pygame.Surface((HEIGHT, WIDTH)) characterHeight = 90 characterWidth = 100 Block_width = 40 Block_heigh = 40 tile_size = 50 run = True clock = pygame.time.Clock() FPS = 60 player_rect = pygame.Rect((80, 100), (80, 90)) lvl = 1 maxlevels = 20 # BackgroundMusic----------------- def backgroundmusic(): mixer.music.load("music/popsmoke.mp3") mixer.music.set_volume(0.008) mixer.music.play(-1) # SFX----------------- jump_s = pygame.mixer.Sound('music/jump.sound.mp3') jump_s.set_volume(0.4) shoot_s = pygame.mixer.Sound('music/shoot.sound.mp3') shoot_s.set_volume(0.3) # Background"0" Background = pygame.image.load(os.path.join("assets/imgs", "BC3.png")) # ImageUpload----------------- """ WalkingList = [pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_000.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_001.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_002.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_003.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_004.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_005.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_006.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_007.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_008.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_009.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_010.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_011.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_012.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_013.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_014.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_015.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_016.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Walking", "Satyr_01_Walking_017.png")), (characterHeight, characterWidth)), ] IdleList = [pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_000.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_001.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_002.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_003.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_004.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_005.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_006.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_007.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_008.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_009.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_010.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle", "Satyr_01_Idle_011.png")), (characterHeight, characterWidth)), ] JumpList = [pygame.transform.scale(pygame.image.load(os.path.join("Jump Loop", "Satyr_01_Jump Loop_000.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Jump Loop", "Satyr_01_Jump Loop_001.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Jump Loop", "Satyr_01_Jump Loop_002.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Jump Loop", "Satyr_01_Jump Loop_003.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Jump Loop", "Satyr_01_Jump Loop_004.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Jump Loop", "Satyr_01_Jump Loop_005.png")), (characterHeight, characterWidth)), ] IdleBlinkList = [pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_000.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_001.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_002.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_003.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_004.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_005.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_006.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_007.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_008.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_009.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_010.png")), (characterHeight, characterWidth)), pygame.transform.scale(pygame.image.load(os.path.join("Idle Blink", "Satyr_01_Idle Blinking_011.png")), (characterHeight, characterWidth))] """ def reset_level(lvl): player.reset(100, HEIGHT - 130) blob_group.empty() tele_group.empty() # load in level data and create world if path.exists(f'level{lvl}_data'): pickle_in = open(f'level{lvl}_data', 'rb') world_data = pickle.load(pickle_in) world = World(world_data) return world class World(): def __init__(self, data): self.tile_list = [] # load images grass_img = pygame.transform.scale(pygame.image.load(os.path.join("tiles/1 Tiles/2.png")), (Block_heigh, Block_width)) dirt_img = pygame.transform.scale(pygame.image.load(os.path.join("tiles/1 Tiles/1.png")), (Block_heigh, Block_width)) row_count = 0 for row in data: col_count = 0 for tile in row: if tile == 1: img = pygame.transform.scale(grass_img, (Block_width, Block_width)) img_rect = img.get_rect() img_rect.x = col_count * Block_width img_rect.y = row_count * Block_width tile = (img, img_rect) self.tile_list.append(tile) if tile == 0: img = pygame.transform.scale(dirt_img, (Block_width, Block_width)) img_rect = img.get_rect() img_rect.x = col_count * Block_width img_rect.y = row_count * Block_width tile = (img, img_rect) self.tile_list.append(tile) if tile == 2: blob = Enemy(col_count * Block_width, row_count * Block_width - 15) blob_group.add(blob) if tile == 3: tele = Teleport(col_count * Block_width, row_count * Block_width - 15) tele_group.add(tele) col_count += 1 row_count += 1 def draw(self): for tile in self.tile_list: WIN.blit(tile[0], tile[1]) Tree = pygame.transform.scale(pygame.image.load(os.path.join("Willows", "3.png")), (350, 300)) WIN.blit(Tree, (450, 420)) Tombstone = pygame.transform.scale(pygame.image.load(os.path.join("Stones", "1.png")), (80, 70)) WIN.blit(Tombstone, (470, 650)) class Player(pygame.sprite.Sprite): def __init__(self, x, y, health=100): self.images_right = [] self.images_left = [] self.inx = 0 self.counter = 0 for num in range(0, 18): img_right = pygame.image.load(f"Player/Walking/Satyr_01_Walking_{num}.png") img_right = pygame.transform.scale(img_right, (characterWidth, characterHeight)) img_left = pygame.transform.flip(img_right, True, False) self.images_right.append(img_right) self.images_left.append(img_left) self.image = self.images_right[self.inx] self.rect = self.image.get_rect() self.rect.x = x + 40 self.rect.y = y self.rect.width = 40 self.rect.height = 60 self.height = self.image.get_height() self.width = self.image.get_width() self.palyer_img = None self.direction = 0 self.char_vel = 0 self.jumped = False self.jumpingcounter = 0 Tombstone = pygame.transform.scale(pygame.image.load(os.path.join("Stones", "1.png")), (80, 70)) WIN.blit(Tombstone, (470, 650)) self.Tombstone = Tombstone.get_rect() self.jump_s = pygame.mixer.Sound('music/jump.sound.mp3') self.jump_s.set_volume(0.4) self.collect_crystal_sound = pygame.mixer.Sound('music/coinsound.mp3') self.collect_crystal_sound.set_volume(0.1) self.crystalcounter = 0 def update(self): hx = 0 hy = 0 walk_cooldown = 1 # jumping&Moving&Gravity # 1.0-Jumping keys = pygame.key.get_pressed() if keys[pygame.K_SPACE] and self.jumped == False: self.char_vel = -15 self.jumpingcounter += 1 self.jumped = True self.jump_s.play() if keys[pygame.K_SPACE] == False: self.jumped = False # 1.1-Moving if keys[pygame.K_a]: hx -= 5 self.counter += 1 self.direction = -1 if keys[pygame.K_d]: hx += 5 self.counter += 1 self.direction = 1 if keys[pygame.K_a] == False and keys[pygame.K_d] == False: self.counter = 0 self.inx = 0 self.image = self.images_right[self.inx] # Animation if self.counter > walk_cooldown: self.counter = 0 self.inx += 1 if self.inx >= len(self.images_right): self.inx = 0 if self.direction == 1: self.image = self.images_right[self.inx] if self.direction == -1: self.image = self.images_left[self.inx] # 1.2-Gravity self.char_vel += 1 if self.char_vel > 7: self.char_vel = 7 hy += self.char_vel # Collisions for tile in world.tile_list: if tile[1].colliderect(self.rect.x + hx, self.rect.y, self.rect.width, self.rect.height): hx = 0 if tile[1].colliderect(self.rect.x, self.rect.y + hy, self.rect.width, self.rect.height): if self.char_vel < 0: hy = tile[1].bottom - self.rect.top self.char_vel = 0 elif self.char_vel >= 0: hy = tile[1].top - self.rect.bottom self.char_vel = 0 # collisons with Crystals if pygame.sprite.spritecollide(self, blob_group, True): print("Stretli sa") self.collect_crystal_sound.play() self.crystalcounter += 1 return self.crystalcounter # collisons with Teleport if pygame.sprite.spritecollide(self, tele_group, False): game_over = 1 print("teleport") self.rect.x += hx self.rect.y += hy if self.rect.bottom > HEIGHT: self.rect.bottom = HEIGHT hy = 0 if self.crystalcounter == 5: tele_group.draw(WIN) tele_group.update() imgsrect = self.image.get_rect() imgsrect.x = self.rect.x - 34 imgsrect.y = self.rect.y - 10 WIN.blit(self.image, imgsrect) class Lava(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(pygame.image.load(os.path.join("lava", "lava_tile1.png")), (Block_heigh, Block_width)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.move_lava = -5 def update(self): self.rect.y += self.move_lava """ def draw(self): WIN.blit(self.image, (450, 420)) """ class Enemy(pygame.sprite.Sprite): def __init__(self, x, y, ): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(pygame.image.load(os.path.join("tiles/1 Tiles/3.png")), (Block_heigh, Block_width)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.move = -1 self.move_counter = 0 def update(self): self.rect.y += self.move self.move_counter += 1 if self.move_counter > 15: self.move *= -1 self.move_counter = 0 class Teleport(pygame.sprite.Sprite): def __init__(self, x, y, ): pygame.sprite.Sprite.__init__(self) self.image = pygame.transform.scale(pygame.image.load(os.path.join("tiles/1 Tiles/4.png")), (Block_heigh, Block_width)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.moveteleport = -1 self.move_counter_teleport = 0 def update(self): self.rect.y += self.moveteleport self.move_counter_teleport += 1 if self.move_counter_teleport > 15: self.moveteleport *= -1 self.move_counter_teleport = 0 # main----------------- backgroundmusic() shoot_s.play() player = Player(400, HEIGHT - 40) blob_group = pygame.sprite.Group() tele_group = pygame.sprite.Group() pickle_in = open(f"level{lvl}_data", "rb") world_data = pickle.load(pickle_in) world = World(world_data) while run: world.draw() clock.tick(FPS) player.update() pygame.display.update() WIN.blit(Background, (0, 0)) """ Lava.draw() """ """ Lava.update() """ blob_group.draw(WIN) blob_group.update() game_over = player.update(game_over) if game_over == 1: lvl += 1 if lvl <= maxlevels: world_data = [] world = reset_level(lvl) game_over = 0 else: pass for event in pygame.event.get(): if event.type == pygame.QUIT: run = False
k5lina
Pac-Man на Python с использованием Pygame — это аркадная игра, вдохновлённая классикой 80–90-х годов. Игрок управляет Пакманом, собирает все точки на карте и избегает столкновений с привидениями. Проект демонстрирует работу со спрайтами, анимацией, столкновениями, звуком и пользовательским вводом.
athisham94
A dynamic maze game built with Pygame. Collect all animated gem clues, enter the secret code to unlock the exit, and escape before the 80-second timer runs out. The maze changes periodically, and falling graffiti marks the exit once it's opened.
mario438
this is script import pygame import time import random pygame.init() white = (255, 255, 255) yellow = (255, 255, 102) black = (0, 0, 0) red = (213, 50, 80) green = (0, 255, 0) blue = (50, 153, 213) dis_width = 600 dis_height = 600 dis = pygame.display.set_mode((dis_width, dis_height)) pygame.display.set_caption('Snake Game by wolf') clock = pygame.time.Clock() snake_block = 10 snake_speed = 15 font_style = pygame.font.SysFont("bahnschrift", 25) score_font = pygame.font.SysFont("comicsansms", 35) def Your_score(score): value = score_font.render("Your Score: " + str(score), True, yellow) dis.blit(value, [0, 0]) def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block]) def message(msg, color): mesg = font_style.render(msg, True, color) dis.blit(mesg, [dis_width / 6, dis_height / 3]) def gameLoop(): game_over = False game_close = False x1 = dis_width / 2 y1 = dis_height / 2 x1_change = 0 y1_change = 0 snake_List = [] Length_of_snake = 1 foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 while not game_over: while game_close: dis.fill(blue) message("You Lost! Press C-Play Again or Q-Quit", red) Your_score(Length_of_snake - 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_UP: y1_change = -snake_block x1_change = 0 elif event.key == pygame.K_DOWN: y1_change = snake_block x1_change = 0 if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change dis.fill(blue) pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block]) snake_Head = [x1, y1] snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] for x in snake_List[:-1]: if x == snake_Head: game_close = True our_snake(snake_block, snake_List) Your_score(Length_of_snake - 1) pygame.display.update() if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0 Length_of_snake += 1 clock.tick(snake_speed) pygame.quit() quit() gameLoop()
SteveNZ20
Este es un juego clásico de Pong desarrollado en Python utilizando la librería Pygame. Juega con un amigo en el mismo teclado y compite por ver quién es el verdadero campeón. ¡Con un marcador en tiempo real, velocidad ajustable y gráficos retro, te hará sentir como si estuvieras jugando en una máquina arcade de los años 80! 🏆
bargaouiahmed
A deep reinforcement learning snake game agent with pygame for the environment and pytorch for the agent itself, due to time constraints, i can't improve the agent as it tends to converge at around the 150'th iteration with a high score of around 80/79 last time i checked, the project doesn't currently support a human player
cedie8
# Wormy (a Nibbles clone) 2. # By Al Sweigart al@inventwithpython.com 3. # http://inventwithpython.com/pygame 4. # Creative Commons BY-NC-SA 3.0 US 5. 6. import random, pygame, sys 7. from pygame.locals import * 8. 9. FPS = 15 10. WINDOWWIDTH = 640 11. WINDOWHEIGHT = 480 12. CELLSIZE = 20 13. assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size." 14. assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size." 15. CELLWIDTH = int(WINDOWWIDTH / CELLSIZE) 16. CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE) 17. 18. # R G B 19. WHITE = (255, 255, 255) 20. BLACK = ( 0, 0, 0) 21. RED = (255, 0, 0) 22. GREEN = ( 0, 255, 0) 23. DARKGREEN = ( 0, 155, 0) 24. DARKGRAY = ( 40, 40, 40) 25. BGCOLOR = BLACK 26. 27. UP = 'up' 28. DOWN = 'down' 29. LEFT = 'left' 30. RIGHT = 'right' 31. 32. HEAD = 0 # syntactic sugar: index of the worm's head 33. 34. def main(): 35. global FPSCLOCK, DISPLAYSURF, BASICFONT 36. 37. pygame.init() 38. FPSCLOCK = pygame.time.Clock() 39. DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) 40. BASICFONT = pygame.font.Font('freesansbold.ttf', 18) 41. pygame.display.set_caption('Wormy') 42. 43. showStartScreen() 44. while True: 45. runGame() 46. showGameOverScreen() 47. 48. 49. def runGame(): 50. # Set a random start point. 51. startx = random.randint(5, CELLWIDTH - 6) 52. starty = random.randint(5, CELLHEIGHT - 6) 53. wormCoords = [{'x': startx, 'y': starty}, 54. {'x': startx - 1, 'y': starty}, 55. {'x': startx - 2, 'y': starty}] 56. direction = RIGHT 57. 58. # Start the apple in a random place. 59. apple = getRandomLocation() 60. 61. while True: # main game loop 62. for event in pygame.event.get(): # event handling loop 63. if event.type == QUIT: 64. terminate() 65. elif event.type == KEYDOWN: 66. if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT: 67. direction = LEFT 68. elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT: 69. direction = RIGHT 70. elif (event.key == K_UP or event.key == K_w) and direction != DOWN: 71. direction = UP 72. elif (event.key == K_DOWN or event.key == K_s) and direction != UP: 73. direction = DOWN 74. elif event.key == K_ESCAPE: 75. terminate() 76. 77. # check if the worm has hit itself or the edge 78. if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == CELLHEIGHT: 79. return # game over 80. for wormBody in wormCoords[1:]: 81. if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']: 82. return # game over 83. 84. # check if worm has eaten an apply 85. if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']: 86. # don't remove worm's tail segment 87. apple = getRandomLocation() # set a new apple somewhere 88. else: 89. del wormCoords[-1] # remove worm's tail segment 90. 91. # move the worm by adding a segment in the direction it is moving 92. if direction == UP: 93. newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1} 94. elif direction == DOWN: 95. newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1} 96. elif direction == LEFT: 97. newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']} 98. elif direction == RIGHT: 99. newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']} 100. wormCoords.insert(0, newHead) 101. DISPLAYSURF.fill(BGCOLOR) 102. drawGrid() 103. drawWorm(wormCoords) 104. drawApple(apple) 105. drawScore(len(wormCoords) - 3) 106. pygame.display.update() 107. FPSCLOCK.tick(FPS) 108. 109. def drawPressKeyMsg(): 110. pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY) 111. pressKeyRect = pressKeySurf.get_rect() 112. pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30) 113. DISPLAYSURF.blit(pressKeySurf, pressKeyRect) 114. 115. 116. def checkForKeyPress(): 117. if len(pygame.event.get(QUIT)) > 0: 118. terminate() 119. 120. keyUpEvents = pygame.event.get(KEYUP) 121. if len(keyUpEvents) == 0: 122. return None 123. if keyUpEvents[0].key == K_ESCAPE: 124. terminate() 125. return keyUpEvents[0].key 126. 127. 128. def showStartScreen(): 129. titleFont = pygame.font.Font('freesansbold.ttf', 100) 130. titleSurf1 = titleFont.render('Wormy!', True, WHITE, DARKGREEN) 131. titleSurf2 = titleFont.render('Wormy!', True, GREEN) 132. 133. degrees1 = 0 134. degrees2 = 0 135. while True: 136. DISPLAYSURF.fill(BGCOLOR) 137. rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1) 138. rotatedRect1 = rotatedSurf1.get_rect() 139. rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2) 140. DISPLAYSURF.blit(rotatedSurf1, rotatedRect1) 141. 142. rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2) 143. rotatedRect2 = rotatedSurf2.get_rect() 144. rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2) 145. DISPLAYSURF.blit(rotatedSurf2, rotatedRect2) 146. 147. drawPressKeyMsg() 148. 149. if checkForKeyPress(): 150. pygame.event.get() # clear event queue 151. return 152. pygame.display.update() 153. FPSCLOCK.tick(FPS) 154. degrees1 += 3 # rotate by 3 degrees each frame 155. degrees2 += 7 # rotate by 7 degrees each frame 156. 157. 158. def terminate(): 159. pygame.quit() 160. sys.exit() 161. 162. 163. def getRandomLocation(): 164. return {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)} 165. 166. 167. def showGameOverScreen(): 168. gameOverFont = pygame.font.Font('freesansbold.ttf', 150) 169. gameSurf = gameOverFont.render('Game', True, WHITE) 170. overSurf = gameOverFont.render('Over', True, WHITE) 171. gameRect = gameSurf.get_rect() 172. overRect = overSurf.get_rect() 173. gameRect.midtop = (WINDOWWIDTH / 2, 10) 174. overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25) 175. 176. DISPLAYSURF.blit(gameSurf, gameRect) 177. DISPLAYSURF.blit(overSurf, overRect) 178. drawPressKeyMsg() 179. pygame.display.update() 180. pygame.time.wait(500) 181. checkForKeyPress() # clear out any key presses in the event queue 182. 183. while True: 184. if checkForKeyPress(): 185. pygame.event.get() # clear event queue 186. return 187. 188. def drawScore(score): 189. scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE) 190. scoreRect = scoreSurf.get_rect() 191. scoreRect.topleft = (WINDOWWIDTH - 120, 10) 192. DISPLAYSURF.blit(scoreSurf, scoreRect) 193. 194. 195. def drawWorm(wormCoords): 196. for coord in wormCoords: 197. x = coord['x'] * CELLSIZE 198. y = coord['y'] * CELLSIZE 199. wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE) 200. pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect) 201. wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8) 202. pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect) 203. 204. 205. def drawApple(coord): 206. x = coord['x'] * CELLSIZE 207. y = coord['y'] * CELLSIZE 208. appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE) 209. pygame.draw.rect(DISPLAYSURF, RED, appleRect) 210. 211. 212. def drawGrid(): 213. for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines 214. pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT)) 215. for y in range(0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines 216. pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y)) 217. 218. 219. if __name__ == '__main__': 220. main()