2401_83393291 2024-03-20 16:15 采纳率: 64.3%
浏览 2
已结题

python编程类似于坦克大战的游戏找不出bug了

import pygame
import time
import random
from pygame.sprite import Sprite

screen_width=600
screen_lenth=400
main_color=pygame.Color(127,255,0)
text_color=pygame.Color(255,0,0)
class BaseItem(Sprite):
    def __init__(self, color, width, height):
        pygame.sprite.Sprite.__init__(self)
class MainGame():
    window = None
    p1_role = None
    p2_role = None
    targetlist = []
    targetcount = 10
    p1_bulletlist = []
    p2_bulletlist = []
    targetbullet = []
    explodelist = []
    targetbulletlist=[]
    walllist = []
    s_pic = 'images/开始.png'
    e_pic = 'images/结束.png'

    def __init__(self):
        pass
    def startsurface(self):
        button_1=Button(300,150,MainGame.s_pic)
        button_2=Button(300,250,MainGame.e_pic)
        var = pygame.display.init
        MainGame.window = pygame.display.set_mode([screen_width,screen_lenth])
        pygame.display.set_caption('双人射击')
        while True:
            MainGame.window.fill(main_color)
            button_1.displayButton()
            button_2.displayButton()
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if button_1.isOver() == True:
                        self.startGame()
                    if button_2.isOver() == True:
                        self.endGame()
                if event.type == pygame.QUIT:
                    self.endGame()
            pygame.display.update()
    def startGame(self):
        var = pygame.display.init
        MainGame.window = pygame.display.set_mode([screen_width, screen_lenth])
        pygame.display.set_caption('双人射击')
        self.createp1()
        self.createp2()
        self.createtarget()
        self.createWall()
        while True:
            time.sleep(0.02)  # 循环变慢

            MainGame.window.fill(main_color)  # 设置主窗口的填充色

            self.getEvent()  # 获取事件

            MainGame.window.blit(self.getTextSurface("剩余目标数量:%d" % len(MainGame.targetlist)),
                                 (10, 10))  # 绘制文字

            if MainGame.p1_role and MainGame.p1_role.live:
                MainGame.p1_role.displayRole()  # 调用我方显示方法,只需要初始化一次,一直显示即可
            else:
                del MainGame.p1_role  # 删除我方
                MainGame.p1_role = None

            if MainGame.p1_role and MainGame.p1_role.live:
                if not MainGame.p1_role.stop:
                    MainGame.p1_role.move()  # 我方坦克的移动,按下方向键一直移动
                    MainGame.p1_role.hitWall()  # 检测我方是否与墙壁发生碰撞
                    MainGame.p1_role.p1_hit_target()

            if MainGame.p2_role and MainGame.p2_role.live:
                MainGame.p2_role.displayRole()  # 调用我方坦克显示方法,只需要初始化一次,一直显示即可
            else:
                del MainGame.p2_role  # 删除我方坦克
                MainGame.p2_role = None

            if MainGame.p2_role and MainGame.p2_role.live:
                if not MainGame.p2_role.stop:
                    MainGame.p2_role.move()  # 我方坦克的移动,按下方向键一直移动
                    MainGame.p2_role.hitWall()  # 检测我方是否与墙壁发生碰撞
                    MainGame.p2_role.p2_hit_target()

             #调用敌方坦克显示方法
            self.p1_bullet()  # 调用我方坦克子弹显示方法
            self.p2_bullet()
            self.blitTarget()
            self.blittargetbullet()  # 调用敌方坦克子弹显示方法
            self.blitExplode()  # 调用爆炸效果的显示方法
            self.blitWall()  # 调用墙壁的显示方法

            pygame.display.update()  # 主窗口的更新,用于一直存在


    def endGame(self):
        print('game over')
        exit()

    def getTextSurface(self, text):
        pygame.font.init()  # 初始化字体模块
        font = pygame.font.SysFont("SimHei", 12)  # 获取系统字体对象并设置字体和大小
        textSurface = font.render(text, True, text_color)  # 绘制文字信息
        return textSurface
    def getEvent(self):
        eventList = pygame.event.get()  # 获取所有事件

        for event in eventList:  # 遍历事件
            if event.type == pygame.QUIT:  # 关闭键
                self.endGame()
            if event.type == pygame.KEYDOWN:  # 键盘按下
                if not MainGame.p1_role:
                    if event.key == pygame.K_r:
                        self.createp1()
                if MainGame.p1_role and MainGame.p1_role.live:
                    if event.key == pygame.K_LEFT:
                        MainGame.p1_role.direction = 'L'  # 切换方向
                        MainGame.p1_role.stop = False
                        print("按下左键,向左移动")
                    elif event.key == pygame.K_RIGHT:
                        MainGame.p1_role.direction = 'R'  # 切换方向
                        MainGame.p1_role.stop = False
                        print("按下右键,向右移动")
                    elif event.key == pygame.K_UP:
                        MainGame.p1_role.direction = 'U'  # 切换方向
                        MainGame.p1_role.stop = False
                        print("按下上键,向上移动")
                    elif event.key == pygame.K_DOWN:
                        MainGame.p1_role.direction = 'D'  # 切换方向
                        MainGame.p1_role.stop = False
                        print("按下下键,向下移动")
                    elif event.key == pygame.K_l:
                        if len(MainGame.p1_bulletlist) < 3:
                            p1bullet = Bullet(MainGame.p1_role)
                            MainGame.p1_bulletlist.append(p1bullet)
                            print('发射子弹')
                    if not MainGame.p2_role:
                        if event.key == pygame.K_e:
                            self.createp2()
                    if MainGame.p2_role and MainGame.p2_role.live:
                        if event.key == pygame.K_a:
                            MainGame.p2_role.direction = 'L'  # 切换方向
                            MainGame.p2_role.stop = False
                            print("按下左键,向左移动")
                        elif event.key == pygame.K_d:
                            MainGame.p2_role.direction = 'R'  # 切换方向
                            MainGame.p2_role.stop = False
                            print("按下右键,向右移动")
                        elif event.key == pygame.K_w:
                            MainGame.p2_role.direction = 'U'  # 切换方向
                            MainGame.p2_role.stop = False
                            print("按下上键,向上移动")
                        elif event.key == pygame.K_s:
                            MainGame.p2_role.direction = 'D'  # 切换方向
                            MainGame.p2_role.stop = False
                            print("按下下键,向下移动")
                        elif event.key == pygame.K_SPACE:
                            if len(MainGame.p2_bulletlist) < 3:
                                p2bullet = Bullet(MainGame.p2_role)
                                MainGame.p2_bulletlist.append(p2bullet)
                                print('发射子弹')
            if event.type == pygame.KEYUP:
                # 判断松开的键是上、下、左、右键时候才停止移动
                if event.key == pygame.K_UP \
                        or event.key == pygame.K_DOWN \
                        or event.key == pygame.K_LEFT \
                        or event.key == pygame.K_RIGHT:
                    if MainGame.p1_role and MainGame.p1_role.live:
                        MainGame.p1_role.stop = True
            if event.type == pygame.KEYUP:
                # 判断松开的键是上、下、左、右键时候才停止移动
                if event.key == pygame.K_w \
                        or event.key == pygame.K_s \
                        or event.key == pygame.K_a \
                        or event.key == pygame.K_d:
                    if MainGame.p2_role and MainGame.p2_role.live:
                        MainGame.p2_role.stop = True

    def createp1(self):
        MainGame.p1_role = P1(350, 300)

    def createp2(self):
        MainGame.p2_role= P2(350, 300)

    def createtarget(self):
        top = 100
        for i in range(MainGame.targetcount):  # 循环生成敌方坦克
            left = random.randint(0, 600)
            speed = random.randint(1, 4)
            tar = Target(top, left, speed)
            MainGame.targetlist.append(tar)
    def blitTarget(self):
        for target in MainGame.targetlist:
            if target.live:
                target.displayRole()
                target.randMove()
                target.hitWall()
                targetbullet = target.shoot()
                if MainGame.p1_role and MainGame.p1_role.live:
                    target.target_hit_p1()
                if targetbullet:  # 敌方子弹是否是None,如果不为None则添加到敌方子弹列表中#3.13.2024
                    MainGame.targetlist.append(targetbullet)
            else:
                MainGame.targetlist.remove(target)
    def p1_bullet(self):
        for p1_bullet in MainGame.p1_bulletlist:
            if p1_bullet.live:
                p1_bullet.displayBullet()
                p1_bullet.move()
                p1_bullet.myBullet_hit_target()
                p1_bullet.bullethitWall()
            else:
                MainGame.p1_bulletlist.remove(p1_bullet)
    def p2_bullet(self):
        for p2_bullet in MainGame.p2_bulletlist:
            if p2_bullet.live:
                p2_bullet.displayBullet()
                p2_bullet.move()
                p2_bullet.myBullet_hit_target()
                p2_bullet.bullethitWall()
            else:
                MainGame.p2_bulletlist.remove(p2_bullet)
    def blittargetbullet(self):
        for targetbullet in MainGame.targetbulletlist:
            if targetbullet.live:
                targetbullet.displayBullet()
                targetbullet.move()
                targetbullet.target_hit_p1()  # 调用子弹与我方碰撞的方法
                targetbullet.bullethitWall()  # 调用敌方子弹与墙壁碰撞方法
            else:
                MainGame.targetbulletlist.remove(targetbullet)
    def blitExplode(self):
        for explode in MainGame.explodelist:
            if explode.live:
                explode.displayExplode()
            else:
                MainGame.explodelist.remove(explode)
    def createWall(self):
        for i in range(6):
            wall = Wall(i * 130, 220)
            MainGame.walllist.append(wall)
    def blitWall(self):
        for wall in MainGame.walllist:
            if wall.live:
                wall.displayWall()
            else:
                MainGame.walllist.remove(wall)


class Button():
    def __init__(self, left, top, filename):  # 初始化该按钮,包括加载图片,初始位置,按钮大小
        self.image = pygame.image.load(filename)
        self.rect = self.image.get_rect()  # 获取图片的区域
        self.rect.left = left
        self.rect.top = top
    def isOver(self):  # 判断鼠标是否放在该按钮上
        point_x, point_y = pygame.mouse.get_pos()
        x = self.rect.left
        y = self.rect.top
        w, h = self.image.get_size()
        in_x = x < point_x < x + w
        in_y = y < point_y < y + h
        return in_x and in_y
    def displayButton(self):
        MainGame.window.blit(self.image, self.rect)
class Role_p1(BaseItem):
    def __init__(self,top,left):
        self.images = {
            "U": pygame.image.load("images/p1up.png"),
            "D": pygame.image.load("images/p1down.png"),
            "L": pygame.image.load("images/p1left.png"),
            "R": pygame.image.load("images/p1right.png"),
        }
        self.direction = "U"
        self.image = self.images[self.direction]  # 初始化方向

        self.rect = self.image.get_rect()  # 获取图片的区域
        self.rect.left = left
        self.rect.top = top

        self.speed = 5  # 初始化速度

        self.stop = True

        self.live = True

        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top

    def move(self):
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top
        if self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
        elif self.direction == 'D':
            if self.rect.top + self.rect.height < screen_lenth:
                self.rect.top += self.speed
        elif self.direction == 'R':
            if self.rect.left + self.rect.height < screen_width:
                self.rect.left += self.speed
    def shoot(self):
        return Bullet(self)

    def stay(self):
        self.rect.left = self.oldLeft
        self.rect.top = self.oldTop

    def hitWall(self):
        for wall in MainGame.walllist:
            if pygame.sprite.collide_rect(self, wall):
                self.stay()

    def displayRole(self):
        self.image = self.images[self.direction]
        MainGame.window.blit(self.image, self.rect)
class P1(Role_p1):
    def __init__(self, top,left):
        super(P1, self).__init__(top,left)

    def p1_hit_target(self):  # 检测是否与目标相撞
        for target in MainGame.targetlist:
            if pygame.sprite.collide_rect(self, target):
                self.stay()


class Role_p2(BaseItem):
    def __init__(self,top,left):
        self.images = {
            "U": pygame.image.load("images/p2up.png"),
            "D": pygame.image.load("images/p2down.png"),
            "L": pygame.image.load("images/p2left.png"),
            "R": pygame.image.load("images/p2right.png"),
        }
        self.direction = "U"
        self.image = self.images[self.direction]  # 初始化方向

        self.rect = self.image.get_rect()  # 获取图片的区域
        self.rect.left = left
        self.rect.top = top

        self.speed = 5  # 初始化速度

        self.stop = True

        self.live = True

        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top

    def move(self):
        self.oldLeft = self.rect.left
        self.oldTop = self.rect.top
        if self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
        elif self.direction == 'D':
            if self.rect.top + self.rect.height < screen_lenth:
                self.rect.top += self.speed
        elif self.direction == 'R':
            if self.rect.left + self.rect.height < screen_width:
                self.rect.left += self.speed
    def shoot(self):
        return Bullet(self)

    def stay(self):
        self.rect.left = self.oldLeft
        self.rect.top = self.oldTop
    def hitWall(self):
        for wall in MainGame.walllist:
            if pygame.sprite.collide_rect(self, wall):
                self.stay()
    def displayRole(self):
        self.image = self.images[self.direction]
        MainGame.window.blit(self.image, self.rect)
class P2(Role_p2):
    def __init__(self, top,left):
        super(P2, self).__init__(top,left)

    def p2_hit_target(self):  # 检测是否与目标相撞
        for target in MainGame.targetlist:
            if pygame.sprite.collide_rect(self, target):
                self.stay()
class Target(Role_p1):
    def __init__(self, top,left,speed):
        super(Target, self).__init__(top,left)
        self.images = {
            'U': pygame.image.load('images/pig.png'),
            'D': pygame.image.load('images/pig.png'),
            'L': pygame.image.load('images/pig.png'),
            'R': pygame.image.load('images/pig.png'),
        }
        self.direction = self.randDirection()  # 方向,随机生成目标
        self.image = self.images[self.direction]  # 根据方向获取图片
        self.rect = self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        self.speed = speed
        self.flag = True  # 移动开关
        self.step = 60  # 移动步数

    def target_hit_p1(self):  # 检测目标是否与角色相撞
        if pygame.sprite.collide_rect(self, MainGame.p1_role):
            self.stay()

    def target_hit_p2(self):  # 检测目标是否与角色相撞
        if pygame.sprite.collide_rect(self, MainGame.p2_role):
            self.stay()

    def randDirection(self):  # 随机方向
        num = random.randint(1, 4)
        if num == 1:
            return 'U'
        elif num == 2:
            return 'D'
        elif num == 3:
            return "L"
        elif num == 4:
            return 'R'

    def randMove(self):  # 随机移动
        if self.step <= 0:
            self.direction = self.randDirection()
            self.step = 60  # 步数复位
        else:
            self.move()
            self.step -= 1

    def shoot(self):
        num = random.randint(1, 50)  # 随机生成50以内的数
        if num < 3:
            return Bullet(self)
class Bullet(BaseItem):
    def __init__(self,role):
        self.image = pygame.image.load("images/zidan.png")
        self.direction =role.direction  # 坦克的方向决定子弹的方向
        self.rect = self.image.get_rect()
        if self.direction == 'U':
            self.rect.left = int(role.rect.left + role.rect.width / 2 - self.rect.width / 2)
            self.rect.top = role.rect.top - self.rect.height
        elif self.direction == 'D':
            self.rect.left = int(role.rect.left + role.rect.width / 2 - self.rect.width / 2)
            self.rect.top = role.rect.top + role.rect.height
        elif self.direction == 'L':
            self.rect.left = int(role.rect.left - self.rect.width / 2 - self.rect.width / 2)
            self.rect.top = int(role.rect.top + role.rect.width / 2 - self.rect.width / 2)
        elif self.direction == 'R':
            self.rect.left = role.rect.left + role.rect.width
            self.rect.top = int(role.rect.top + role.rect.width / 2 - self.rect.width / 2)
        self.speed = 6
        self.live = True
    def move(self):
        if self.direction == 'U':
            if self.rect.top > 0:
                self.rect.top -= self.speed
            else:
                self.live = False
        elif self.direction == 'R':
            if self.rect.left + self.rect.width < screen_width:
                self.rect.left += self.speed
            else:
                self.live = False
        elif self.direction == 'D':
            if self.rect.top + self.rect.height < screen_lenth:
                self.rect.top += self.speed
            else:
                self.live = False
        elif self.direction == 'L':
            if self.rect.left > 0:
                self.rect.left -= self.speed
            else:
                self.live = False

    def bullethitWall(self):  # 检测子弹与墙壁碰撞
        for wall in MainGame.walllist:
            if pygame.sprite.collide_rect(self, wall):
                self.live = False
                wall.hp -= 1  # 墙壁的生命值减小
                if wall.hp <= 0:
                    wall.live = False

    def displayBullet(self):
        MainGame.window.blit(self.image, self.rect)

    def myBullet_hit_target(self):  # 我方子弹与目标发生碰撞
        for target in MainGame.targetlist:
            if pygame.sprite.collide_rect(target, self):
                self.live = False  # 修改目标和我方子弹的状态
                target.live = False
                explode = Explode(target)  # 创建爆炸对象
                MainGame.explodelist.append(explode)
    def target_hit_p1(self):  # 敌方子弹与我方的碰撞
        if MainGame.p1_role and MainGame.p1_role.live:
            if pygame.sprite.collide_rect(MainGame.p1_role, self):
                self.live = False
                MainGame.p1_role.live = False
                explode = Explode(MainGame.p1_role)
                MainGame.explodelist.append(explode)

    def target_hit_p2(self):  # 敌方子弹与我方的碰撞
        if MainGame.p2_role and MainGame.p2_role.live:
            if pygame.sprite.collide_rect(MainGame.p2_role, self):
                self.live = False
                MainGame.p2_role.live = False
                explode = Explode(MainGame.p2_role)
                MainGame.explodelist.append(explode)
class Explode():
    def __init__(self,role):
        self.rect = role.rect  # 爆炸的位置由当前子弹打中的位置决定
        self.images = [
            pygame.image.load('images/boom.png'),
            pygame.image.load('images/boom.png'),
            pygame.image.load('images/boom.png'),
            pygame.image.load('images/boom.png'),
            pygame.image.load('images/boom.png'),
        ]
        self.step = 0
        self.image = self.images[self.step]
        self.live = True
    def displayExplode(self):
        if self.step < len(self.images):
            self.image = self.images[self.step]
            self.step += 1
            MainGame.window.blit(self.image, self.rect)
        else:
            self.live = False
            self.step = 0  # 复位
class Wall():
    def __init__(self, left, top):
        self.image = pygame.image.load('images/wall.png')
        self.rect = self.image.get_rect()
        self.rect.left = left
        self.rect.top = top
        self.live = True
        self.hp = 3  # 设置墙壁生命值

    def displayWall(self):
        MainGame.window.blit(self.image, self.rect)
if __name__ == "__main__":
    MainGame().startsurface()
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/9581cfb5dd0842d4ac5f4445301a7ca0.png "#left")





接上个问题进行提问 实在找不出来bug了

  • 写回答

4条回答 默认 最新

  • GISer Liu 2024-03-26 16:09
    关注

    该回答引用自GPT-3.5,由博主GISer Liu编写:

    根据您提供的代码,您想创建一个类似坦克大战的游戏。从代码看,存在一些问题,我会逐个解释并给出修改建议:

    1. BaseItem 类没有完整的实现,它应该是一个基类,用于其他游戏对象的继承。在 BaseItem 类中,您应该至少包含 colorwidthheight 这些属性,并实现 draw 方法用于绘制游戏对象。
    2. MainGame 类的 startsurface 方法中,var = pygame.display.init 这行代码没有实际作用,应该删除。在按钮的创建过程中,缺少 Button 类的定义和实现,需要添加或导入。此外,MainGame 类中的图片路径可能需要根据实际情况调整,确保图片能正确加载。
    3. MainGame 类的 startGame 方法中,var = pygame.display.init 这行代码也没有实际作用,应删除。游戏循环中,time.sleep(0.02) 的作用是降低循环速度,但这种方式并不是最好的做法,可以考虑使用 pygame.time.Clock 控制帧率。同时,self.getEvent() 应该在循环外部调用,以确保事件能够及时响应。
    4. MainGame 类中的一些方法(如 createp1createp2createtargetcreateWallp1_bulletp2_bulletblittargetbulletblitExplodeblitWall)没有给出具体实现,如果这些方法是用来创建游戏对象或处理游戏逻辑的,需要完善这些方法的内容。
    5. MainGame 类中的部分代码存在重复,例如两次判断 MainGame.p1_role and MainGame.p1_role.live,可以考虑优化为单次判断。
    6. MainGame 类中,使用 del MainGame.p1_roleMainGame.p1_role = None 的方式来删除和重新初始化角色对象可能会导致潜在的问题,建议使用其他方式来处理对象的创建和销毁。
    7. MainGame 类中的 getTextSurface 方法在每次调用时都会重新初始化字体模块,这会导致性能问题。建议将 pygame.font.init() 移至 MainGame 类的初始化方法中,并将字体对象作为类属性,避免重复初始化。
    8. MainGame 类中的 getEvent 方法中,部分按键事件处理代码存在缩进错误

    如果该回答解决了您的问题,请采纳!如果没有,请参考以下方案进行修订

    用户答题指南

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

问题事件

  • 系统已结题 5月1日
  • 已采纳回答 4月23日
  • 创建了问题 3月20日

悬赏问题

  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境