python+pygame 最强大脑联动归位游戏

联动归位游戏

上视频。

【最强大脑】第二轮挑战“联动归位”

下载包

pip install pygame

项目结构

在这里插入图片描述

  • simsun.ttc是字体
  • applicant下的东西是滑块
  • background.jpeg是背景
  • help.jpg是目标图片
  • icon.png是图标

准备

资源及源代码下载链接
提取码: 7jhp

编写代码

在"联动归位"文件夹下创建main-game.py

导入包

import pygame
import random
import os
import sys
import time
import pprint

定义图像类

class Image(object):
    def __init__(self, path):
        self.image = pygame.image.load(path)
        self.name = (os.path.basename(path)).split('.')[0]

    def __str__(self):
        return self.name

绘制滑块和文字

def render(colors):
    screen.blit(background.image, (0, 0))
    for row, i in enumerate(colors):
        for column, j in enumerate(i):
            screen.blit(j.image, (row * 40, column * 40))
    screen.blit(getfont(text='成果实例图:'), (gwidth * 40, screen.get_rect().centery - gwidth // 2 * 40))
    screen.blit(helping.image, (gwidth * 40 + 6 * 28, screen.get_rect().centery - gwidth // 2 * 40))
    screen.blit(getfont(text=f'计时:{timer}秒'), (gwidth * 40, screen.get_rect().centery))
    screen.blit(getfont(text=f'移动步数:{movement}次'), (gwidth * 40, screen.get_rect().centery + 50))

定义一个二维列表的查找函数

def getindex(target, lists):
    for row, i in enumerate(lists):
        for column, j in enumerate(i):
            if j == target:
                return row, column
    raise IndexError

定义字体

def getfont(text, color=(255, 70, 130)):
    return gamefont.render(text, True, color)

生成目标

def targets(images):
    ans = images[:]
    for counter, color in enumerate(imgcolors):
        ans[-1][counter] = color
    return ans

移动函数

分析

  • 获得滑块的行列
  • 通过angel的方向参数,定义四个方向的不同移动

获得滑块行列

def move(angel):
    global movement, colors
    redx, redy = getindex(red, colors)
    bluex, bluey = getindex(blue, colors)
    brownx, browny = getindex(brown, colors)
    greenx, greeny = getindex(green, colors)
    orangex, orangey = getindex(orange, colors)
    pinkx, pinky = getindex(pink, colors)
    purplex, purpley = getindex(purple, colors)
    yellowx, yellowy = getindex(yellow, colors)
    movement += 1

四个方向的移动方法

    def left():
        def mover(x, y, col):
            colors[x][y] = street
            x -= 1
            if (colors[x][y] != street and (colors[x][y] not in imgtars)) or x < 0:
                x += 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def right(): # 差不多
        def mover(x, y, col):
            colors[x][y] = street
            x += 1
            if x >= gwidth:
                x -= 1
            if colors[x][y] != street and (colors[x][y] not in imgtars):
                x -= 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def up(): # 差不多
        def mover(x, y, col):
            colors[x][y] = street
            y -= 1
            if (colors[x][y] != street and (colors[x][y] not in imgtars)) or y < 0:
                y += 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def down(): # 差不多
        def mover(x, y, col):
            colors[x][y] = street
            y += 1
            if y >= gwidth:
                y -= 1
            if colors[x][y] != street and (colors[x][y] not in imgtars):
                y -= 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

调用移动方法

    functions = {
        'left': left,
        'right': right,
        'up': up,
        'down': down,
    }[angel]
    functions()

完整的代码

def move(angel):
    global movement, colors
    redx, redy = getindex(red, colors)
    bluex, bluey = getindex(blue, colors)
    brownx, browny = getindex(brown, colors)
    greenx, greeny = getindex(green, colors)
    orangex, orangey = getindex(orange, colors)
    pinkx, pinky = getindex(pink, colors)
    purplex, purpley = getindex(purple, colors)
    yellowx, yellowy = getindex(yellow, colors)
    movement += 1

    def left():
        def mover(x, y, col):
            colors[x][y] = street
            x -= 1
            if (colors[x][y] != street and (colors[x][y] not in imgtars)) or x < 0:
                x += 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def right():
        def mover(x, y, col):
            colors[x][y] = street
            x += 1
            if x >= gwidth:
                x -= 1
            if colors[x][y] != street and (colors[x][y] not in imgtars):
                x -= 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def up():
        def mover(x, y, col):
            colors[x][y] = street
            y -= 1
            if (colors[x][y] != street and (colors[x][y] not in imgtars)) or y < 0:
                y += 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def down():
        def mover(x, y, col):
            colors[x][y] = street
            y += 1
            if y >= gwidth:
                y -= 1
            if colors[x][y] != street and (colors[x][y] not in imgtars):
                y -= 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    functions = {
        'left': left,
        'right': right,
        'up': up,
        'down': down,
    }[angel]
    functions()

初始化游戏并定义常量

pygame.init()

gwidth = 19
width = gwidth * 40 + 240
height = gwidth * 40

helping = Image('images/help/help.jpg')
gamefont = pygame.font.Font('fonts/simsun.ttc', 29)

icon = Image('images/icon/icon.png')

background = Image('images/back/background.jpeg')
blue = Image('images/applicant/blue.bmp')
brown = Image('images/applicant/brown.bmp')
green = Image('images/applicant/green.bmp')
orange = Image('images/applicant/orange.bmp')
pink = Image('images/applicant/pink.bmp')
purple = Image('images/applicant/purple.bmp')
red = Image('images/applicant/red.bmp')
stack = Image('images/applicant/stack.bmp')
street = Image('images/applicant/street.bmp')
yellow = Image('images/applicant/yellow.bmp')

bluetar = Image('images/applicant/target/blue-target.bmp')
browntar = Image('images/applicant/target/brown-target.bmp')
greentar = Image('images/applicant/target/green-target.bmp')
orangetar = Image('images/applicant/target/orange-target.bmp')
pinktar = Image('images/applicant/target/pink-target.bmp')
purpletar = Image('images/applicant/target/purple-target.bmp')
redtar = Image('images/applicant/target/red-target.bmp')
yellowtar = Image('images/applicant/target/yellow-target.bmp')

imgcolors = [blue, brown, green, orange, purple, red, yellow, pink]
imgtars = [bluetar, browntar, greentar, orangetar, pinktar, purpletar, redtar, yellowtar]

movement = 0

colors = [[stack if random.random() < 0.28 else street for i in range(gwidth)] for j in range(gwidth)]
colors = targets(colors)
winmap = [list(i) for i in colors]
# print(images, winmap)
for count in range(gwidth * gwidth):
    move(random.choice(('left', 'right', 'up', 'down')))

clock = pygame.time.Clock()
fps = 12

start = time.time()
end = time.time()
timer = 0

movement = 0

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption('联动归位')
pygame.display.set_icon(icon.image)

running = True
win = False
# win = True

循环判断

while running:
    clock.tick(fps)
    end = time.time()
    timer = int(end - start)
    render(colors)
    if colors == winmap:
        win = True
        running = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            elif event.key == pygame.K_LEFT:
                move('left')
            elif event.key == pygame.K_RIGHT:
                move('right')
            elif event.key == pygame.K_UP:
                move('up')
            elif event.key == pygame.K_DOWN:
                move('down')

    pygame.display.flip()

游戏结束后显示信息

running = win
while running:
    screen.blit(background.image, background.image.get_rect())
    centerx = screen.get_rect().centerx
    centery = screen.get_rect().centery
    screen.blit(getfont('作答完成'), (centerx, centery - 158))
    screen.blit(getfont(f'用时:{timer}'), (centerx, centery - 102))
    screen.blit(getfont(f'移动:{movement}'), (centerx, centery - 60))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
    pygame.display.update()

pygame.quit()
sys.exit()

完整代码

import pygame
import random
import os
import sys
import time
import pprint

class Image(object):
    def __init__(self, path):
        self.image = pygame.image.load(path)
        self.name = (os.path.basename(path)).split('.')[0]

    def __str__(self):
        return self.name

def render(colors):
    screen.blit(background.image, (0, 0))
    for row, i in enumerate(colors):
        for column, j in enumerate(i):
            screen.blit(j.image, (row * 40, column * 40))
    screen.blit(getfont(text='成果实例图:'), (gwidth * 40, screen.get_rect().centery - gwidth // 2 * 40))
    screen.blit(helping.image, (gwidth * 40 + 6 * 28, screen.get_rect().centery - gwidth // 2 * 40))
    screen.blit(getfont(text=f'计时:{timer}秒'), (gwidth * 40, screen.get_rect().centery))
    screen.blit(getfont(text=f'移动步数:{movement}次'), (gwidth * 40, screen.get_rect().centery + 50))

def getindex(target, lists):
    for row, i in enumerate(lists):
        for column, j in enumerate(i):
            if j == target:
                return row, column
    raise ValueError

def getfont(text, color=(255, 70, 130)):
    return gamefont.render(text, True, color)

def targets(images):
    ans = images[:]
    for counter, color in enumerate(imgcolors):
        ans[-1][counter] = color
    return ans

def move(angel):
    global movement, colors
    redx, redy = getindex(red, colors)
    bluex, bluey = getindex(blue, colors)
    brownx, browny = getindex(brown, colors)
    greenx, greeny = getindex(green, colors)
    orangex, orangey = getindex(orange, colors)
    pinkx, pinky = getindex(pink, colors)
    purplex, purpley = getindex(purple, colors)
    yellowx, yellowy = getindex(yellow, colors)
    movement += 1

    def left():
        def mover(x, y, col):
            colors[x][y] = street
            x -= 1
            if (colors[x][y] != street and (colors[x][y] not in imgtars)) or x < 0:
                x += 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def right():
        def mover(x, y, col):
            colors[x][y] = street
            x += 1
            if x >= gwidth:
                x -= 1
            if colors[x][y] != street and (colors[x][y] not in imgtars):
                x -= 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def up():
        def mover(x, y, col):
            colors[x][y] = street
            y -= 1
            if (colors[x][y] != street and (colors[x][y] not in imgtars)) or y < 0:
                y += 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    def down():
        def mover(x, y, col):
            colors[x][y] = street
            y += 1
            if y >= gwidth:
                y -= 1
            if colors[x][y] != street and (colors[x][y] not in imgtars):
                y -= 1
            colors[x][y] = col

        mover(bluex, bluey, blue)
        mover(brownx, browny, brown)
        mover(greenx, greeny, green)
        mover(orangex, orangey, orange)
        mover(pinkx, pinky, pink)
        mover(purplex, purpley, purple)
        mover(redx, redy, red)
        mover(yellowx, yellowy, yellow)

    functions = {
        'left': left,
        'right': right,
        'up': up,
        'down': down,
    }[angel]
    functions()

pygame.init()

gwidth = 19
width = gwidth * 40 + 240
height = gwidth * 40

helping = Image('images/help/help.jpg')
gamefont = pygame.font.Font('fonts/simsun.ttc', 29)

icon = Image('images/icon/icon.png')

background = Image('images/back/background.jpeg')
blue = Image('images/applicant/blue.bmp')
brown = Image('images/applicant/brown.bmp')
green = Image('images/applicant/green.bmp')
orange = Image('images/applicant/orange.bmp')
pink = Image('images/applicant/pink.bmp')
purple = Image('images/applicant/purple.bmp')
red = Image('images/applicant/red.bmp')
stack = Image('images/applicant/stack.bmp')
street = Image('images/applicant/street.bmp')
yellow = Image('images/applicant/yellow.bmp')

bluetar = Image('images/applicant/target/blue-target.bmp')
browntar = Image('images/applicant/target/brown-target.bmp')
greentar = Image('images/applicant/target/green-target.bmp')
orangetar = Image('images/applicant/target/orange-target.bmp')
pinktar = Image('images/applicant/target/pink-target.bmp')
purpletar = Image('images/applicant/target/purple-target.bmp')
redtar = Image('images/applicant/target/red-target.bmp')
yellowtar = Image('images/applicant/target/yellow-target.bmp')

imgcolors = [blue, brown, green, orange, purple, red, yellow, pink]
imgtars = [bluetar, browntar, greentar, orangetar, pinktar, purpletar, redtar, yellowtar]

movement = 0

colors = [[stack if random.random() < 0.28 else street for i in range(gwidth)] for j in range(gwidth)]
colors = targets(colors)
winmap = [list(i) for i in colors]
# print(images, winmap)
for count in range(gwidth * gwidth):
    move(random.choice(('left', 'right', 'up', 'down')))

clock = pygame.time.Clock()
fps = 12

start = time.time()
end = time.time()
timer = 0

movement = 0

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption('联动归位')
pygame.display.set_icon(icon.image)

running = True
win = False
# win = True

while running:
    clock.tick(fps)
    end = time.time()
    timer = int(end - start)
    render(colors)
    if colors == winmap:
        win = True
        running = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            elif event.key == pygame.K_LEFT:
                move('left')
            elif event.key == pygame.K_RIGHT:
                move('right')
            elif event.key == pygame.K_UP:
                move('up')
            elif event.key == pygame.K_DOWN:
                move('down')

    pygame.display.flip()

running = win
while running:
    screen.blit(background.image, background.image.get_rect())
    centerx = screen.get_rect().centerx
    centery = screen.get_rect().centery
    screen.blit(getfont('作答完成'), (centerx, centery - 158))
    screen.blit(getfont(f'用时:{timer}'), (centerx, centery - 102))
    screen.blit(getfont(f'移动:{movement}'), (centerx, centery - 60))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
    pygame.display.update()

pygame.quit()
sys.exit()

资源及源代码下载链接

资源及源代码下载链接
提取码: 7jhp

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值