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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/650929.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2024/4/26 C++day4

1在Complex类的基础上&#xff0c;完成^&#xff0c;>>&#xff0c;<<,~运算符的重载 #include <iostream> using namespace std; class Complex {int rel; //实部int vir; //虚部 public:Complex(){}Complex(int rel,int vir):rel(rel),vir(vir){}vo…

换脸插件升级导致SDWebUI无法启动cannot import name ‘Undefined‘ from ‘pydantic.fields‘

今天在一台新的机器环境装了SDWEBUI&#xff0c;都使用最新的版本&#xff0c;升级了下换脸的插件&#xff0c;于是乎启动崩溃了。错误如下 Launching Web UI with arguments: --listen --skip-torch-cuda-test --disable-nan-check --skip-version-check --skip-python-versi…

服装连锁收银系统需要注意的五个要素

在现代零售行业中&#xff0c;服装连锁店是一个庞大而复杂的商业体系&#xff0c;而收银系统则是其核心管理工具之一。商淘云服装连锁收银系统是一款专为服装连锁店设计的全面解决方案&#xff0c;为商家提供了高效、灵活的收银管理服务。在选择和配置服装连锁收银系统时&#…

Python + selenium自动化生成测试报告!

前言 今天笔者想和大家聊聊Pythonselenium自动化生成测试报告&#xff0c;批量执行完用例后&#xff0c;生成的测试报告是文本形式的&#xff0c;不够直观&#xff0c;为了更好的展示测试报告&#xff0c;最好是生成HTML格式的。 unittest里面是不能生成html格式报告的&#…

C# WinForm —— 10 单选按钮与复选框的介绍与使用

单选按钮 RadioButton 一组单选按钮中&#xff0c;只能选择一个&#xff0c;互相排斥 常用属性、事件&#xff1a; 属性用途(Name)单选按钮的ID&#xff0c;在代码里引用的时候会用到,一般以 rb开头Text单选按钮旁边显示的 文本信息Checked单选按钮的勾选状态Appearance控制单…

【个人博客搭建】(11)swagger添加jwt信息

这个主要是为了方便使用swagger时&#xff0c;能更好的带入我们的token。 ps&#xff1a;如果使用其他第三方api工具&#xff08;apipost、postman等&#xff09;则不需要。 &#xff08;当然&#xff0c;不用不能没有&#xff0c;是吧&#xff09; 1、在AddSwaggerGen内添加…

cuda非root用户安装及mamba库安装报错问题

1、先检查是不是cuda版本的问题&#xff08;cuda≥11.6&#xff09; 非root用户安装指南&#xff1a; &#xff08;1&#xff09;先去NVIDIA官网CUDA Toolkit Archive | NVIDIA Developer 选一个版本 查看architecture的命令 uname -m 查看version的命令 lsb_release -a 下…

【产品经理修炼之道】- 携程酒店业务

这篇文章里&#xff0c;作者以携程为参照对象进行了业务分析&#xff0c;一起来看看本文作者关于携程酒店业务的思考。想了解OTA、或者酒店业务的同学们&#xff0c;或许可以来看看本文的思路。 本文是以携程为参照对象做的一个业务分析&#xff0c;系列一共有三期&#xff0c…

【链表】Leetcode K个一组翻转链表

题目讲解 25. K 个一组翻转链表 算法讲解 虽然这道题是一道困难题&#xff0c;但是从代码层面很简单&#xff0c;只是一道简单的模拟&#xff1a;我们要先求出总共需要翻转的链表有多少组&#xff08;链表的长度 / k&#xff09;&#xff0c;接下来就是翻转k的链表最链接的问…

【JAVA】PO、VO、DAO、BO、DTO、POJO你分得清吗?

在Java开发中&#xff0c;PO、VO、DAO、BO、DTO、POJO这些词汇是比较常见的&#xff0c;每个术语都有其特定的含义和用途。下面是它们的具体区别&#xff1a; 名称简要概况用途和特定PO (Persistence Object) 持…

SpringBoot+vue开发记录(二)

说明&#xff1a;本篇文章的主要内容为SpringBoot开发中后端的创建 项目创建: 1. 新建项目&#xff1a; 如下&#xff0c;这样简单创建就行了&#xff0c;JDK什么的就先17&#xff0c;当然1.8也是可以的&#xff0c;后面可以改。 这样就创建好了&#xff1a; 2. pom.xml…

JVM(Jvm如何管理空间?对象如何存储、管理?)

Jvm如何管理空间&#xff08;Java运行时数据区域与分配空间的方式&#xff09; ⭐运行时数据区域 程序计数器 程序计数器&#xff08;PC&#xff09;&#xff0c;是一块较小的内存空。它可以看作是当前线程所执行的字节码的行号指示器。Java虚拟机的多线程是通过时间片轮转调…