基于Python实现的推箱子小游戏

ops/2025/1/15 21:47:52/

Python贪吃蛇小游戏实现:

     推箱子曾经在我们的童年给我们带来了很多乐趣。推箱子这款游戏现在基本上没人玩了,甚至在新一代人的印象中都已毫无记忆了。。。但是,这款游戏可以在一定程度上锻炼自己的编程能力。

运行效果如图所示:

    游戏关卡有点难哦,码友们一起来挑战一下吧。

代码如下:

import pygame, sys, os
from pygame.locals import *
from collections import deque


def to_box(level, index):
   if level[index] == '-' or level[index] == '@':
       level[index] = '$'
   else:
       level[index] = '*'


def to_man(level, i):
   if level[i] == '-' or level[i] == '$':
       level[i] = '@'
   else:
       level[i] = '+'


def to_floor(level, i):
   if level[i] == '@' or level[i] == '$':
       level[i] = '-'
   else:
       level[i] = '.'


def to_offset(d, width):
   d4 = [-1, -width, 1, width]
   m4 = ['l', 'u', 'r', 'd']
   return d4[m4.index(d.lower())]

def b_manto(level, width, b, m, t):
   maze = list(level)
   maze[b] = '#'
   if m == t:
       return 1
   queue = deque([])
   queue.append(m)
   d4 = [-1, -width, 1, width]
   m4 = ['l', 'u', 'r', 'd']
   while len(queue) > 0:
       pos = queue.popleft()
       for i in range(4):
           newpos = pos + d4[i]
           if maze[newpos] in ['-', '.']:
               if newpos == t:
                   return 1
               maze[newpos] = i
               queue.append(newpos)
   return 0

def b_manto_2(level, width, b, m, t):
   maze = list(level)
   maze[b] = '#'
   maze[m] = '@'
   if m == t:
       return []
   queue = deque([])
   queue.append(m)
   d4 = [-1, -width, 1, width]
   m4 = ['l', 'u', 'r', 'd']
   while len(queue) > 0:
       pos = queue.popleft()
       for i in range(4):
           newpos = pos + d4[i]
           if maze[newpos] in ['-', '.']:
               maze[newpos] = i
               queue.append(newpos)
               if newpos == t:
                   path = []
                   while maze[t] != '@':
                       path.append(m4[maze[t]])
                       t = t - d4[maze[t]]
                   return path

   return []

class Sokoban:
   def __init__(self):
       self.level = list(
           '----#####--------------#---#--------------#$--#------------###--$##-----------#--$-$-#---------###-#-##-#---#######---#-##-#####--..##-$--$----------..######-###-#@##--..#----#-----#########----#######--------')
       self.w = 19
       self.h = 11
       self.man = 163
       self.hint = list(self.level)
       self.solution = []
       self.push = 0
       self.todo = []
       self.auto = 0
       self.sbox = 0
       self.queue = []

   def draw(self, screen, skin):
       w = skin.get_width() / 4
       offset = (w - 4) / 2
       for i in range(0, self.w):
           for j in range(0, self.h):
               if self.level[j * self.w + i] == '#':
                   screen.blit(skin, (i * w, j * w), (0, 2 * w, w, w))
               elif self.level[j * self.w + i] == '-':
                   screen.blit(skin, (i * w, j * w), (0, 0, w, w))
               elif self.level[j * self.w + i] == '@':
                   screen.blit(skin, (i * w, j * w), (w, 0, w, w))
               elif self.level[j * self.w + i] == '$':
                   screen.blit(skin, (i * w, j * w), (2 * w, 0, w, w))
               elif self.level[j * self.w + i] == '.':
                   screen.blit(skin, (i * w, j * w), (0, w, w, w))
               elif self.level[j * self.w + i] == '+':
                   screen.blit(skin, (i * w, j * w), (w, w, w, w))
               elif self.level[j * self.w + i] == '*':
                   screen.blit(skin, (i * w, j * w), (2 * w, w, w, w))
               if self.sbox != 0 and self.hint[j * self.w + i] == '1':
                   screen.blit(skin, (i * w + offset, j * w + offset), (3 * w, 3 * w, 4, 4))

   def move(self, d):
       self._move(d)
       self.todo = []

   def _move(self, d):
       self.sbox = 0
       h = to_offset(d, self.w)
       h2 = 2 * h
       if self.level[self.man + h] == '-' or self.level[self.man + h] == '.':
           # move
           to_man(self.level, self.man + h)
           to_floor(self.level, self.man)
           self.man += h
           self.solution += d
       elif self.level[self.man + h] == '*' or self.level[self.man + h] == '$':
           if self.level[self.man + h2] == '-' or self.level[self.man + h2] == '.':
               # push
               to_box(self.level, self.man + h2)
               to_man(self.level, self.man + h)
               to_floor(self.level, self.man)
               self.man += h
               self.solution += d.upper()
               self.push += 1

   def undo(self):
       if self.solution.__len__() > 0:
           self.todo.append(self.solution[-1])
           self.solution.pop()

           h = to_offset(self.todo[-1], self.w) * -1
           if self.todo[-1].islower():
               # undo a move
               to_man(self.level, self.man + h)
               to_floor(self.level, self.man)
               self.man += h
           else:
               # undo a push
               to_floor(self.level, self.man - h)
               to_box(self.level, self.man)
               to_man(self.level, self.man + h)
               self.man += h
               self.push -= 1

   def redo(self):
       if self.todo.__len__() > 0:
           self._move(self.todo[-1].lower())
           self.todo.pop()

   def manto(self, x, y):
       maze = list(self.level)
       maze[self.man] = '@'
       queue = deque([])
       queue.append(self.man)
       d4 = [-1, -self.w, 1, self.w]
       m4 = ['l', 'u', 'r', 'd']
       while len(queue) > 0:
           pos = queue.popleft()
           for i in range(4):
               newpos = pos + d4[i]
               if maze[newpos] in ['-', '.']:
                   maze[newpos] = i
                   queue.append(newpos)
       # print str(maze)
       t = y * self.w + x
       if maze[t] in range(4):
           self.todo = []
           while maze[t] != '@':
               self.todo.append(m4[maze[t]])
               t = t - d4[maze[t]]
       # print self.todo
       self.auto = 1

   def automove(self):
       if self.auto == 1 and self.todo.__len__() > 0:
           self._move(self.todo[-1].lower())
           self.todo.pop()
       else:
           self.auto = 0

   def boxhint(self, x, y):
       d4 = [-1, -self.w, 1, self.w]
       m4 = ['l', 'u', 'r', 'd']
       b = y * self.w + x
       maze = list(self.level)
       to_floor(maze, b)
       to_floor(maze, self.man)
       mark = maze * 4
       size = self.w * self.h
       self.queue = []
       head = 0
       for i in range(4):
           if b_manto(maze, self.w, b, self.man, b + d4[i]):
               if len(self.queue) == 0:
                   self.queue.append((b, i, -1))
               mark[i * size + b] = '1'
       # print self.queue
       while head < len(self.queue):
           pos = self.queue[head]
           head += 1
           # print pos
           for i in range(4):
               if mark[pos[0] + i * size] == '1' and maze[pos[0] - d4[i]] in ['-', '.']:
                   # print i
                   if mark[pos[0] - d4[i] + i * size] != '1':
                       self.queue.append((pos[0] - d4[i], i, head - 1))
                       for j in range(4):
                           if b_manto(maze, self.w, pos[0] - d4[i], pos[0], pos[0] - d4[i] + d4[j]):
                               mark[j * size + pos[0] - d4[i]] = '1'
       for i in range(size):
           self.hint[i] = '0'
           for j in range(4):
               if mark[j * size + i] == '1':
                   self.hint[i] = '1'
       # print self.hint

   def boxto(self, x, y):
       d4 = [-1, -self.w, 1, self.w]
       m4 = ['l', 'u', 'r', 'd']
       om4 = ['r', 'd', 'l', 'u']
       b = y * self.w + x
       maze = list(self.level)
       to_floor(maze, self.sbox)
       to_floor(maze, self.man)  # make a copy of working maze by removing the selected box and the man
       for i in range(len(self.queue)):
           if self.queue[i][0] == b:
               self.todo = []
               j = i
               while self.queue[j][2] != -1:
                   self.todo.append(om4[self.queue[j][1]].upper())
                   k = self.queue[j][2]
                   if self.queue[k][2] != -1:
                       self.todo += b_manto_2(maze, self.w, self.queue[k][0], self.queue[k][0] + d4[self.queue[k][1]],
                                              self.queue[k][0] + d4[self.queue[j][1]])
                   else:
                       self.todo += b_manto_2(maze, self.w, self.queue[k][0], self.man,
                                              self.queue[k][0] + d4[self.queue[j][1]])
                   j = k
               # print self.todo
               self.auto = 1
               return
       print('not found!')

   def mouse(self, x, y):
       if x >= self.w or y >= self.h:
           return
       m = y * self.w + x
       if self.level[m] in ['-', '.']:
           if self.sbox == 0:
               self.manto(x, y)
           else:
               self.boxto(x, y)
       elif self.level[m] in ['$', '*']:
           if self.sbox == m:
               self.sbox = 0
           else:
               self.sbox = m
               self.boxhint(x, y)
       elif self.level[m] in ['-', '.', '@', '+']:
           self.boxto(x, y)


def main():
   # start pygame
   pygame.init()
   screen = pygame.display.set_mode((400, 300))

   # load skin
   skinfilename = os.path.join('borgar.png')
   try:
       skin = pygame.image.load(skinfilename)
   except pygame.error as msg:
       print('cannot load skin')
       raise SystemExit(msg)
   skin = skin.convert()

   # print skin.get_at((0,0))
   # screen.fill((255,255,255))
   screen.fill(skin.get_at((0, 0)))
   pygame.display.set_caption('推箱子')

   # create Sokoban object
   skb = Sokoban()
   skb.draw(screen, skin)

   #
   clock = pygame.time.Clock()
   pygame.key.set_repeat(200, 50)

   # main game loop
   while True:
       clock.tick(60)

       if skb.auto == 0:
           for event in pygame.event.get():
               if event.type == QUIT:
                   # print skb.solution
                   pygame.quit()
                   sys.exit()
               elif event.type == KEYDOWN:
                   if event.key == K_LEFT:
                       skb.move('l')
                       skb.draw(screen, skin)
                   elif event.key == K_UP:
                       skb.move('u')
                       skb.draw(screen, skin)
                   elif event.key == K_RIGHT:
                       skb.move('r')
                       skb.draw(screen, skin)
                   elif event.key == K_DOWN:
                       skb.move('d')
                       skb.draw(screen, skin)
                   elif event.key == K_BACKSPACE:
                       skb.undo()
                       skb.draw(screen, skin)
                   elif event.key == K_SPACE:
                       skb.redo()
                       skb.draw(screen, skin)
               elif event.type == MOUSEBUTTONUP and event.button == 1:
                   mousex, mousey = event.pos
                   mousex /= (skin.get_width() / 4)
                   mousey /= (skin.get_width() / 4)
                   skb.mouse(mousex, mousey)
                   skb.draw(screen, skin)
       else:
           skb.automove()
           skb.draw(screen, skin)

       pygame.display.update()
       pygame.display.set_caption(skb.solution.__len__().__str__() + '/' + skb.push.__str__() + ' - 推箱子')


if __name__ == '__main__':
   main()

图片素材:

完整素材及全部代码

代码已上传csdn,0积分下载,觉得这片博文有用请留下你的点赞。

基于Python实现的推箱子小游戏
 


http://www.ppmy.cn/ops/16466.html

相关文章

【Hadoop】-Apache Hive概述 Hive架构[11]

目录 Apache Hive概述 一、分布式SQL计算-Hive 二、为什么使用Hive Hive架构 一、Hive组件 Apache Hive概述 Apache Hive是一个在Hadoop上构建的数据仓库基础设施&#xff0c;它提供了一个SQL-Like查询语言来分析和查询大规模的数据集。Hive将结构化查询语言&#xff08;…

联想用万全智算,画出中国AI的山脊

如果我们把欧亚大陆看作一个整体&#xff0c;会发现中国是一个有几座山脉的超大半岛&#xff0c;横断山脉与天山、阴山、昆仑山、南岭、大兴安岭&#xff0c;一横五纵的山脊&#xff0c;描绘出了中华大地的轮廓。 一方水土的休养生息&#xff0c;需要山脉作为屏障&#xff1b;一…

低空经济和无人机

低空经济和无人机是当前科技领域中的两个热门话题&#xff0c;它们的发展互为促进&#xff0c;共同推动着低空经济持续发热&#xff0c;投资主线也愈发清晰。 低空经济是指以低空空域为活动场所&#xff0c;以各类低空飞行器为运载工具&#xff0c;所衍生的各类经济形态、经济…

Android --- RecycleView

RecyclerView是官方在5.0之后新添加的控件&#xff0c;推出用来替代传统的ListView和GridView列表控件。 使用 RecyclerView 步骤 在布局文件中定义的一个 RecyclerView 实例&#xff0c;用作视图的容器。 <?xml version"1.0" encoding"utf-8"?>…

JavaScript云LIS系统概述 前端框架JQuery+EasyUI+Bootstrap医院云HIS系统源码 开箱即用

云LIS系统概述JavaScript前端框架JQueryEasyUIBootstrap医院云HIS系统源码 开箱即用 云LIS&#xff08;云实验室信息管理系统&#xff09;是一种结合了计算机网络化信息系统的技术&#xff0c;它无缝嵌入到云HIS&#xff08;医院信息系统&#xff09;中&#xff0c;用于连…

HTTP接口调用时报错 java.io.IOException: Connection reset by peer解决办法

问题描述 在接口调用时,遇到如下报错:Caused by: java.io.IOException: Connection reset by peer at sun.nio.ch.FileDispatcherImpl.write0(Native Method) ~[?:1.8.0_241] at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47) ~[?:1.8.0_…

社交巨头与去中心化:解析Facebook在区块链的角色

在数字化时代&#xff0c;社交媒体已经成为人们日常生活中不可或缺的一部分。作为全球最大的社交媒体平台&#xff0c;Facebook 在社交领域的影响力无可置疑。然而&#xff0c;随着区块链技术的崛起&#xff0c;Facebook 也开始探索如何将这一技术应用于其平台&#xff0c;以适…

MongoDB的UTCDateTime如何使用

使用MongoDB的UTCDateTime类来存储当前的UTC日期和时间。UTCDateTime对象在MongoDB中表示一个日期&#xff0c;但是它不是PHP的DateTime类。如果你想把UTCDateTime对象格式化为可读的字符串需要先把UTCDateTime对象转换成PHP的DateTime类 方法 (new MongoDB\BSON\UTCDateTime…