用户:
天之鹰查看:0 回复:1 评论:0 创建时间:2022-09-18T11:00:19
【作品展示】

【作品介绍】
滑动图块
【作品源代码】
from PIL import Image
import pygame
import sys
import time
import random
import os
#第一节课代码
def cut_picture():
pic = Image.open('1.jpg')
pic_size = pic.size
cut_w = pic_size[0]//3
cut_h = pic_size[1]//3
for j in range(3):
for i in range(3):
cut = pic.crop((i*cut_w, j*cut_h, (i+1)*cut_w, (j+1)*cut_h))
cut.save('pic\\'+str(i+j*3)+'.jpg')
print(cut)
return pic_size[0], pic_size[1], cut_w, cut_h
def make_ctrl():
im_ctrl = Image.open('pic\\8.jpg')
im_ctrl = im_ctrl.convert('L') # 将图片转换为灰度模式
im_ctrl_l = im_ctrl.load() # 创建用于修改像素的对象
for w in range(cut_w):
for h in range(cut_h):
im_ctrl_l[w, h] = 0
im_ctrl.save('pic\\8.jpg')
def init_pos():
pos_list = []
for j in range(3):
for i in range(3):
pos_list.append((i * cut_w, j * cut_h))
return pos_list
#第二节课代码
def init_pad():
pygame.init()
pad = pygame.display.set_mode((pic_w*2, pic_h))
pygame.display.set_caption('滑块拼图')
pad.fill((0, 0, 0))
return pad
def show():
answer = pygame.Rect(pic_w, 0, pic_w, pic_h)
answer_pic = pygame.image.load('1.jpg')
pad.blit(answer_pic, answer)
for i in range(9):
cut_rec = pygame.Rect(pos_list[i][0], pos_list[i][1], cut_w, cut_h)
cut_img = pygame.image.load('pic\\'+cp[i])
cut_img = pygame.transform.scale(cut_img, (cut_w-5, cut_w-5))
pad.blit(cut_img, cut_rec)
pygame.display.update()
#第三节课代码
def move(dct):
global ctrl
if dct == 'w' and ctrl not in [6,7,8]:
cp[ctrl], cp[ctrl+3] = cp[ctrl+3], cp[ctrl]
ctrl = ctrl+3
elif dct == 's' and ctrl not in [0,1,2]:
cp[ctrl-3], cp[ctrl] = cp[ctrl], cp[ctrl-3]
ctrl = ctrl-3
elif dct == 'a' and ctrl not in [2, 5, 8]:
cp[ctrl+1], cp[ctrl] = cp[ctrl], cp[ctrl+1]
ctrl = ctrl+1
elif dct == 'd' and ctrl not in [0, 3, 6]:
cp[ctrl-1], cp[ctrl] = cp[ctrl], cp[ctrl-1]
ctrl = ctrl-1
def isright():
right = [str(i)+".jpg" for i in range(0, 9)]
if cp == right:
print('胜利!一共用了:'+str(step)+'步')
time.sleep(4)
sys.exit()
else:
print(cp)
#请在下方键入本节课代码
if __name__ == '__main__':
pic_w, pic_h, cut_w, cut_h = cut_picture()
make_ctrl()
cp = os.listdir('pic')
pos_list = init_pos()
ctrl = 8
step = 0
pad = init_pad()
for i in range(100):
move(random.choice(['w','s','a','d']))
while True:
show()
for event in pygame.event.get():
if event.type == pygame.QUIT:
print('放弃!已走了:'+str(step)+'步')
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
move('w')
step += 1
show()
isright()
if event.key == pygame.K_s:
move('s')
step += 1
show()
isright()
if event.key == pygame.K_a:
move('a')
step += 1
show()
isright()
if event.key == pygame.K_d:
move('d')
step += 1
show()
isright()
【提示】
部分含有Python第三方库相关内容的作品,在海龟编辑器网页端无法运行哦!如遇到这种情况,可以打开下面的链接,下载海龟编辑器客户端:
https://python.codemao.cn