会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132428个问题
JAVA 全系列/第三阶段:数据库编程/SQL 语言 32509楼
JAVA 全系列/第九阶段:Spring Boot实战/Spring Boot 32511楼

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

bg =pygame.Color(0,0,0)  # 背景颜色
text_color = pygame.Color(255,0,0)  # 文字颜色
screen_width = 800;screen_height = 500
# 创建一个基类
class BaseItem(Sprite):
    def __init__(self,color,width,height):
        pygame.sprite.Sprite.__init__(self)
# 搭建主程序
class MainGame(object):
    window = None
    my_tank=None
    # 创建存储敌方坦克的列表
    enemyTankList = []
    # 定义敌方坦克的数量
    enemyTankCount = 5
    # 存储我方子弹的列表
    myBulletlist= []
    # 储存敌方坦克列表
    enemyBulletList =[]
    # 存储爆炸效果的列表
    explodeList = []
    # 存储墙壁的列表
    wallList=[]
    def __init__(self):
        pass
    # 开始游戏
    def startGame(self):
        # 初始化窗口
        pygame.display.init()
        # 设置窗口大小及显示
        MainGame.window=pygame.display.set_mode((screen_width,screen_height))
        # 初始化我方坦克
        self.createMytank()
        # 初始化敌方坦克,并添加到敌方坦克列表
        self.createEnemyTank()
        # 初始化墙壁
        self.createWall()
        # 设置窗口标题
        pygame.display.set_caption('坦克大战1.0')
        while True:
            # 是循环慢一点
            time.sleep(0.03)
            # 给窗口设置填充色
            MainGame.window.fill(bg)
            # 获取事件
            self.getEvent()
            # 绘制文字
            MainGame.window.blit(self.getTextSuface('敌方坦克剩余数量:%d'%len(MainGame.enemyTankList)),(10,10))
            # 调用显示我方坦克
            # 判断我方坦克是否存活
            if MainGame.my_tank and MainGame.my_tank.live:
                MainGame.my_tank.displayTank()
            else:
                # 删除我方坦克
                del MainGame.my_tank
                MainGame.my_tank = None
            # 循环遍历敌方坦克列表,显示敌方坦克
            self.blitEnemyTank()
            # 循环遍历显示我方坦克的子弹
            self.bulitMyBullet()
            # 循环遍历显示敌方坦克的子弹
            self.bulitenemyBullet()
            # 循环遍历爆炸列表,展示爆炸效果
            self.blitExplode()
            # 循环遍历显示墙壁列表
            self.blitWall()
            # 调用移动方法
            if MainGame.my_tank and MainGame.my_tank.live:
                if not MainGame.my_tank.stop:
                    MainGame.my_tank.move()
                    # 检测我方坦克是否与墙壁发生碰撞
                    MainGame.my_tank.hitWall()
                    # 检测我方坦克是否与敌方坦克发生碰撞
                    MainGame.my_tank.myTank_hit_enemyTank()
            # 刷新屏幕
            pygame.display.update()
    # 循环遍历显示墙壁列表
    def blitWall(self):
        for wall in MainGame.wallList:
            # 判断墙壁是否存活
            if wall.live:
                # 调用墙壁的显示方法
                wall.displayWall()
            else:
                # 从墙壁列表移除
                MainGame.wallList.remove(wall)
    # 初始化墙壁
    def createWall(self):
        for i in range(6):
            wall=Wall(i*132,220)
            # 将墙壁添加到列表中
            MainGame.wallList.append(wall)
    # 创建我方坦克的方法
    def createMytank(self):
        MainGame.my_tank = MyTank(screen_width / 2-3, screen_height / 2+35)
        # 创建Music对象
        music=Music('../img/start.wav')
        # 播放音乐
        music.play()
    # 初始化敌方坦克,并添加到敌方坦克列表
    def createEnemyTank(self):
        top = 100
        # 循环生成敌方坦克
        for i in range(MainGame.enemyTankCount):
            left = random.randint(0,screen_width-100)
            speed = random.randint(1,4)
            enemy = EnemyTank(left,top,speed)
            MainGame.enemyTankList.append(enemy)
    # 循环展示爆炸效果
    def blitExplode(self):
        for explode in MainGame.explodeList:
            # 判断是否活着
            if explode.live:
                explode.displayExplode()
            else:
                # 在爆炸效果中移除
                MainGame.explodeList.remove(explode)
    # 循环遍历敌方坦克列表,显示敌方坦克
    def blitEnemyTank(self):
        for enemyTank in MainGame.enemyTankList:
            # 判断敌方坦克是否活着
            if enemyTank.live:
                enemyTank.displayTank()
                enemyTank.randMove()
                # 检测敌方坦克是否与墙壁发生碰撞
                enemyTank.hitWall()
                # 检测敌方坦克是否与我方坦克发生碰撞
                if MainGame.my_tank and MainGame.my_tank.live:
                    enemyTank.enemyTank_hit_myTank()
                # 发射子弹
                enemyBullet = enemyTank.shot()
                # 判断敌方子弹是否为None
                if enemyBullet:
                    # 将敌方子弹存储到敌方列表
                    MainGame.enemyBulletList.append(enemyBullet)
                    # 检测敌方子弹是否与墙壁碰撞
                    enemyBullet.hitWall()
            else:
                MainGame.enemyTankList.remove(enemyTank)
    # 循环遍历我方子弹存储列表
    def bulitMyBullet(self):
        for myBullet in MainGame.myBulletlist:
            # 判断当前子弹是否活着状态,如果活着,显示及移动
            if myBullet.live:
                myBullet.displayBullet()
                # 调用子弹的移动方法
                myBullet.move()
                # 检测我方子弹是否与敌方坦克发生碰撞
                myBullet.myBullet_hit_enenmyTank()
                # 检测我方子弹是否与墙壁碰撞
                myBullet.hitWall()
            else:
                MainGame.myBulletlist.remove(myBullet)
    # 循环遍历敌方子弹储存列表
    def bulitenemyBullet(self):
        for enemyBullet in MainGame.enemyBulletList:
            # 判断敌方子弹是否存活
            if enemyBullet.live:
                enemyBullet.displayBullet()
                enemyBullet.move()
                # 调用敌方子弹与我方坦克碰撞的方法
                enemyBullet.enemyBullet_hit_myTank()
            else:
                MainGame.enemyBulletList.remove(enemyBullet)
    # 结束游戏
    def endGame(self):
        print('谢谢使用,欢迎下次光临')
        exit()
    # 左上角文字的绘制
    def getTextSuface(self,text):
        # 初始化字体模块
        pygame.font.init()
        # 获取font文字对象
        font=pygame.font.SysFont('kaiti',20)
        # 绘制文字信息
        textSurface=font.render(text,True,text_color)
        return textSurface
    # 获取事件
    def getEvent(self):
        # 获取所有事件
        eventList=pygame.event.get()
        # 遍历事件
        for event in eventList:
            # QUIT 表示用户按下关闭按钮
            if event.type == pygame.QUIT:
                self.endGame()
            # KEYDOWN 表示按下键
            if event.type == pygame.KEYDOWN:
                # 当坦克不存在或者死亡
                if not MainGame.my_tank:
                    # 判断按下的是Esc键,让坦克重生
                    if event.key == pygame.K_ESCAPE:
                        # 让我方坦克重生
                        self.createMytank()
                if MainGame.my_tank and MainGame.my_tank.live:
                    # K_LEFT 表示向左,K_LEFT 表示向右,K_UP 表示向上,K_DOWN表示向下
                    if event.key == pygame.K_LEFT:
                        # 切换方向
                        MainGame.my_tank.direction = 'L'
                        # 修改坦克的开关
                        MainGame.my_tank.stop=False
                    elif event.key == pygame.K_RIGHT:
                        MainGame.my_tank.direction = 'R'
                        # 修改坦克的开关
                        MainGame.my_tank.stop = False
                    elif event.key == pygame.K_UP:
                        MainGame.my_tank.direction = 'U'
                        # 修改坦克的开关
                        MainGame.my_tank.stop = False
                    elif event.key == pygame.K_DOWN:
                        MainGame.my_tank.direction = 'D'
                        # 修改坦克的开关
                        MainGame.my_tank.stop = False
                    elif event.key == pygame.K_SPACE:
                        # 如果当前我方子弹列表大小小于等于3时可以发射子弹
                        if len(MainGame.myBulletlist) < 3:
                            # 创建我方坦克发射子弹
                            my_bullet=Bullet(MainGame.my_tank)
                            MainGame.myBulletlist.append(my_bullet)
                            music=Music('../img/hit.wav')
                            music.play()
            # 松开方向键,坦克停止移动,修改坦克的开关状态
            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.my_tank and MainGame.my_tank.live:
                        MainGame.my_tank.stop = True
# 坦克类
class Tank(BaseItem):
    # 添加位置
    def __init__(self,left,top):
        # 保存加载图片
        self.images={
            'U': pygame.image.load('../img/p1tankU.gif'),
            'D': pygame.image.load('../img/p1tankD.gif'),
            'L': pygame.image.load('../img/p1tankL.gif'),
            'R': pygame.image.load('../img/p1tankR.gif')
        }
        # 设置初始图片方向
        self.direction = 'U'
        # 根据当前图片获取图片
        self.image=self.images[self.direction]
        # 根据当前图片获取区域
        self.rect=self.image.get_rect()
        # 设置区域的left和top
        self.rect.left = left
        self.rect.top = top
        # 移动速度
        self.speed=3
        # 坦克移动的开关
        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 == 'R':
            if self.rect.left < screen_width-self.rect.width:
                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< screen_height-self.rect.height:
                self.rect.top += self.speed
    # 射击
    def shot(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 displayTank(self):
        # 获取展示的对象
        self.image=self.images[self.direction]
        # 调用blit方法展示
        MainGame.window.blit(self.image,self.rect)
# 我方坦克
class MyTank(Tank):
    def __init__(self,left,top):
        super(MyTank, self).__init__(left,top)
    # 检测我方坦克与敌方坦克发生碰撞
    def myTank_hit_enemyTank(self):
        # 循环遍历敌方坦克列表
        for enemyTank in MainGame.enemyTankList:
            if pygame.sprite.collide_rect(self,enemyTank):
                self.stay()
# 敌方坦克
class EnemyTank(Tank):
    def __init__(self,left,top,speed):
        # 调用父类的初始化方法
        super(EnemyTank, self).__init__(left,top)
        # 加载图片集
        self.images={
            'U':pygame.image.load('../img/enemy1U.gif'),
            'D': pygame.image.load('../img/enemy1D.gif'),
            'L': pygame.image.load('../img/enemy1L.gif'),
            'R': pygame.image.load('../img/enemy1R.gif')
        }
        # 方向,随机生成敌方坦克方向
        self.direction = self.randDirection()
        # 根据方向获取图片
        self.image = self.images[self.direction]
        # 区域
        self.rect = self.image.get_rect()
        # 对top和left进行赋值
        self.rect.left = left
        self.rect.top = top
        # 速度
        self.speed = speed
        # 开关键
        self.flag = True
        # 步数初始值
        self.step = 40
    # 敌方坦克与我方坦克是否发生碰撞
    def enemyTank_hit_myTank(self):
        if pygame.sprite.collide_rect(self,MainGame.my_tank):
            self.stay()
    # 随机生成敌方坦克方向
    def randDirection(self):
        num =random.randint(1,4)
        if num == 1:
            return 'U'
        elif num == 2:
            return 'D'
        elif num == 3:
            return 'R'
        elif num == 4:
            return 'L'
    # 敌方坦克随机移动
    def randMove(self):
        if self.step <= 0:
            self.direction = self.randDirection()
            self.step = 40
        else:
            self.move()
            self.step -= 1
    # 重写shot方法
    def shot(self):
        # 随机生成100以内的数
        num = random.randint(1,100)
        if num < 5:
            return Bullet(self)
# 子弹类
class Bullet(BaseItem):
    def __init__(self,tank):
        # 加载图片
        self.image=pygame.image.load('../img/enemymissile.gif')
        # 坦克的方向决定子弹的方向
        self.direction = tank.direction
        # 获取区域
        self.rect = self.image.get_rect()
        # 子弹的left和top与方向有关
        if self.direction =='U':
            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.direction =='D':
            self.rect.left = tank.rect.left+tank.rect.width/2-self.rect.width/2
            self.rect.top=tank.rect.top+tank.rect.height
        elif self.direction =='L':
            self.rect.left=tank.rect.left-self.rect.width/2-self.rect.width/2
            self.rect.top=tank.rect.top+tank.rect.width/2-self.rect.width/2
        elif self.direction =='R':
            self.rect.left = tank.rect.left+tank.rect.width
            self.rect.top=tank.rect.top+tank.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_height:
                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 displayBullet(self):
        # 将图片加载到窗口
        MainGame.window.blit(self.image,self.rect)
    # 子弹是否碰到墙壁
    def hitWall(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 myBullet_hit_enenmyTank(self):
        # 遍历敌方坦克列表,判断是否发生碰撞
        for enemyTank in MainGame.enemyTankList:
            if pygame.sprite.collide_rect(enemyTank,self):
                # 修改敌方坦克和我方子弹的状态
                enemyTank.live = False
                self.live = False
                # 创建爆炸对象
                explode = Explode(enemyTank)
                # 将爆炸效果添加到爆炸列表中
                MainGame.explodeList.append(explode)
    # 敌方子弹与我方坦克的碰撞
    def enemyBullet_hit_myTank(self):
        if MainGame.my_tank and MainGame.my_tank.live:
            if pygame.sprite.collide_rect(MainGame.my_tank,self):
                # 产生爆炸对象
                explode=Explode(MainGame.my_tank)
                # 将爆炸对象添加到爆炸列表中
                MainGame.explodeList.append(explode)
                # 修改敌方子弹与我方坦克的状态
                self.live=False
                MainGame.my_tank.live=False
# 墙壁类
class Wall():
    def __init__(self,left,top):
        # 加载墙壁图片
        self.image=pygame.image.load('../img/steels.gif')
        # 获取墙壁的区域
        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)
# 爆炸类
class Explode():
    def __init__(self,tank):
        # 爆炸的位置由当前子弹打中坦克的位置决定
        self.rect = tank.rect
        self.images = [
            pygame.image.load('../img/blast0.gif'),
            pygame.image.load('../img/blast1.gif'),
            pygame.image.load('../img/blast2.gif'),
            pygame.image.load('../img/blast3.gif'),
            pygame.image.load('../img/blast4.gif')
        ]
        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 Music(object):
    def __init__(self,filename):
        self.filename=filename
        # 初始化音乐混合器
        pygame.mixer.init()
        # 加载音乐
        pygame.mixer.music.load(self.filename)
    # 播放音乐
    def play(self):
        pygame.mixer.music.play()

if __name__ == '__main__':
    MainGame().startGame()

老师,完整的代码已经写好了,运行不报错,但是我发现,敌方坦克发射的子弹有时能穿过墙壁,有时有不能,这是哪里出错了

Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 32514楼

老师:

      你好, 这样的什么原因?

Traceback (most recent call last):

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>

    from tensorflow.python.pywrap_tensorflow_internal import *

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>

    _pywrap_tensorflow_internal = swig_import_helper()

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper

    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)

  File "C:\Programs\Python\Python38\lib\imp.py", line 242, in load_module

    return load_dynamic(name, filename, file)

  File "C:\Programs\Python\Python38\lib\imp.py", line 342, in load_dynamic

    return _load(spec)

ImportError: DLL load failed while importing _pywrap_tensorflow_internal: 找不到指定的模块。


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "C:/Users/george/AppData/Local/Temp/tensorflow_loader.py", line 2, in <module>

    import tensorflow as tf

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\__init__.py", line 41, in <module>

    from tensorflow.python.tools import module_util as _module_util

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\__init__.py", line 50, in <module>

    from tensorflow.python import pywrap_tensorflow

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 69, in <module>

    raise ImportError(msg)

ImportError: Traceback (most recent call last):

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module>

    from tensorflow.python.pywrap_tensorflow_internal import *

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module>

    _pywrap_tensorflow_internal = swig_import_helper()

  File "C:\Programs\Python\Python38\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper

    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)

  File "C:\Programs\Python\Python38\lib\imp.py", line 242, in load_module

    return load_dynamic(name, filename, file)

  File "C:\Programs\Python\Python38\lib\imp.py", line 342, in load_dynamic

    return _load(spec)

ImportError: DLL load failed while importing _pywrap_tensorflow_internal: 找不到指定的模块。



Failed to load the native TensorFlow runtime.


See https://www.tensorflow.org/install/errors


for some common reasons and solutions.  Include the entire stack trace

above this error message when asking for help.


Python 全系列/第二十四阶段:人工智能基础_深度学习理论和实战(旧)/Tensorflow入门与安装 32517楼
Python 全系列/第一阶段:Python入门/编程基本概念 32518楼
Python 全系列/第一阶段:Python入门/编程基本概念 32520楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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