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

2024-04-26 12:52
文章标签 python 实现 箱子 小游戏

本文主要是介绍基于Python实现的推箱子小游戏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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实现的推箱子小游戏
 

这篇关于基于Python实现的推箱子小游戏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/937641

相关文章

Python将博客内容html导出为Markdown格式

《Python将博客内容html导出为Markdown格式》Python将博客内容html导出为Markdown格式,通过博客url地址抓取文章,分析并提取出文章标题和内容,将内容构建成html,再转... 目录一、为什么要搞?二、准备如何搞?三、说搞咱就搞!抓取文章提取内容构建html转存markdown

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Python Websockets库的使用指南

《PythonWebsockets库的使用指南》pythonwebsockets库是一个用于创建WebSocket服务器和客户端的Python库,它提供了一种简单的方式来实现实时通信,支持异步和同步... 目录一、WebSocket 简介二、python 的 websockets 库安装三、完整代码示例1.

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

MySQL双主搭建+keepalived高可用的实现

《MySQL双主搭建+keepalived高可用的实现》本文主要介绍了MySQL双主搭建+keepalived高可用的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、测试环境准备二、主从搭建1.创建复制用户2.创建复制关系3.开启复制,确认复制是否成功4.同