Jun 192021
 

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

老师给了小孩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)
#screen
#background=bg  背景
#snowman=sm        雪人
#smr               雪人blit,贴在的方块
#snowflake=sf      雪花
#sfr               雪花blit,贴在的方块
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) 

rlist=[]
for i in range (20):
     m=pygame.Rect(rd(0,640),0,50,50)
     rlist.append(m)

def draw(): 
     global rlist
     keep=[]       
     screen.blit(bg,(0,0))
     screen.blit(sm,(smr.x,smr.y))    
     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):
             keep.append(a)            
     rlist=keep    
     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

def mousedown():
     b=pygame.mouse.get_pos()
     r=pygame.Rect(b[0],b[1],50,50)
     rlist.append(r)
     pygame.display.flip()

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)            
         if i.type == pygame.MOUSEBUTTONDOWN:
             mousedown()
 
pygame.quit()

  One Response to “pygame 圣诞老人扫雪”

 Leave a Reply

(required)

(required)

This site uses Akismet to reduce spam. Learn how your comment data is processed.