会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132369个问题

'''
新增方法:
 加载主窗口

'''
#导入pygame模块
import pygame
# #pygame官方网站:www.pygame.org
SCREEN_WIDTH=700
SCREEN_HEIGHT=500
class MianGame():
#主类
    window=None
    def __init__(self):
        pass
#开始游戏

    def Startgame(self):
        pass
        #加载主窗口
        pygame.display.init()
        MianGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
#结束游戏

    def Endgame(self):
        pass
class Tank():
    #坦克类
    def __init__(self):
        pass
    #移动
    def move(self):
        pass
    #射击
    def shoot(self):
        pass
    #展示坦克的方法
    def displayTank(self):
        pass

    #我方坦克类,继承的是坦克类
class MyTank(Tank):
    def __init__(self):
        pass

    #敌方坦克
class EnemyTank(Tank):
    def __init__(self):
        pass

    #子弹类
class Bullet():
    def __init__(self):
        pass
    #移动子弹的方法
    def MoveBullet(self):
        pass
    #展示子弹的方法
    def displayBullet(self):
        pass

    #墙壁类
class wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displaywall(self):
        pass

    #爆炸类
class Explode():
    def __init__(self):
        pass
    #展示爆炸效果的方法
    def displayExlpode(self):
        pass
    #音效类
class Music():
    def __init__(self):
        pass
    #展示音效的方法
    def displayMusic(self):
        pass
if '_name_'=='_main_':
    MianGame().Startgame()

老师,我的窗口加载不出来,没有报错

blob.png

Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1816楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1817楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1819楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1820楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 1821楼

image.png

老师,Bullet类里面,给了默认的属性tank。系统怎么知道这个tank指的就是坦克呢,我在上面的代码里头没有找到tank的定义呀?

"""
坦克大战游戏的需求
1.项目中有哪些类
1)坦克类(我方,敌方)
①射击
②移动
③显示坦克的方法
2)子弹类
①移动
②显示子弹的方法
3)墙壁类
属性:是否可以通过
4)爆炸效果类
展示爆炸效果
5)音效类
播放音乐
6)主类
开始游戏
结束游戏

2.每个类中有哪些方法
"""
"""
新增功能:
    完成我方坦克发射子弹
    
"""
#导入pygame模块
import pygame
import time
import random
SCREEM_WIDTH=700
SCREEN_HEIGHT=500
BG_COLOR=pygame.Color(0,0,0)
TEXT_COLOR=pygame.Color(255,0,0)
class MainGame():

    window=None
    my_tank=None
    #存储敌方坦克的列表
    enemyTankList=[]
    #定义坦克的数量
    enemyTankCount=5
    #存储我方子弹的列表
    myBulletList=[]
    def __init__(self):
        pass
    #开始游戏
    def startGame(self):
        #加载主窗口
        pygame.display.init()
        #设置窗口的大小及显示
        MainGame.window = pygame.display.set_mode([SCREEM_WIDTH,SCREEN_HEIGHT])
        #初始化我方坦克
        MainGame.my_tank=Tank(350,250)
        #初始化敌方坦克,并将敌方坦克添加到列表中
        self.createEnemyTank()
        #设置窗口的标题
        pygame.display.set_caption("坦克大战1.03")
        while True:
            #时坦克的移动速度慢一点
            time.sleep(0.02)
            #给窗口设置填充色
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSurface("敌方坦克剩余数量%d"%len(MainGame.enemyTankList)),(10,10))
            #调用坦克的显示方法
            MainGame.my_tank.displayTank()
            #循环遍历敌方坦克列表,展示敌方坦克
            self.blitEnemyTank()
            #循环遍历我方坦克的子弹
            self.blitMyBullet()
            #调用移动方法
            #如果坦卡的开关是开启,才可以移动
            if not MainGame.my_tank.stop:
                MainGame.my_tank.move()
            pygame.display.update()

    #初始化敌方坦克,并将敌方坦克添加到列表中
    def createEnemyTank(self):
        top=100
        #循环生成敌方坦克
        for i in range(MainGame.enemyTankCount):
            left=random.randint(0,600)
            speed=random.randint(1,4)
            enemy=EnemyTank(left,top,speed)
            MainGame.enemyTankList.append(enemy)

    #循环遍历敌方坦克的列表,展示敌方坦克
    def blitEnemyTank(self):
        for enemyTank in MainGame.enemyTankList:
            enemyTank.displayTank()
            enemyTank.randMove()

    #循环遍历我方子弹存储列表
    def blitMyBullet(self):
        for myBullet in MainGame.myBulletList:
            myBullet.displayBullet()

    #结束游戏
    def endGame(self):
        print("谢谢使用,欢迎再次使用")
        exit()

    #左上角文字的绘制
    def getTextSurface(self,text):
        #初始化字体模块
        pygame.font.init()
        #查看所有的字体名称
        #print(pygame.font.get_fonts())
        #获取字体的Font对象
        font=pygame.font.SysFont("kaiti",18)
        #绘制文字信息
        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 event.key == pygame.K_LEFT:
                    #切换方向
                    MainGame.my_tank.direction="L"
                    #将坦克开启
                    MainGame.my_tank.stop = False
                #   MainGame.my_tank.move()
                    print("按下左键,坦克向左移动")
                elif event.key == pygame.K_RIGHT:
                    MainGame.my_tank.direction = "R"
                    # 将坦克开启
                    MainGame.my_tank.stop = False
                #    MainGame.my_tank.move()
                    print("按下右键,坦克向右移动")
                elif event.key == pygame.K_UP:
                    MainGame.my_tank.direction = "U"
                    # 将坦克开启
                    MainGame.my_tank.stop = False
                #    MainGame.my_tank.move()
                    print("按下上键,坦克向上移动")
                elif event.key == pygame.K_DOWN:
                    MainGame.my_tank.direction = "D"
                    # 将坦克开启
                    MainGame.my_tank.stop = False
                #    MainGame.my_tank.move()
                    print("按下下键,坦克向下移动")
                #发射子弹
                elif event.key == pygame.K_SPACE:
                    print("发射子弹")
                    #创建我方坦克发射的子弹
                    myBullet=Bullet(MainGame.my_tank)
                    MainGame.myBulletList.append(myBullet)

            #松开方向键,坦克移动停止,将坦克修改为关闭状态
            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:
                    MainGame.my_tank.stop = True

class Tank():
    #添加距离左边left 距离上边top
    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=5
        #坦克移动的开关
        self.stop=True
    #移动
    def move(self):
        #判断坦克的方向来进行移动
        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_HEIGHT:
                self.rect.top+=self.speed
        elif self.direction=="R":
            if self.rect.left+self.rect.height<SCREEM_WIDTH:
                self.rect.left+=self.speed
    #射击
    def shot(self):
        pass

    #展示坦克的方法
    def displayTank(self):
        #获取展示的对象
        self.image=self.images[self.direction]
        #调用blit方法
        MainGame.window.blit(self.image,self.rect)


#我方坦克
class MyTank(Tank):
    def __init__(self):
        pass

#敌方坦克
class EnemyTank(Tank):
    def __init__(self,left,top,speed):
        #加载图片集
        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()
        #对left和top进行赋值
        self.rect.left=left
        self.rect.top=top
        #速度
        self.speed=speed
        #移动开关键
        self.flag=True
        #新增一个步数变量 step
        self.step=20

    #随机生成坦克的方向
    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


#子弹类
class Bullet():
    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

    #移动
    def move(self):
        pass
    #展示子弹的方法
    def displayBullet(self):
        #将图片surface加载到窗口
        MainGame.window.blit(self.image,self.rect)

#墙壁
class Wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displayWall(self):
        pass

#爆炸效果
class Explode():
    def __init__(self):
        pass

#音效
class Music():
    def __init__(self):
        pass
    #播放音乐
    def play(self):
        pass

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


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 1822楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1823楼
Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1825楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 1826楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 1827楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 1828楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 1829楼

image.png

Collecting pyinstaller

  Downloading pyinstaller-4.1.tar.gz (3.5 MB)


ERROR: Exception:

Traceback (most recent call last):

  File "C:\Program Files\Python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 425, in _error_catcher

    yield

  File "C:\Program Files\Python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 507, in read

    data = self._fp.read(amt) if not fp_closed else b""

  File "C:\Program Files\Python38\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read

    data = self.__fp.read(amt)

  File "C:\Program Files\Python38\lib\http\client.py", line 458, in read

    n = self.readinto(b)

  File "C:\Program Files\Python38\lib\http\client.py", line 502, in readinto

    n = self.fp.readinto(b)

  File "C:\Program Files\Python38\lib\socket.py", line 669, in readinto

    return self._sock.recv_into(b)

  File "C:\Program Files\Python38\lib\ssl.py", line 1241, in recv_into

    return self.read(nbytes, buffer)

  File "C:\Program Files\Python38\lib\ssl.py", line 1099, in read

    return self._sslobj.read(len, buffer)

ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。


During handling of the above exception, another exception occurred:


Traceback (most recent call last):

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in _main

    status = self.run(options, args)

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\cli\req_command.py", line 185, in wrapper

    return func(self, options, args)

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\commands\install.py", line 332, in run

    requirement_set = resolver.resolve(

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 179, in resolve

    discovered_reqs.extend(self._resolve_one(requirement_set, req))

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 362, in _resolve_one

    abstract_dist = self._get_abstract_dist_for(req_to_install)

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\resolution\legacy\resolver.py", line 314, in _get_abstract_dist_for

    abstract_dist = self.preparer.prepare_linked_requirement(req)

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\operations\prepare.py", line 467, in prepare_linked_requirement

    local_file = unpack_url(

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\operations\prepare.py", line 255, in unpack_url

    file = get_http_url(

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\operations\prepare.py", line 129, in get_http_url

    from_path, content_type = _download_http_url(

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\operations\prepare.py", line 281, in _download_http_url

    for chunk in download.chunks:

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\cli\progress_bars.py", line 166, in iter

    for x in it:

  File "C:\Program Files\Python38\lib\site-packages\pip\_internal\network\utils.py", line 15, in response_chunks

    for chunk in response.raw.stream(

  File "C:\Program Files\Python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 564, in stream

    data = self.read(amt=amt, decode_content=decode_content)

  File "C:\Program Files\Python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 529, in read

    raise IncompleteRead(self._fp_bytes_read, self.length_remaining)

  File "C:\Program Files\Python38\lib\contextlib.py", line 131, in __exit__

    self.gen.throw(type, value, traceback)

  File "C:\Program Files\Python38\lib\site-packages\pip\_vendor\urllib3\response.py", line 443, in _error_catcher

    raise ProtocolError("Connection broken: %r" % e, e)

pip._vendor.urllib3.exceptions.ProtocolError: ("Connection broken: ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054, None)", ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054, None))

WARNING: You are using pip version 20.1.1; however, version 20.3.3 is available.

You should consider upgrading via the 'C:\Program Files\Python38\python.exe -m pip install --upgrade pip' command.



老师,这个报错可能是什么原因导致的?

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 1830楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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