pygame弹球游戏
Pygame 入门基本指南 - RioTian - 博客园 (cnblogs.com)
代码
import os
import pygame
# Colors (R, G, B)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WIDTH = 360 # 游戏窗口的宽度
HEIGHT = 480 # 游戏窗口的高度
FPS = 30 # 帧率
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = player_img
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.speed = 1;
def update(self):
self.rect.x += 5 * self.speed;
if self.rect.right > WIDTH:
self.speed = -1;
if self.rect.left < 0:
self.speed = 1;
# initialize pygame and create window
pygame.init()
pygame.mixer.init() #声音初始化
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Soccer")#设置游戏窗口标题栏文字
clock = pygame.time.Clock()
# set up asset folders
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')
player_img = pygame.image.load(os.path.join(img_folder, "soccer_ball.png")).convert()
player_img = pygame.transform.scale(player_img, (50, 50))
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# Game Loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
# Update
all_sprites.update()
# Draw / render
screen.fill(BLACK)
all_sprites.draw(screen)
# *after* drawing everything, flip the display
pygame.display.flip()
要点
精灵图像导入
# set up asset folders
game_folder = os.path.dirname(__file__)
img_folder = os.path.join(game_folder, 'img')
player_img = pygame.image.load(os.path.join(img_folder, "soccer_ball.png")).convert()
player_img = pygame.transform.scale(player_img, (50, 50))
精灵图像缩放
pygame.Surface — pygame v2.0.1.dev1 documentation
player_img = pygame.transform.scale(player_img, (50, 50))
精灵 Player 类
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = player_img
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.speed = 1;
def update(self):
self.rect.x += 5 * self.speed;
if self.rect.right > WIDTH:
self.speed = -1;
if self.rect.left < 0:
self.speed = 1;
精灵组初始化
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)