飞道的博客

小白收藏 | 用Python做个小游戏之九宫格拼图

464人阅读  评论(0)


前面说了几个游戏都没什么难度,来个高难度的九宫格拼图,我不知道大家是不是玩得很上手,反正小编是觉得难。话不多说,上代码。
#!/usr/bin/env python
#- * - coding: utf-8 -*-

import simpleguitk as simplegui
import random

byamax = simplegui.load_image(‘https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=4179492541,951772381&fm=26&gp=0.jpg’)

WIDTH = 600
HEIGHT = WIDTH+100

IMAGE_SIZE = WIDTH/3

all_coordinates = [[IMAGE_SIZE0.5, IMAGE_SIZE0.5], [IMAGE_SIZE1.5, IMAGE_SIZE0.5],
[IMAGE_SIZE2.5, IMAGE_SIZE0.5], [IMAGE_SIZE0.5, IMAGE_SIZE1.5],
[IMAGE_SIZE1.5, IMAGE_SIZE1.5], [IMAGE_SIZE2.5, IMAGE_SIZE1.5],
[IMAGE_SIZE0.5, IMAGE_SIZE2.5], [IMAGE_SIZE1.5, IMAGE_SIZE2.5], None]

ROWS = 3
COLS = 3

steps = 0

board = [[None,None,None],[None,None,None],[None,None,None]]

class Square:

def __init__(self,coordinage):
    self.center = coordinage

def draw(self,canvas,board_pos):

    canvas.draw_image(byamax,self.center,[IMAGE_SIZE,IMAGE_SIZE],
                      [(board_pos[1]+0.5)*IMAGE_SIZE,(board_pos[0]+0.5)*IMAGE_SIZE],[IMAGE_SIZE,IMAGE_SIZE])

def init_board():

random.shuffle(all_coordinates)

for i in range(ROWS):
    for j in range(COLS):

        idx = i * ROWS + j
        square_center = all_coordinates[idx]

        if square_center is None:
            board[i][j] = None
        else:
            board[i][j] = Square(square_center)

def play_game():

global steps
steps = 0
init_board()

def draw(canvas):

canvas.draw_image(byamax,[WIDTH/2,WIDTH/2],[WIDTH,WIDTH],[50,WIDTH+50],[98,98])

canvas.draw_text('步数:'+str(steps),[400,680],22,'White')

for i in range(ROWS):
    for j in range(COLS)
        if board[i][j] is not None:
            board[i][j].draw(canvas,[i,j])

def mouseclick(pos):

global steps

r = int(pos[1]//IMAGE_SIZE)
c = int(pos[0]//IMAGE_SIZE)

if r<3 and c<3:
    if board[r][c] is None:
        return
    else:
        current_square = board[r][c]
        if r - 1 >= 0 and board[r - 1][c] is None:  # 判断上面
            board[r][c] = None
            board[r - 1][c] = current_square
            steps += 1
        elif c + 1 <= 2 and board[r][c + 1] is None:  # 判断右面
            board[r][c] = None
            board[r][c + 1] = current_square
            steps += 1
        elif r + 1 <= 2 and board[r + 1][c] is None:  # 判断下面
            board[r][c] = None
            board[r + 1][c] = current_square
            steps += 1
        elif c - 1 >= 0 and board[r][c - 1] is None:  # 判断左面
            board[r][c] = None
            board[r][c - 1] = current_square
            steps += 1

frame = simplegui.create_frame(‘拼图’,WIDTH,HEIGHT)
frame.set_canvas_background(‘Black’)
frame.set_draw_handler(draw)
frame.add_button(‘重新开始’,play_game,60)

frame.set_mouseclick_handler(mouseclick)

play_game()

frame.start()

整体步骤就是这样了,拼凑出来就是一张美女的图片,我就不放图了,留点悬念给你们,大家试着自己拼出来看看吧。
文章部分内容源于网络,联系侵删*
文章参考源于http://h.jiguangdaili.com/news/54299.html


转载:https://blog.csdn.net/zhimaHTTP/article/details/111284388
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场