今天介绍一下pygame库,用于创建画板。
Pygame
- Pygame是一组跨平台的Python模块, 用于创建视频游戏。
- 它由旨在与Python编程语言一起使用的计算机图形和声音库组成。
- Pygame由Pete Shinners正式编写, 以取代PySDL。
- Pygame适合于创建客户端应用程序, 这些应用程序可以包装在独立的可执行文件中。
Pygame的先决条件:
-
在学习pygame之前, 我们需要了解我们要开发哪种游戏。
- 要学习pygame, 必须具有Python的基本知识。
Pygame安装
在Windows中安装pygame
在安装Pygame之前, 应先在系统中安装Python, 最好安装3.6.1或更高版本, 因为它对初学者更友好, 并且运行速度更快。主要有两种安装Pygame的方法, 如下所示:
1.通过pip安装:安装Pygame的好方法是使用pip工具(这是python用于安装软件包的工具)。命令如下:
py -m pip install -U pygame --user
在Mac中安装pygame
按照以下步骤在Mac中安装pygame
- 访问pygame pygame.org的官方网站, 它将显示以下窗口, 下载pygame-1.9.1release-python.org-32bit-py2.7-macosx10.3.dmg:
以下是代码实现画板的创建
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((800,600))
screen.fill((255,255,255))
up = pygame.image.load('up.png')
screen.blit(up,(0,0))
clear = pygame.image.load('cl.png')
screen.blit(clear,(150,50))
add=pygame.image.load('add.png')
cut=pygame.image.load('cut.png')
screen.blit(add, (220, 55))
screen.blit(cut, (280, 55))
clist = [(255,0,0),(0,255,0),(0,0,255),(0,51,255),(255,0,102),(219,7,109)]
for i in range(len(clist)):
c_x = 400+48*i
c_y = 55
pygame.draw.rect(screen,clist[i],(c_x,c_y,48,48))
pen_color = (255, 0, 0)
pen_size = 20
is_start = False
while True:
for event in pygame.event.get():
x,y = pygame.mouse.get_pos()
if event.type ==QUIT:
pygame.display.quit()
exit()
elif event.type == MOUSEBUTTONDOWN:
if (150 < x < 198)and(50 < y <98):
screen.fill((255,255,255))
screen.blit(up, (0, 0))
screen.blit(clear, (150, 50))
screen.blit(add,(220,55))
screen.blit(cut, (280, 55))
for i in range(len(clist)):
c_x = 400+48*i
c_y = 55
pygame.draw.rect(screen, clist[i], (c_x, c_y, 48, 48))
pygame.display.update()
elif 220 < x < 268 and 55 <y <95:
pen_size = pen_size+3
if pen_size > 50:
pen_size = 50
elif 280 < x < 328 and 55 < y < 95:
pen_size = pen_size-3
if pen_size < 1:
pen_size = 1
elif 400 < x <400+48*1 and 55< y <103:
pen_color = clist[0]
elif 400 < x < 400+48*2 and 55 < y < 103:
pen_color = clist[1]
elif 400 < x < 400+48*3 and 55 < y < 103:
pen_color = clist[2]
elif 400 < x < 400+48*4 and 55 < y < 103:
pen_color = clist[3]
elif 400 < x < 400+48*5 and 55 < y < 103:
pen_color = clist[4]
elif 400 < x < 400+48*6 and 55 < y < 103:
pen_color = clist[5]
else :
pygame.draw.circle(screen,pen_color,(x,y),pen_size)
pygame.display.update()
is_start = True
elif event.type == MOUSEMOTION:
if is_start == True:
pygame.draw.circle(screen,pen_color,(x,y),pen_size)
pygame.display.update()
elif event.type == MOUSEBUTTONUP:
is_start = False
代码素材:
文件名对应的图片
add.png
cl.png
cut.png
up.png
图片顺序不能弄错哦!!!
运行结果:
更多内容请关注作者,我会持续更新的哦!!!