3

pygame 圣诞老人扫雪

 2 years ago
source link: http://www.chenshake.com/pygame-santa-claus-is-sweeping-the-snow/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

 

现在周末一个任务就是陪儿子学编程,还是很艰巨的。厚着脸皮,让老师录课,这样我可以重复听一下不明白,没记住的地方。

老师给了小孩3个图片,几个要点

  • 图片如何load,加载到页面
  • 图片通过 blit 方式,可以理解贴在屏幕上
  • 图片没有坐标,无法移动。如果希望移动,需要把图片 blit,贴在方块rect上。雪人移动,其实上雪人的图片贴在方块上,你移动方块,就移动雪人。
  • 通过两个列表,list,实现方块碰撞后消失。
import pygame,time
from random import randint as rd
pygame.init()
screen = pygame.display.set_mode([640,480])
pygame.key.set_repeat(50)

# background=bg  背景
#snowman=sm        雪人
#smr               雪人blit,贴在的方块
#snowflake=sf      雪花
#sfr               雪花blit,贴在的方块,下面通过for循环生成10个方块,没使用
bg=pygame.image.load('865.png')
sm=pygame.image.load('877.png')
smr=pygame.Rect(320,380,100,110)
sf=pygame.image.load('896.png')
#sfr=pygame.Rect(320,360,50,50)

klist=[]
rlist=[]
for i in range (10):
     m=pygame.Rect(i*60,0,50,50)
     rlist.append(m)

def draw():        
     screen.blit(bg,(0,0))
     screen.blit(sm,(smr.x,smr.y))
     global rlist
     global klist
     for a in rlist:
         screen.blit(sf,(a.x,a.y))
         if a.y < 430:
             a.y+=1            
         else:
             a.y+=0        
         if not smr.colliderect(a):
             klist.append(a)
     rlist=klist
     klist=[]    
     pygame.display.flip()


def keydown(i):
     if i.key == pygame.K_UP:
         smr.y-=10
     if i.key == pygame.K_DOWN:
         smr.y+=10
     if i.key == pygame.K_RIGHT:
         smr.x+=10
     if i.key == pygame.K_LEFT:
         smr.x-=10

a=1
 while a ==1:
     draw()
     e = pygame.event.get()
     for i in e:
         if i.type == pygame.QUIT:
             a = 0     
         if i.type == pygame.KEYDOWN:
             keydown(i)
 pygame.quit()

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK