Python+Pygame实现简易画板功能详解
本文介绍使用Python和Pygame库实现一个简易画板的方法。文章首先探讨了Pygame在当前的应用现状,指出其虽非最新但适合练习2D游戏算法。随后通过代码实例展示了画板的核心功能,包括画笔设置、颜色调整及绘图逻辑,旨在为开发者提供实践Pygame基础操作的参考。
疑问:pygame已经过时了吗?
关于其是否过时的讨论尚无定论,官方更新频率已接近四年未有大动作。尽管如此,其用户基数在同类库中仍属可观,但多数用户仅将其用于个人兴趣项目或小型实验,鲜有用于商业级开发。Pygame本质上是SDL的Python封装,而SDL底层依赖OpenGL,因此部分开发者会结合pyOpenGL进行3D演示开发。若旨在开发完整游戏,Pygame提供的封装层级较低,许多功能需自行实现,这虽降低了自由度但也提供了更高的定制空间。鉴于文档资源相对匮乏,虽然前人留下了不少教程,但它仍是练习2D游戏常用算法和思想的良好工具。若目标明确为开发2D游戏,可考虑Python版的cocos2d(非iOS版),其API设计简洁易用,内置场景管理和控制台等功能,尽管该库也有一年未更新,作者重心似乎转向了Objective-C版本,导致Python版缺失帧动画等特性。若需开发引擎,可尝试pyglet;若涉及3D开发,panda3D或python-orge也是常见选择,尽管作者未亲自验证,但社区反馈普遍认可。总体而言,使用Python开发游戏的群体较小,且存在环境依赖和打包兼容性问题,因此它更适合作为算法原型验证工具,而非最终产品发布的首选。当然,若您的目标并非使用Pygame开发游戏,上述讨论可忽略。
(以上观点源自知乎回答,特此致谢!)
以下是画板运行效果的截图展示

# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
import math
class Brush:
def __init__(self, screen):
self.screen = screen
self.color = (0, 0, 0)
self.size = 1
self.drawing = False
self.last_pos = None
self.style = True
self.brush = pygame.image.load("images/brush.png").convert_alpha()
self.brush_now = self.brush.subsurface((0, 0), (1, 1))
def start_draw(self, pos):
self.drawing = True
self.last_pos = pos
def end_draw(self):
self.drawing = False
def set_brush_style(self, style):
print("* set brush style to", style)
self.style = style
def get_brush_style(self):
return self.style
def get_current_brush(self):
return self.brush_now
def set_size(self, size):
if size < 1:
size = 1
elif size > 32:
size = 32
print("* set brush size to", size)
self.size = size
self.brush_now = self.brush.subsurface((0, 0), (size*2, size*2))
def get_size(self):
return self.size
def set_color(self, color):
self.color = color
for i in xrange(self.brush.get_width()):
for j in xrange(self.brush.get_height()):
self.brush.set_at((i, j),
color + (self.brush.get_at((i, j)).a,))
def get_color(self):
return self.color
def draw(self, pos):
if self.drawing:
for p in self._get_points(pos):
if self.style:
self.screen.blit(self.brush_now, p)
else:
pygame.draw.circle(self.screen, self.color, p, self.size)
self.last_pos = pos
def _get_points(self, pos):
points = [(self.last_pos[0], self.last_pos[1])]
len_x = pos[0] - self.last_pos[0]
len_y = pos[1] - self.last_pos[1]
length = math.sqrt(len_x**2 + len_y**2)
step_x = len_x / length
step_y = len_y / length
for i in xrange(int(length)):
points.append((points[-1][0] + step_x, points[-1][1] + step_y))
points = map(lambda x: (int(0.5 + x[0]), int(0.5 + x[1])), points)
return list(set(points))
class Menu:
def __init__(self, screen):
self.screen = screen
self.brush = None
self.colors = [
(0xff, 0x00, 0xff), (0x80, 0x00, 0x80),
(0x00, 0x00, 0xff), (0x00, 0x00, 0x80),
(0x00, 0xff, 0xff), (0x00, 0x80, 0x80),
(0x00, 0xff, 0x00), (0x00, 0x80, 0x00),
(0xff, 0xff, 0x00), (0x80, 0x80, 0x00),
(0xff, 0x00, 0x00), (0x80, 0x00, 0x00),
(0xc0, 0xc0, 0xc0), (0xff, 0xff, 0xff),
(0x00, 0x00, 0x00), (0x80, 0x80, 0x80),
]
self.colors_rect = []
for (i, rgb) in enumerate(self.colors):
rect = pygame.Rect(10 + i % 2 * 32, 254 + i / 2 * 32, 32, 32)
self.colors_rect.append(rect)
self.pens = [
pygame.image.load("images/pen1.png").convert_alpha(),
pygame.image.load("images/pen2.png").convert_alpha(),
]
self.pens_rect = []
for (i, img) in enumerate(self.pens):
rect = pygame.Rect(10, 10 + i * 64, 64, 64)
self.pens_rect.append(rect)
self.sizes = [
pygame.image.load("images/big.png").convert_alpha(),
pygame.image.load("images/small.png").convert_alpha()
]
self.sizes_rect = []
for (i, img) in enumerate(self.sizes):
rect = pygame.Rect(10 + i * 32, 138, 32, 32)
self.sizes_rect.append(rect)
def set_brush(self, brush):
self.brush = brush
def draw(self):
for (i, img) in enumerate(self.pens):
self.screen.blit(img, self.pens_rect[i].topleft)
for (i, img) in enumerate(self.sizes):
self.screen.blit(img, self.sizes_rect[i].topleft)
self.screen.fill((255, 255, 255), (10, 180, 64, 64))
pygame.draw.rect(self.screen, (0, 0, 0), (10, 180, 64, 64), 1)
size = self.brush.get_size()
x = 10 + 32
y = 180 + 32
if self.brush.get_brush_style():
x = x - size
y = y - size
self.screen.blit(self.brush.get_current_brush(), (x, y))
else:
pygame.draw.circle(self.screen,
self.brush.get_color(), (x, y), size)
for (i, rgb) in enumerate(self.colors):
pygame.draw.rect(self.screen, rgb, self.colors_rect[i])
def click_button(self, pos):
for (i, rect) in enumerate(self.pens_rect):
if rect.collidepoint(pos):
self.brush.set_brush_style(bool(i))
return True
for (i, rect) in enumerate(self.sizes_rect):
if rect.collidepoint(pos):
if i:
self.brush.set_size(self.brush.get_size() - 1)
else:
self.brush.set_size(self.brush.get_size() + 1)
return True
for (i, rect) in enumerate(self.colors_rect):
if rect.collidepoint(pos):
self.brush.set_color(self.colors[i])
return True
return False
class Painter:
def __init__(self):
self.screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Painter")
self.clock = pygame.time.Clock()
self.brush = Brush(self.screen)
self.menu = Menu(self.screen)
self.menu.set_brush(self.brush)
def run(self):
self.screen.fill((255, 255, 255))
while True:
self.clock.tick(30)
for event in pygame.event.get():
if event.type == QUIT:
return
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.screen.fill((255, 255, 255))
elif event.type == MOUSEBUTTONDOWN:
if event.pos[0] <= 74 and self.menu.click_button(event.pos):
pass
else:
self.brush.start_draw(event.pos)
elif event.type == MOUSEMOTION:
self.brush.draw(event.pos)
elif event.type == MOUSEBUTTONUP:
self.brush.end_draw()
self.menu.draw()
pygame.display.update()
def main():
app = Painter()
app.run()
if __name__ == '__main__':
main()
总结
以上是关于使用Python和Pygame实现简单画板功能的完整代码实例,希望能为读者提供帮助。感兴趣的用户可继续浏览本站其他相关技术专题,如有任何疏漏或疑问,欢迎在评论区留言指正。感谢各位读者对本站的支持与关注!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









