Python 취미 도전 의 pygame 무적 보기 좋 은 블라인드 동적 효과 실현
(1)사용 한 python 라 이브 러 리
pygame 라 이브 러 리,random 라 이브 러 리,os,sys 등 시스템 라 이브 러 리 를 사용 합 니 다.
그 중:
pygame 라 이브 러 리 는 주체 기능 을 실현 하고 창 인터페이스 디 스 플레이,동적 효과 디 스 플레이 등 을 제공 합 니 다.
random 라 이브 러 리 는 랜 덤 수의 생 성 을 실현 하고 랜 덤 수 를 통 해 동적 블라인드 의 상하 좌우 선택,블라인드 의 수량 선택 등 기능 을 실현 합 니 다.os 라 이브 러 리 는 그림 자원 의 적재 와 읽 기 를 실현 합 니 다.
sys 라 이브 러 리 종료 작업 등.
(2)전체적인 논리 실현
창 높이 와 너비 설정
현재 표 시 된 그림 과 다음 표 시 될 그림 을 설정 합 니 다.
표시 할 블라인드 수 를 설정 합 니 다.
현재 runimage 에서 분 리 된 블라인드 의 surface 자원 을 저장 하여 블라인드 동적 효과 과정 에서 표시 합 니 다.
상하 운동 인지 좌우 운동 인지 설정 합 니 다.
준비 작업
(1)pygame 의 주 창 구현
import pygame,sys
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption(' ')
fcclock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.K_F1:
pygame.quit()
sys.exit()
fcclock.tick(60)
pygame.display.flip() #
까 만 테두리,캡 처 안 해.다 들 알 아.(2)그림 을 붙 여서 예 쁘 게 보 여 주세요.
import pygame,sys
pygame.init()
screen = pygame.display.set_mode((500, 500))
pygame.display.set_caption(' ')
fcclock = pygame.time.Clock()
img = pygame.image.load('./image/aerial-alpine-ceresole-reale-desktop-backgrounds-1562.jpg').convert_alpha()
img = pygame.transform.scale(img, (500, 500))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.K_F1:
pygame.quit()
sys.exit()
screen.blit(img,(0,0))
fcclock.tick(60)
pygame.display.flip() #
(3)그림 은 어디에서 나 옵 니까?
인터넷 을 통 해 무료 로 예 쁜 그림 을 다운로드 하고 지정 한 폴 더 에 저장 해 보 여 주 는 것 을 권장 합 니 다.
나 는 세 가지 방법 이 있다 고 생각한다.
첫째,파충류 기술 로 인터넷 에서 사진 을 다운로드 하면 키 라인 을 열 어 인터넷 사진 을 채집 한 다음 에 list 목록 에 불 러 올 수 있다.
둘째,컴퓨터 에 있 는 모든 디스크 를 자동 으로 검색 한 다음 list 목록 에 불 러 올 수 있 습 니 다.셋째:디 렉 터 리 를 지정 하고 list 목록 에 불 러 옵 니 다.
나 는 게 으 름 을 피 워 서 세 번 째 방법 을 선택 하여 실현 한다.
구체 적 인 실현 코드 는 다음 과 같다.
path = './image/'
files = []
dirs = os.listdir(path)
for diretion in dirs:
files.append(path + diretion)
(4)그림 불 러 오기내 가 왜 초기 화 할 때 불 러 오지?
효율 문 제 를 해결 하기 위해 서 는 사용 할 때마다 반복 적 으로 불 러 올 필요 가 없 으 며 초기 화 할 때 화면 크기 에 맞 게 그림 크기 를 조정 하기 때 문 입 니 다.
그래서 저 는 이 과정 을 함수 로 포장 하여 후속 호출 에 편리 하고 매개 변 수 는 화면의 크기 로 전달 합 니 다.그리고 bglist 대상 으로 돌아 갑 니 다.
for file in files:
picture = pygame.transform.scale(pygame.image.load(file), (1440, 900))
dSurface = picture
# dSurface = pygame.image.load(file).convert()
bglist.append(dSurface)
OK,그림 이 있 습 니 다.창 이 있 습 니 다.그러면 우리 의 업무 논 리 를 실현 합 시다.3.핵심 기능 모듈
(1)init 실현image 함수 가 surface 대상 에 그림 을 초기 화 합 니 다.
def init_image():
path = './image/'
files = []
dirs = os.listdir(path)
for diretion in dirs:
files.append(path + diretion)
for file in files:
picture = pygame.transform.scale(pygame.image.load(file), (WIDTH, HEIGHT))
dSurface = picture
# dSurface = pygame.image.load(file).convert()
bglist.append(dSurface)
(2)관련 변 수 를 초기 화 합 니 다.
runimage = None
nextimage = None
flag = False # FALSE TRUE
flag2 = False
choose = 6
num_part = random.randint(3,8) #
num_list = []
num_increse = 1
inc = random.choice([-1,1])
while num_increse<=num_part:
inc = -inc
num_list.append(inc)
num_increse += 1
변수 flag 와 flag 2 를 왜 도입 해 야 하 는 지 생각해 보 세 요.(3)매번 블라인드 전환 후 리 셋
def reset():
global flag,runimage,nextimage,flag2,i,j,choose,num_part,num_list
flag = False # FALSE TRUE
flag2 = False
choose = random.randint(6,7)
if nextimage is None:
nextimage = random.choice(bglist)
if runimage is None:
runimage = random.choice(bglist)
else:
runimage = nextimage
nextimage = random.choice(bglist)
num_part = random.randint(3,8) #
num_list = []
num_increse = 1
inc = random.choice([-1,1])
while num_increse <= num_part:
inc = -inc
num_list.append(inc)
num_increse += 1
(4)블라인드 동적 전환 을 실현 하 는 run 함수
def run():
global flag,runimage,flag2,nextimage,i,j,choose,num_part,num_list
reset()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.K_F1:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_SPACE:
if flag is False:# FALSE TRUE
flag = True
flag2 = False
screen.fill((255, 255, 255)) #
if flag:
if choose==6:
select_rect = []
kk = 0
while kk < num_part:
tmp_rect = pygame.Rect(kk * WIDTH/num_part,0,WIDTH/num_part,HEIGHT)
select_rect.append(runimage.subsurface(tmp_rect).copy())
kk += 1
screen.blit(nextimage, (0, 0))
mm = 0
for each in zip(select_rect,num_list):
if each[1]==1:
screen.blit(each[0], (i+mm*WIDTH/num_part, -j))
else:
screen.blit(each[0], (i+mm*WIDTH/num_part, j))
mm += 1
j += step
if j >= HEIGHT:
flag2 = True
elif choose==7:
select_rect = []
kk = 0
while kk < num_part:
tmp_rect = pygame.Rect(0,kk * HEIGHT/num_part,WIDTH,HEIGHT/num_part)
select_rect.append(runimage.subsurface(tmp_rect).copy())
kk += 1
screen.blit(nextimage, (0, 0))
mm = 0
for each in zip(select_rect,num_list):
if each[1]==1:
screen.blit(each[0], (-i, j+mm*HEIGHT/num_part))
else:
screen.blit(each[0], (i, j+mm*HEIGHT/num_part))
mm += 1
i += step
if i >= WIDTH:
flag2 = True
else:
screen.blit(nextimage, (0, 0))
screen.blit(runimage, (0, 0))
if flag2:
reset()
fcclock.tick(fps)
pygame.display.flip() #
(5)주 함수
if __name__ == '__main__':
init_image()
run()
전체 코드
import sys, pygame
import os
import random
pygame.init() # pygame
WIDTH = 600
HEIGHT = 600
screen = pygame.display.set_mode((WIDTH, HEIGHT)) #
pygame.display.set_caption(' ') #
tick = pygame.time.Clock()
fps = 60 # ,
fcclock = pygame.time.Clock()
runimage = None
nextimage = None
flag = False # FALSE TRUE
flag2 = False
choose = 6
num_part = random.randint(3,8) #
num_list = []
num_increse = 1
inc = random.choice([-1,1])
while num_increse<=num_part:
inc = -inc
num_list.append(inc)
num_increse += 1
def init_image():
path = './image/'
files = []
dirs = os.listdir(path)
for diretion in dirs:
files.append(path + diretion)
for file in files:
picture = pygame.transform.scale(pygame.image.load(file), (WIDTH, HEIGHT))
dSurface = picture
bglist.append(dSurface)
def reset():
global flag,runimage,nextimage,flag2,i,j,choose,num_part,num_list
flag = False # FALSE TRUE
flag2 = False
i = 0
j = 0
choose = random.randint(6,7)
if nextimage is None:
nextimage = random.choice(bglist)
if runimage is None:
runimage = random.choice(bglist)
else:
runimage = nextimage
nextimage = random.choice(bglist)
num_part = random.randint(3,8) #
num_list = []
num_increse = 1
inc = random.choice([-1,1])
while num_increse <= num_part:
inc = -inc
num_list.append(inc)
num_increse += 1
def run():
global flag,runimage,flag2,nextimage,i,j,choose,num_part,num_list
reset()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.K_F1:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_SPACE:
if flag is False:# FALSE TRUE
flag = True
flag2 = False
screen.fill((255, 255, 255)) #
if flag:
if choose==6:
select_rect = []
kk = 0
while kk < num_part:
tmp_rect = pygame.Rect(kk * WIDTH/num_part,0,WIDTH/num_part,HEIGHT)
select_rect.append(runimage.subsurface(tmp_rect).copy())
kk += 1
screen.blit(nextimage, (0, 0))
mm = 0
for each in zip(select_rect,num_list):
if each[1]==1:
screen.blit(each[0], (i+mm*WIDTH/num_part, -j))
else:
screen.blit(each[0], (i+mm*WIDTH/num_part, j))
mm += 1
j += step
if j >= HEIGHT:
flag2 = True
elif choose==7:
select_rect = []
kk = 0
while kk < num_part:
tmp_rect = pygame.Rect(0,kk * HEIGHT/num_part,WIDTH,HEIGHT/num_part)
select_rect.append(runimage.subsurface(tmp_rect).copy())
kk += 1
screen.blit(nextimage, (0, 0))
mm = 0
for each in zip(select_rect,num_list):
if each[1]==1:
screen.blit(each[0], (-i, j+mm*HEIGHT/num_part))
else:
screen.blit(each[0], (i, j+mm*HEIGHT/num_part))
mm += 1
i += step
if i >= WIDTH:
flag2 = True
else:
screen.blit(nextimage, (0, 0))
screen.blit(runimage, (0, 0))
if flag2:
reset()
fcclock.tick(fps)
pygame.display.flip() #
if __name__ == '__main__':
init_image()
run()
5.운행 효과OK,다 쓰 면 재 밌 어 요.여러분 이 자동 으로 두 드 려 도 돼 요.저 보다 더 잘 쓸 수도 있어 요.
파 이 썬 의 흥미 로 운 도전 에 관 한 pygame 의 멋 진 블라인드 동적 효 과 를 실현 하 는 글 을 소개 합 니 다.더 많은 pygame 이 블라인드 동적 효 과 를 실현 하 는 내용 은 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 많이 응원 해 주세요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.