pygame 中坦克与墙壁碰撞

2023-12-01

我一直在致力于这个关于坦克的项目(基于游戏 Tank Trouble),并且我让墙壁出现在屏幕上。如何让坦克撞到墙壁时停下来?

将来我也计划让子弹也能撞到墙壁。

任何帮助将不胜感激!

完整游戏代码:https://gist.github.com/vairiskovels/1d975e02e4140c116fe259141c75f2e4

class Game:

    def __init__(self):
        self.run = True
        self.screen_width = 1060
        self.screen_height = 798
        self.image = pygame.image.load("bin/sprites/background/background1.png")
        self.image = pygame.transform.scale(self.image, (self.screen_width, self.screen_height))
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))

        # all_sprites is used to update and draw all sprites together.
        self.all_sprites = pygame.sprite.Group()

        # for collision detection with enemies.
        self.bullet_group = pygame.sprite.Group()

        # for collision detection with walls.
        self.wall_list = pygame.sprite.Group()

        self.tank = Tank()
        self.all_sprites.add(self.tank)

        self.enemy = Enemy()
        self.all_sprites.add(self.enemy)

        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            bullet = Bullet(self.tank)
            self.bullet_group.add(bullet)
            self.all_sprites.add(bullet)

        # -------------- Walls --------------

        self.wall = Wall(0, 0, 16, 798)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(0, 0, 1060, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(1044, 0, 16, 798)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(0, 782, 1060, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(0, 260, 130, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(260, 0, 16, 130)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(146, 130, 130, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(130, 130, 16, 408)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(146, 522, 130, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(146, 390, 130, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(130, 652, 16, 146)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(146, 652, 130, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(390, 0, 16, 146)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(522, 0, 16, 146)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(390, 130, 148, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(260, 260, 146, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(390, 260, 16, 408)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(406, 390, 132, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(522, 260, 16, 146)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(522, 260, 130, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(522, 522, 16, 260)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(652, 130, 278, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(652, 130, 16, 296)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(782, 0, 16, 146)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(914, 0, 16, 146)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(782, 260, 278, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(782, 390, 148, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(914, 390, 16, 148)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(914, 522, 148, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(914, 652, 148, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(652, 522, 146, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(652, 652, 146, 16)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)

        self.wall = Wall(782, 522, 16, 276)
        self.wall_list.add(self.wall)
        self.all_sprites.add(self.wall)


    def handle_events(self):
        self.tank.handle_events()
        self.enemy.handle_events()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.run = False
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    self.run = False
                if event.key == pygame.K_SPACE:
                    bullet = Bullet(self.tank)
                    self.bullet_group.add(bullet)
                    self.all_sprites.add(bullet)

    def update(self):
        # Calls `update` methods of all contained sprites.
        self.all_sprites.update()

    def draw(self):
        self.screen.blit(self.image, (0, 0))
        self.all_sprites.draw(self.screen)  # Draw the contained sprites.
        pygame.display.update()


class Tank(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bin/sprites/player/player_tank.png")
        self.org_image = self.image.copy()

        # A nicer way to set the start pos with `get_rect`.
        self.rect = self.image.get_rect(center=(70, 600))

        self.vel = 3

        self.angle = 270  # starts looking right
        self.direction = pygame.Vector2(1, 0)
        self.pos = pygame.Vector2(self.rect.center)

        self.hp = 1

    def handle_events(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.angle += 3
        if keys[pygame.K_RIGHT]:
            self.angle -= 3
        if keys[pygame.K_UP] and self.rect.left - 5 > 0 and self.rect.top - 5 > 0 and self.rect.right + 5 < 1060 and self.rect.bottom + 5 < 798:
            self.move(-3)
        if keys[pygame.K_DOWN] and self.rect.left - 5 > 0 and self.rect.top - 5 > 0 and self.rect.right + 5 < 1060 and self.rect.bottom + 5 < 798:
            self.move(3)

        self.direction = pygame.Vector2(1, 0).rotate(-self.angle)
        self.image = pygame.transform.rotate(self.org_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def move(self, vel):
        direction = pygame.Vector2(0, vel).rotate(-self.angle)
        self.pos += direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])


class Enemy(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bin/sprites/enemy/enemy_tank.png")
        self.org_image = self.image.copy()

        self.spawnx = [600, 850, 860]  # spawning x coord
        self.spawny = [70, 200, 700]  # spawning y coord
        self.i = random.randint(0, len(self.spawnx) - 1)

        # A nicer way to set the start pos with `get_rect`.
        self.rect = self.image.get_rect(center=(self.spawnx[self.i], self.spawny[self.i]))

        self.vel = 3
        self.hp = 1

        if self.i == 0:
            self.angle = 180
        elif self.i == 1:
            self.angle = 90
        elif self.i == 2:
            self.angle = 0

        self.direction = pygame.Vector2(1, 0)
        self.pos = pygame.Vector2(self.rect.center)

    def handle_events(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            self.angle += 3
        if keys[pygame.K_d]:
            self.angle -= 3
        if keys[pygame.K_w]:
            self.move(-3)
        if keys[pygame.K_s]:
            self.move(3)

        self.direction = pygame.Vector2(1, 0).rotate(-self.angle)
        self.image = pygame.transform.rotate(self.org_image, self.angle)
        self.rect = self.image.get_rect(center=self.rect.center)

    def move(self, vel):
        direction = pygame.Vector2(0, vel).rotate(-self.angle)
        self.pos += direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])


class Wall(pygame.sprite.Sprite):

    def __init__(self, x, y, width, height):
        super().__init__()

        # Make a wall, of the size specified in the parameters
        self.image = pygame.Surface([width, height])
        self.image.fill(dark_gray)

        # Make our top-left corner the passed-in location.
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x


class Bullet(pygame.sprite.Sprite):

    def __init__(self, tank):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load("bin/sprites/bullet/bullet.png")
        self.image = pygame.transform.scale(self.image, (16, 16))
        self.rect = self.image.get_rect()
        self.rect.centerx = tank.rect.centerx + 3  # How much pixels from tank turret on x axis
        self.rect.centery = tank.rect.centery - 25  # How much pixels from tank turret on y axis
        self.angle = tank.angle
        self.pos = pygame.Vector2(self.rect.center)
        self.direction = pygame.Vector2(0, -10).rotate(-self.angle)
        self.lives = 4  # how many times bounces

    def update(self):
        self.pos += self.direction
        self.rect.center = round(self.pos[0]), round(self.pos[1])

        if self.rect.left < 0:
            self.direction.x *= -1
            self.rect.left = 0
            self.pos.x = self.rect.centerx
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

        if self.rect.right > 1060:
            self.direction.x *= -1
            self.rect.right = 1060
            self.pos.x = self.rect.centerx
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

        if self.rect.top < 0:
            self.direction.y *= -1
            self.rect.top = 0
            self.pos.y = self.rect.centery
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

        if self.rect.bottom > 798:
            self.direction.y *= -1
            self.rect.right = 798
            self.pos.y = self.rect.centery
            self.lives -= 1
            if self.lives == 0:
                return self.kill()
            bounce.play()

坦克是一个Sprite目的。墙壁是Sprite对象,也收集在Group wall_list。因此你可以使用pygame.sprite.spritecollide()检测碰撞:

if pygame.sprite.spritecollide(self.tank, self.wall_list, False):
    print("tank collides with wall")

Note, pygame.sprite.spritecollide()返回一个列表Wall物体,导致碰撞。在您的情况下,当坦克碰撞时,列表可能包含 1 个元素:

hit_walls = pygame.sprite.spritecollide(self.tank, self.wall_list, False)
if hit_walls:
    hit_wall = hit_walls[0]

或者,您可以遍历导致碰撞的墙壁:

for hit_wall in pygame.sprite.spritecollide(self.tank, self.wall_list, False):
    # [...]

例如,当坦克撞到墙壁时,您可以取消坦克的移动Game.handle_events:

class Game:
    # [...]

    def handle_events(self):

        tank_pos = pygame.math.Vector2(self.tank.pos)
        self.tank.handle_events()
        if pygame.sprite.spritecollide(self.tank, self.wall_list, False): 
            self.tank.pos = tank_pos
            self.tank.rect.center = round(tank_pos[0]), round(tank_pos[1])

        # [...] 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pygame 中坦克与墙壁碰撞 的相关文章

随机推荐

  • 如何在Python中计算两个日期之间的差异(以周为单位)

    我正在尝试计算 一年中的几周 中两个日期之间的差异 我可以获取日期时间对象并获取天数等 但不能获取周数 当然 我不能减去日期 因为不能保证周末 我尝试使用获取周数d1 isocalendar 1 并减去d2 isocalendar 1 但问
  • Google Play 许可服务:关于 userId 字段的断言?

    根据其参考实现 我们假设Google Play 许可服务 ice er 在userId其反应范围 返回一个 应用程序特定的用户标识符 另一方面 层压参考不做出此类承诺 实际上 返回的值似乎是冗长的二进制数据 甚至可能以 至少 a 开头0x0
  • 使用 scanf/printf 从位集输入/输出

    我对 C 有点陌生 我想知道如何 scanf 进入或 printf 出位集 即 I O 到位集索引的适当类型说明符是什么 我想做的一个例子是 include
  • 无法单击或选择“控制 XAML 设计”

    我在 Window 7 上的 VS2010 WPF 上进行开发 我有一个项目不会引发任何错误或警告 编译正常 XAML 设计显示正常 但我无法在 XAML 设计视图中单击或选择任何控件 原因是什么 或者如何找出问题或可能的异常 有同样的问题
  • 传输协议 Firebase 实时数据库使用

    有许多数据传输机制 例如 Websockets 服务器发送事件作为 HTML5 传输 以及旧传输 例如 Forever Frame 和 ajax 长轮询 firebase 使用哪种传输方式 Firebase 使用基于 HTTPS 的 Web
  • 如何使用 win32gui 才能让应用程序在后台运行?

    我从中找到了一段很棒的代码here关于如何使用 win32gui 模块创建托盘应用程序 但是 该应用程序基于一个名为的函数运行notify仅当鼠标移到图标上时运行 如何让应用程序不断循环执行某些操作 而不管用户做什么 换句话说 我想以非基于
  • MessageBox.Show会导致跨线程异常吗?

    我可以打电话吗MessageBox Show在子线程上而不担心跨线程异常 我知道表面上的答案是 尝试一下并找出答案 我成功地做到了这一点 但我注意到 Windows 7 在引发跨线程异常方面似乎不如 Windows XP 严格 那么 是否有
  • Bash 中运算符“=”和“==”有什么区别?

    看起来这两个运算符几乎相同 有区别吗 我应该什么时候使用 什么时候 你必须使用 在数值比较中 if 3 3 then echo yes fi yes if 3 3 then echo yes fi bash 3 3 attempted as
  • 构建 WSO2 Carbon 标签的正确方法是什么?

    我正在尝试并排构建 WSO2 Carbon 的多个标签以进行比较 但我担心我可能会丢失有关目录布局以及如何进行构建的信息 请问我可以帮忙吗 目前 我已经从以下位置查看了我认为相关的标签 https svn wso2 org repos ws
  • Spring + Hibernate + Tomcat 依赖问题

    当我运行 tomcat 并部署战争时 我得到 NoClassDefFoundError org apache commons collections map LRUMap Invocation of init method failed n
  • 运行存储在互联网上的 Ruby 脚本

    我有我的托管和域 我在其中上传了 Ruby 脚本 我正在使用以下命令运行本地脚本 ruby path to script script rb 我上传了 Ruby 脚本 我想在终端中运行它 如下所示 ruby http www example
  • 在 Excel 中将具有数据列的行转换为具有多行的列

    我有几行数据 TAG SKU SIZE GRADE LOCATION A001 123 12 A X1 A002 789 13 B X3 A003 456 15 C X5 我需要将其转换为 A001 123 SIZE 12 A001 123
  • 将引用作为参数的模板参数推导

    我正在尝试深刻理解模板论证推导 我不明白的一点是 我应该如何应用标准中的规则here对于类型A and P对于以下情况 遗憾的是 cppreference com 上没有示例 请参阅下面的相关部分 template
  • 如何通过 Code First 方法在 Entity Framework 4.3 中实现 Table-Per-Type 继承?

    我在代码中有这样的类层次结构 Table A public class A IIdentification public int id get set Table B public class B A some properties her
  • Flash CS5 在非文档类的构造函数中引用显示对象

    在学习了这种在Flash CS5中除了文档类之外的类中访问放置在舞台上的对象的优秀方法之后 发现在这个线程中 我遇到了一个绊脚石 我在用 this stage getChildAt 0 greenLight1 visible false 在
  • timeBasedSeq 函数重复它创建的一些日期!

    我正在使用 xts 包中的 timeBasedSeq 函数作为时间序列 zoo 对象中的索引 但它会重复它创建的某些日子 这会导致动物园出现问题 因为 order by 中的索引条目不是唯一的 例如 timeBasedSeq 1986060
  • SED-根据脚本中的 2 个条件将列从小写更改为大写

    我必须根据运动栏是射击或柔道的条件将 名称 栏从小写更改为大写 到目前为止 我有 anubhava 提供的以下代码在终端中运行 但不在脚本内运行 sed E s 5 shooting judo 1 U 2 L 3 一些输入 id name
  • 如何使用powershell执行.sql文件?

    我有一个 sql文件 我正在尝试通过 Powershell 脚本传递连接字符串详细信息并调用 sql file 我正在搜索并想出了一个与Invoke sqlcmd 当我试图找到与 SQL 相对应的模块时 我在我的机器上没有找到任何模块 我应
  • 只是一个关于 javascript BOM 问题的小问题

    问题是这样的 创建一个包含多个链接的页面 然后编写在窗口 onload 事件上触发的代码 显示 页面上每个链接的 href 这是我的解决方案 a href http www google com First link a a href ht
  • pygame 中坦克与墙壁碰撞

    我一直在致力于这个关于坦克的项目 基于游戏 Tank Trouble 并且我让墙壁出现在屏幕上 如何让坦克撞到墙壁时停下来 将来我也计划让子弹也能撞到墙壁 任何帮助将不胜感激 完整游戏代码 https gist github com vai