最近在玩Pygame小游戏,因而想把一些部分整理下来供往后学习参考。
效果大概是这样的:
![v2-5bc28f2aa8c4c059f5229d0fa3a21379_b.jpg](http://img-03.proxy.5ce.com/view/image?&type=2&guid=deee1047-1c30-eb11-8da9-e4434bdf6706&url=https://pic2.zhimg.com/v2-5bc28f2aa8c4c059f5229d0fa3a21379_b.jpg)
导入pygame
为了效果好一些,我选了张背景图bg.jpg,剩下的部分就是设定好屏幕的宽、高
pygame的初始化还是需要的
import pygame
display_width = 1200
display_height = 600
WHITE = (255, 255, 255)
RED = (255, 0, 0)
bg_location = 'bg.jpg'
pygame.init()
按钮类 Class Button
说是Button,其实就是设定特定的text要在屏幕的哪个地方显示,而当鼠标移到这个text所占的区域的时候(or 点击),程序再做出对应的操作
class Button(object):
def __init__(self, text, color, x=None, y=None, **kwargs):
self.surface = font.render(text, True, color)
self.WIDTH = self.surface.get_width()
self.HEIGHT = self.surface.get_height()
if 'centered_x' in kwargs and kwargs['centered_x']:
self.x = display_width // 2 - self.WIDTH // 2
else:
self.x = x
if 'centered_y' in kwargs and kwargs['cenntered_y']:
self.y = display_height // 2 - self.HEIGHT // 2
else:
self.y = y
def display(self):
screen.blit(self.surface, (self.x, self.y))
def check_click(self, position):
x_match = position[0] > self.x and position[0] < self.x + self.WIDTH
y_match = position[1] > self.y and position[1] < self.y + self.HEIGHT
if x_match and y_match:
return True
else:
return False
开始页面 Starting Screen
开始页面做的,,就是加载背景、Button,如果加了音乐的话,还需要这里进行音乐的播放
在Button的显示上,这边设置了当鼠标移到Button上就显示红色高亮,这个也是通过加载text中实现的,一个while中的条件判读
def starting_screen():
screen.blit(bg, (0,0))
game_title = font.render('Starting Screen', True, WHITE)
screen.blit(game_title, (display_width//2 - game_title.get_width()//2, 150))
play_button = Button('Play', RED, None, 350, centered_x=True)
exit_button = Button('Exit', WHITE, None, 400, centered_x=True)
play_button.display()
exit_button.display()
pygame.display.update()
while True:
if play_button.check_click(pygame.mouse.get_pos()):
play_button = Button('Play', RED, None, 350, centered_x=True)
else:
play_button = Button('Play', WHITE, None, 350, centered_x=True)
if exit_button.check_click(pygame.mouse.get_pos()):
exit_button = Button('Exit', RED, None, 400, centered_x=True)
else:
exit_button = Button('Exit', WHITE, None, 400, centered_x=True)
play_button.display()
exit_button.display()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
raise SystemExit
if pygame.mouse.get_pressed()[0]:
if play_button.check_click(pygame.mouse.get_pos()):
break
if exit_button.check_click(pygame.mouse.get_pos()):
break
调用函数
这边到了实现的部分,你需要一个screen作为基础,然后加载背景图,加载字体,之后再调用Starting_scrreen函数
screen = pygame.display.set_mode((display_width, display_height))
bg = pygame.image.load(bg_location)
font_addr = pygame.font.get_default_font()
font = pygame.font.Font(font_addr, 36)
starting_screen()
总结:
Pygame所涉及的模块并不多,实现的2D小游戏也没有多少市场了,但编程的初学者可以用来了解项目的流程及熟悉Python及面向对象编程。