会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132358个问题
Python 全系列/第八阶段:轻量级Web开发利器-Flask框架/Flask高级 121楼

'''

敌方坦克随机发射子弹

'''

导入 pygame

from time import sleep (从时间导入睡眠)

导入随机

来自 Pygame精灵导入 collide_rect


#设置通用属性

BG_COLOR = pygame颜色0,0,0)

SCREEN_WIDTh = 1200

SCREEN_HEIGHT = 800

TEXT_COLOR = pygame色度(255,255,255)


等级 坦克

    '''

    坦克类

    '''      

    def __init__self) -> None

        self 中。live =

    def display_tankself) -> None

        '''

        显示坦克

        '''

        #获取最新坦克的朝向位置图片

        self 中。图片 =self.images.get(self.direction

        MainGame窗口blitself.image,self.rect

    def moveself) -> None

        '''

        坦克的移动

        '''

        if self.direction == “L”

            #判断坦克的位置是否超越左边界

            如果 self.rect.left > 0

            #修改坦克的位置 离左边的距离 - 操作

                self.rect.left = self.rect.left - self.speed

        elif self.direction == “R”

            #判断坦克的位置是否超越右边界

            如果 self.rect.left + self.rect.width < SCREEN_WIDTh

            #修改坦克的位置 离右边的距离 +操作

                self.rect.left = self.rect.left + self.speed

        elif self.direction == “U”

            #判断坦克的位置是否超越上边界

            如果 self.rect.top > 0

            #修改坦克的位置 离上边的距离 - 操作

                self.rect.top = self.rect.top - self.speed

        elif self.direction == “D”

            #判断坦克的位置是否超越上边界

            如果 self.rect.top + self.rect.height < SCREEN_HEIGHT

            #修改坦克的位置 离下边的距离 + 操作

                 self.rect.top = self.rect.top + self.speed

    def shotself) ->

        '''

        坦克的射击

        '''

        pass

   

MyTankTank):

    '''

    我方坦克

    '''

    def __init__(self,left:int,top:int) -> None:

        #设置我方坦克的图片资源

        self.images = {

            'U':pygame.image.load('D://游戏开发/img/p1tankU.gif'),

            'D':pygame.image.load('D://游戏开发/img/p1tankD.gif'),

            'L':pygame.image.load('D://游戏开发/img/p1tankL.gif'),

            'R':pygame.image.load('D://游戏开发/img/p1tankR.gif'),

        }

        #设置我方坦克的方向

        self.direction = 'D'

        #获取图片信息

        self.image = self.images.get(self.direction)

        #获取图片的矩形

        self.rect = self.image.get_rect()

        #设置我方坦克的位置

        self.rect.left = left

        self.rect.top = top

        #设置移动速度

        self.speed = 20

        #设置移动开关,False是不移动,True是移动

        self.remove = False

   

class EnemyTank(Tank):

    '''

    敌方坦克

    '''

   

    def __init__(self,left,top,speed) -> None:

        self.images = {

            'U':pygame.image.load('./img/enemy1U.gif'),

            'D':pygame.image.load('./img/enemy1D.gif'),

            'R':pygame.image.load('./img/enemy1R.gif'),

            'L':pygame.image.load('./img/enemy1L.gif'),

        }

        #设置敌方坦克的方向

        self.direction = self.rand_direction()

        #获取图片信息

        self.image = self.images.get(self.direction)

        #获取图片的矩形

        self.rect = self.image.get_rect()

        #设置敌方坦克的位置

        self.rect.left = left

        self.rect.top = top

        #设置移动速度

        self.speed = speed  

        #设置移动的步长

        self.step = 20

    def rand_direction(self) -> str:

        '''

        生成随机方向

        '''

        choice = random.randint(1,4)

        if choice == 1:

            return 'U'

        elif choice == 2:

            return 'D'

        elif choice == 3:

            return 'R'

        elif choice == 4:

            return 'L'

    def rand_move(self):

        '''

        随机移动

        '''

        #判断步长是否为0

        if self.step <= 0:

            #如果小于0,更换方向

            self.direction = self.rand_direction()

            #重置步长

            self.step = 20

        else:

            #如果大于0,移动

            self.move()

            #步长减一

            self.step -= 1

    def shot(self):

        '''

        敌方坦克的射击

        '''

        num = random.randint(1,100)

        if num < 10:

            return Bullet(self)        

       

   

class Bullet:

    '''

    子弹类

    '''

    def __init__(self,tank) -> None:

        #加载图片

        self.image = pygame.image.load('./img/enemymissile.gif')

        #获取子弹的方向

        self.direcction = tank.direction

        #获取子弹的图形

        self.rect = self.image.get_rect()

        #设置子弹的位置

        if self.direcction == 'L':

            #子弹的位置 = 坦克的位置 - 子弹的宽度

            self.rect.left = tank.rect.left - self.rect.width

            #子弹的位置 = 坦克的位置 +坦克的高度/2 - 子弹的高度/2

            self.rect.top = tank.rect.top + tank.rect.height/2 - self.rect.height/2

        elif self.direcction == 'U':

            #子弹的位置 = 坦克的位置 + 坦克的宽度/2 - 子弹的宽度/2

            self.rect.left = tank.rect.left + tank.rect.width/2 - self.rect.width/2

            #子弹的位置 = 坦克的位置 - 子弹的高度

            self.rect.top = tank.rect.top - self.rect.height

        elif self.direcction == 'R':

            #子弹的位置 = 坦克的位置 + 坦克的宽度

            self.rect.left = tank.rect.left + tank.rect.width

            #子弹的位置 = 坦克的位置 + 坦克的高度/2 - 子弹的高度/2

            self.rect.top = tank.rect.top + tank.rect.height/2 - self.rect.height/2

        elif self.direcction == "D":

            #子弹的位置 = 坦克的位置 + 坦克的宽度/2 - 子弹的宽度/2

            self.rect.left = tank.rect.left + tank.rect.width/2 - self.rect.width/2

            #子弹的位置 = 坦克的位置 + 坦克的高度

            self.rect.top = tank.rect.top + tank.rect.height

        #设置子弹的速度

        self.speed = 10

        #设置子弹的状态

        self.live = True

    def display_bullet(self) -> None:

        '''

        子弹的显示

        '''

        MainGame.window.blit(self.image,self.rect)

       

    def move(self) -> None:

        '''

        子弹的移动

        '''

        #根据子弹生成的方向来去移动

        if self.direcction == "L":

            if self.rect.left > 0 :

                self.rect.left -= self.speed

            else:

                self.live = False

        elif self.direcction == "R":

            if self.rect.left  + self.rect.width < SCREEN_WIDTh:

                self.rect.left += self.speed

            else:

                self.live = False

        elif self.direcction == "U":

            if self.rect.top  > 0:

                self.rect.top -= self.speed

            else:

                self.live = False

        elif self.direcction == "D":

            if self.rect.top + self.rect.height < SCREEN_HEIGHT:

                self.rect.top += self.speed

            else:

                self.live = False

    def hit_enemy_tank(self):

        for e_tank in MainGame.enemy_tank_list:

            #判断子弹是否击中坦克

            if collide_rect(self,e_tank):

                #修改子弹的状态

                self.live = False

                e_tank.live = False

   

class Wall:

    '''

    墙壁类

    '''

    def __init__(self) -> None:

        pass

    def display_wall(self) -> None:

        '''

        墙壁的显示

        '''

        pass

   

class Explode:

    '''

    爆炸效果类

    '''

    def __init__(self) -> None:

        pass

    def display_explode(self) -> None:

        '''

        显示爆炸效果

        '''

        pass

   

class Music:

    '''

    音效类

    '''

    def __init__(self) -> None:

        pass

    def play_music(self) -> None:

        '''

        播放音乐

        '''

        pass

   

class MainGame:

    '''

    游戏主窗口类

    '''

    #游戏主窗口对象

    window = None

    #设置我方坦克

    my_tank = None

    #存储敌方坦克的列表

    enemy_tank_list = []

    #设置敌方坦克的数量

    enemy_tank_count = 6

    #存储我方子弹的列表

    my_bullet_list = []

    #存储敌方子弹的列表

    enemy_bullet_list = []

   

    def __init__(self) -> None:

        pass

    def start_game(self) -> None:

        '''

        开始游戏

        '''

       

        #初始化游戏窗口

        pygame.display.init()

        #创建一个1200*800的窗口

        MainGame.window =  pygame.display.set_mode((SCREEN_WIDTh,SCREEN_HEIGHT))

        #设置窗口标题

        pygame.display.set_caption("坦克大战1.0")

        #创建一个我方坦克

        MainGame.my_tank =MyTank(350,200)

        #创建敌方坦克

        self.create_enemy_tank()

        #刷新窗口

        while True:

            sleep(0.05)

            #给窗口设置填充色

            MainGame.window.fill(BG_COLOR)

            #增加提示文字

            #1.要增加的文字内容

            #num = 6

            text = self.get_text_surface(f'敌方坦克剩余数量{len(MainGame.enemy_tank_list)}')

            #2.如何把文字加上

            MainGame.window.blit(text,(0,0))

            #添加事件

            self.get_event()

            #显示我方坦克

            MainGame.my_tank.display_tank()

            #显示敌方坦克

            self.display_enemy_tank()

            #移动坦克

            if MainGame.my_tank.remove:

                MainGame.my_tank.move()

            # 显示我方子弹

            self.display_my_bullet()

            #显示敌方子弹

            self.display_enemy_bullet()

            pygame.display.update()

           

    def display_my_bullet(self) -> None:

        '''

        显示我方子弹

        '''

        for my_bullet in MainGame.my_bullet_list:

            #判断我方子弹是否存活

            if my_bullet.live:

                #显示我方子弹

                my_bullet.display_bullet()

                #移动我方坦克

                my_bullet.move()

                #判断我方子弹是否集中敌方坦克

                my_bullet.hit_enemy_tank()

            else:

                #从列表中移除

                MainGame.my_bullet_list.remove(my_bullet)

    def create_enemy_tank(self) -> None:

        '''

        创建敌方坦克

        '''

        self.enemy_top = 500

        self.enemy_speed = 6

        for i in range(self.enemy_tank_count):

            #生成坦克的位置

            left = random.randint(0,600)

            speed = random.randint(1,15)

            #创建敌方坦克

            e_tank = EnemyTank(left,self.enemy_top,speed)

            #将敌方坦克添加到列表中

            self.enemy_tank_list.append(e_tank)

   

    def display_enemy_tank(self) -> None:

        '''

        显示敌方坦克

        '''

        for e_tank in self.enemy_tank_list:

            #显示敌方坦克

            e_tank.display_tank()

            #移动敌方坦克

            e_tank.rand_move()

            #发射子弹

            e_bullet = e_tank.shot()

            #判断是否有子弹

            if e_bullet:

                #将子弹增加到列表中

                MainGame.enemy_bullet_list.append(e_bullet)

            else:

                #从列表中删除

                self.enemy_tank_list.remove(e_tank)

           

    def display_enemy_bullet(self) -> None:

        '''

        显示敌方子弹

        '''

        for e_bullet in MainGame.enemy_bullet_list:

            #显示子弹

            if e_bullet.live:

                #如果子弹存活,显示子弹                

                e_bullet.display_bullet()

                e_bullet.move()

            else:

                #如果子弹不存活,从列表中移除

                MainGame.enemy_bullet_list.remove(e_bullet)

       

    def get_text_surface(self,text:str) -> None:

        '''

        获取文字的图片

        '''

        #初始化字体模块

        pygame.font.init()        

        #获取可以使用的字体

        #print(pygame.font.get_fonts())

        #创建字体

        font =pygame.font.SysFont('kaiti',18)

        #绘制文字信息

        text_surface = font.render(text,True,TEXT_COLOR)

        #将绘制的文字信息返回

        return text_surface

   

    def get_event(self) -> None:

        '''

        获取事件

        '''

        #获取所有时间

        event_list = pygame.event.get()

        #遍历事件

        for event in event_list:

            #判断是什么事件,然后做出相应的处理

            if event.type == pygame.QUIT:

                #退出游戏,点击关闭按钮

                self.end_game()

            if event.type ==pygame.KEYDOWN:

                #按下键盘

                if event.key == pygame.K_LEFT:

                    print('坦克像左移动')

                    #修改方向

                    MainGame.my_tank.direction = 'L'

                    #修改为坦克可以移动的状态

                    MainGame.my_tank.remove = True

                elif event.key == pygame.K_RIGHT:

                    print('坦克像右移动')

                    #修改方向

                    MainGame.my_tank.direction = 'R'

                    #修改为坦克可以移动的状态

                    MainGame.my_tank.remove = True

                elif event.key == pygame.K_UP:

                    print('坦克像上移动')

                    #修改方向

                    MainGame.my_tank.direction = 'U'

                    #修改为坦克可以移动的状态

                    MainGame.my_tank.remove = True

                elif event.key == pygame.K_DOWN:

                    print('坦克像下移动')

                    #修改方向

                    MainGame.my_tank.direction = 'D'

                    #修改为坦克可以移动的状态

                    MainGame.my_tank.remove = True

                elif event.key == pygame.K_SPACE:

                    #判断子弹是否上限

                    if len(MainGame.my_bullet_list) < 2:

                        #发射子弹

                        print('发射子弹')

                        #创建子弹

                        m_bullet = Bullet(MainGame.my_tank)

                        #将子弹添加到列表中

                        MainGame.my_bullet_list.append(m_bullet)

                       

            if event.type == pygame.KEYUP and event.key in ((pygame.K_LEFT,pygame.K_RIGHT,pygame.K_UP,pygame.K_DOWN)):

                #修改坦克移动的状态

                MainGame.my_tank.remove = False

                   

    def end_game(self) -> None:

            '''

            结束游戏

            '''  

            print("谢谢使用,欢迎再次使用")

            exit()


    def new_method(self):

        self.end_game()

       

       

   

   

if __name__ == "__main__":

    #调用MainGame类中的start_game方法,开始游戏

    MainGame() 的start_game()

老师,我这里一运行坦克瞬间就消失了,但是没有报错,麻烦您帮我看一下


Python 全系列/第二阶段:Python 深入与提高/坦克大战 122楼
Python 全系列/第一阶段:Python入门/函数和内存分析 123楼
Python 全系列/第十一阶段:重量级Web框架-Django/Django初级 124楼

屏幕截图 2025-03-10 215412.png

Python 全系列/第五阶段:数据库编程/项目-音乐播放器 126楼
Python 全系列/第五阶段:数据库编程/python操作mysql 127楼
Python 全系列/第一阶段:Python入门/函数和内存分析 128楼
Python 全系列/第十五阶段:Python 爬虫开发/Python爬虫基础与应用 129楼
Python 全系列/第一阶段:Python入门/函数和内存分析 132楼
JAVA 全系列/第一阶段:JAVA 快速入门/面向对象详解和JVM底层内存分析 133楼
人工智能/第二阶段:人工智能基础-Python基础/Python开发环境搭建 135楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637