Pygame是一个开源的跨平台的Python多媒体库,用于开发2D游戏和多媒体应用程序。它基于Simple DirectMedia Layer(SDL)库,提供了一系列用于图形、音频和输入处理的函数和类。Pygame能够使用硬件加速,使得游戏开发更加高效和快速。
import pygame
WIDTH, HEIGHT = 500, 500
class Bg:
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load("./img/bg.jpeg")
# 构造一个面相关的矩形
self.rect = self.image.get_rect()
# 修改矩形的初始位置
self.rect.left = 50
self.rect.top = -400
def update(self):
# 更新矩形位置
self.rect.top += 1
if self.rect.top > 500:
self.rect.top = -400
# 把面绘制到矩形的位置
self.screen.blit(self.image, self.rect)
class Player:
def __init__(self, screen):
self.screen = screen
self.player_x = 220
self.player_speed = 5
self.image = pygame.Surface((60, 60))
self.image.fill("green")
self.rect = self.image.get_rect()
self.rect.center = (250, 410)
def update(self):
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LEFT]:
self.rect.left -= self.player_speed
if self.rect.left < 0:
self.rect.left = 0
elif key_pressed[pygame.K_RIGHT]:
self.rect.right += self.player_speed
if self.rect.right > 500:
self.rect.right = 500
self.screen.blit(self.image, self.rect)
class Game:
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
self.bg = Bg(self.screen)
self.player = Player(self.screen)
def check_event(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
def update_draw(self):
self.screen.fill("grey")
self.bg.update()
self.player.update()
pygame.display.flip()
def run(self):
while True:
self.clock.tick(25)
self.check_event()
self.update_draw()
game = Game()
game.run()