pygame学习笔记(2):画点的三种方法和动画实例

1236次阅读  |  发布于5年以前

1、单个像素(画点)

利用pygame画点主要有三种方法:
方法一:画长宽为1个像素的正方形

复制代码 代码如下:

import pygame,sys
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
pygame.draw.rect(screen,[0,0,0],[150,50,1,1],1) #画11的矩形,线宽为1,这里不能是0,因为11无空白区域。
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()

方法二:画个直径为1的圆

复制代码 代码如下:

import pygame,sys
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
pygame.draw.circle(screen,[0,0,0],[150,200],1,1)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()

方法三:这种方法并不是画上去的,而是改变了surface上某个点的颜色,这样看上去像是画了一个点screen.set_at()。另外,如果要得到某个像素的颜色,可以使用screen.get_at()。

复制代码 代码如下:

import pygame,sys
pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
screen.set_at([150,150],[255,0,0])#将150,150改为红色。
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()

2、连接多个点形成线

pygame.draw.lines()方法可以将多个点连接成为线。该方法有5个参数:surface表面、颜色、闭合线或者非闭合线(如果闭合为True,否则为False),点的列表,线宽。pygame.draw.lines(surface,[color],False/True,plotpoints,1)。下面的例子画出了一条马路,具体如下:

复制代码 代码如下:

import pygame,sys
def lineleft(): #画马路左边界
plotpoints=[]
for x in range(0,640):
y=-5x+1000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def lineright():#画马路右边界
plotpoints=[]
for x in range(0,640):
y=5
x-2000
plotpoints.append([x,y])
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
pygame.display.flip()
def linemiddle():#画马路中间虚线
plotpoints=[]
x=300
for y in range(0,480,20):
plotpoints.append([x,y])
if len(plotpoints)==2:
pygame.draw.lines(screen,[0,0,0],False,plotpoints,5)
plotpoints=[]
pygame.display.flip()

pygame.init()
screen=pygame.display.set_caption('hello world!')
screen=pygame.display.set_mode([640,480])
screen.fill([255,255,255])
lineleft()
lineright()
linemiddle()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
sys.exit()

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8