使用pygame模块如何自动补全,自动提示

因为最近在使用pygame做一些小的游戏来玩,但是在使用过程中发现不能自动补全,就开始了尝试

开发环境

  1. vsCode
  2. python3.6.5
  3. Win10 64位

过程

1,之前从网上搜索有些说离线安装pygame等方法可以,本人比较懒没有尝试,但是看该解决方法下的其他网友评论好像是不行,好像也有成功,我说一下我的
我是’科学‘了一下,看到有人说是因为pygame的__init__.py方法中有太多的try…execpt…
图片1
于是乎我就开始从这里下手把大部分的try…except…删掉,但是在删掉之前我先测试了哪些模块导入时没有问题的,如何测试稍后会说,剩余的完成代码是这样的

注意备份代码

import sys
import os

# Choose Windows display driver
if os.name == 'nt':

    #pypy does not find the dlls, so we add package folder to PATH.
    pygame_dir = os.path.split(__file__)[0]
    os.environ['PATH'] = os.environ['PATH'] + ';' + pygame_dir
    # Respect existing SDL_VIDEODRIVER setting if it has been set
    if 'SDL_VIDEODRIVER' not in os.environ:

        # If the Windows version is 95/98/ME and DirectX 5 or greater is
        # installed, then use the directx driver rather than the default
        # windib driver.

        # http://docs.python.org/lib/module-sys.html
        # 0 (VER_PLATFORM_WIN32s)          Win32s on Windows 3.1
        # 1 (VER_PLATFORM_WIN32_WINDOWS)   Windows 95/98/ME
        # 2 (VER_PLATFORM_WIN32_NT)        Windows NT/2000/XP
        # 3 (VER_PLATFORM_WIN32_CE)        Windows CE
        if sys.getwindowsversion()[0] == 1:

            import _winreg

            try:

                # Get DirectX version from registry
                key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                      'SOFTWARE\\Microsoft\\DirectX')
                dx_version_string = _winreg.QueryValueEx(key, 'Version')
                key.Close()

                # Set video driver to directx if DirectX 5 or better is
                # installed.
                # To interpret DirectX version numbers, see this page:
                # http://en.wikipedia.org/wiki/DirectX#Releases
                minor_dx_version = int(dx_version_string.split('.')[1])
                if minor_dx_version >= 5:
                    os.environ['SDL_VIDEODRIVER'] = 'directx'

                # Clean up namespace
                del key, dx_version_string, minor_dx_version

            except:
                pass

            # Clean up namespace
            del _winreg

# when running under X11, always set the SDL window WM_CLASS to make the
#   window managers correctly match the pygame window.
elif 'DISPLAY' in os.environ and 'SDL_VIDEO_X11_WMCLASS' not in os.environ:
    os.environ['SDL_VIDEO_X11_WMCLASS'] = os.path.basename(sys.argv[0])


class MissingModule:
    _NOT_IMPLEMENTED_ = True

    def __init__(self, name, urgent=0):
        self.name = name
        exc_type, exc_msg = sys.exc_info()[:2]
        self.info = str(exc_msg)
        self.reason = "%s: %s" % (exc_type.__name__, self.info)
        self.urgent = urgent
        if urgent:
            self.warn()

    def __getattr__(self, var):
        if not self.urgent:
            self.warn()
            self.urgent = 1
        missing_msg = "%s module not available (%s)" % (self.name, self.reason)
        raise NotImplementedError(missing_msg)

    def __nonzero__(self):
        return 0

    def warn(self):
        msg_type = 'import' if self.urgent else 'use'
        message = '%s %s: %s\n(%s)' % (msg_type, self.name, self.info, self.reason)
        try:
            import warnings
            level = 4 if self.urgent else 3
            warnings.warn(message, RuntimeWarning, level)
        except ImportError:
            print (message)


# we need to import like this, each at a time. the cleanest way to import
# our modules is with the import command (not the __import__ function)

# first, the "required" modules
from pygame.base import *
from pygame.constants import *
from pygame.version import *
from pygame.rect import Rect
from pygame.compat import PY_MAJOR_VERSION
from pygame.rwobject import encode_string, encode_file_path
import pygame.surflock
import pygame.color
Color = color.Color
import pygame.bufferproxy
BufferProxy = bufferproxy.BufferProxy
import pygame.math
Vector2 = pygame.math.Vector2
Vector3 = pygame.math.Vector3

__version__ = ver

# next, the "standard" modules
# we still allow them to be missing for stripped down pygame distributions
import pygame.cursors
import pygame.display
import pygame.draw
import pygame.event
import pygame.image
import pygame.key
import pygame.mouse
import pygame.sprite
import pygame.threads
from pygame.surface import *
import pygame.mask
from pygame.mask import Mask    
from pygame.pixelarray import *
from pygame.overlay import *
import pygame.time
import pygame.transform
import pygame.font
import pygame.sysfont
pygame.font.SysFont = pygame.sysfont.SysFont
pygame.font.get_fonts = pygame.sysfont.get_fonts
pygame.font.match_font = pygame.sysfont.match_font
import pygame.mixer
try:
    import pygame.scrap
except (ImportError, IOError):
    print(21)
    scrap = MissingModule("scrap", urgent=0)

try:
    import pygame.surfarray
except (ImportError, IOError):
    print(22)
    surfarray = MissingModule("surfarray", urgent=0)

try:
    import pygame.sndarray
except (ImportError, IOError):
    print(23)
    sndarray = MissingModule("sndarray", urgent=0)

try:
    import pygame.fastevent
except (ImportError, IOError):
    print(24)
    fastevent = MissingModule("fastevent", urgent=0)

#
# make Rects pickleable
if PY_MAJOR_VERSION >= 3:
    import copyreg as copy_reg
else:
    import copy_reg


def __rect_constructor(x, y, w, h):
    return Rect(x, y, w, h)


def __rect_reduce(r):
    assert type(r) == Rect
    return __rect_constructor, (r.x, r.y, r.w, r.h)
copy_reg.pickle(Rect, __rect_reduce, __rect_constructor)


# make Colors pickleable
def __color_constructor(r, g, b, a):
    return Color(r, g, b, a)


def __color_reduce(c):
    assert type(c) == Color
    return __color_constructor, (c.r, c.g, c.b, c.a)
copy_reg.pickle(Color, __color_reduce, __color_constructor)


# Thanks for supporting pygame. Without support now, there won't be pygame later.
if 'PYGAME_HIDE_SUPPORT_PROMPT' not in os.environ:
    print('pygame %s' % ver)
    print('Hello from the pygame community. https://www.pygame.org/contribute.html')


# cleanup namespace
del os, sys, surflock, MissingModule, copy_reg, PY_MAJOR_VERSION

可能也注意到了,就是其中有三个模块的try没有删除,这三个模块主要是我用不到,还有就是这三个模块需要有numpy模块,我这里也没有,所以就留下来了,你可以根据需要决定是否保留或者删除。
这样做了以后,大部分还是可以补全的, display | draw | event | font | image | locals | mixer | mouse | Rect | Surface | time ,其中key模块无法补全。

如何测试哪些模块正常

我把原来的__init__.py文件中都输出数字,错误的就会输出,然后把正常的模块中的try…execpt…删掉,祝大家好运,

import sys
import os

# Choose Windows display driver
if os.name == 'nt':

    #pypy does not find the dlls, so we add package folder to PATH.
    pygame_dir = os.path.split(__file__)[0]
    os.environ['PATH'] = os.environ['PATH'] + ';' + pygame_dir
    # Respect existing SDL_VIDEODRIVER setting if it has been set
    if 'SDL_VIDEODRIVER' not in os.environ:

        # If the Windows version is 95/98/ME and DirectX 5 or greater is
        # installed, then use the directx driver rather than the default
        # windib driver.

        # http://docs.python.org/lib/module-sys.html
        # 0 (VER_PLATFORM_WIN32s)          Win32s on Windows 3.1
        # 1 (VER_PLATFORM_WIN32_WINDOWS)   Windows 95/98/ME
        # 2 (VER_PLATFORM_WIN32_NT)        Windows NT/2000/XP
        # 3 (VER_PLATFORM_WIN32_CE)        Windows CE
        if sys.getwindowsversion()[0] == 1:

            import _winreg

            try:

                # Get DirectX version from registry
                key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
                                      'SOFTWARE\\Microsoft\\DirectX')
                dx_version_string = _winreg.QueryValueEx(key, 'Version')
                key.Close()

                # Set video driver to directx if DirectX 5 or better is
                # installed.
                # To interpret DirectX version numbers, see this page:
                # http://en.wikipedia.org/wiki/DirectX#Releases
                minor_dx_version = int(dx_version_string.split('.')[1])
                if minor_dx_version >= 5:
                    os.environ['SDL_VIDEODRIVER'] = 'directx'

                # Clean up namespace
                del key, dx_version_string, minor_dx_version

            except:
                pass

            # Clean up namespace
            del _winreg

# when running under X11, always set the SDL window WM_CLASS to make the
#   window managers correctly match the pygame window.
elif 'DISPLAY' in os.environ and 'SDL_VIDEO_X11_WMCLASS' not in os.environ:
    os.environ['SDL_VIDEO_X11_WMCLASS'] = os.path.basename(sys.argv[0])


class MissingModule:
    _NOT_IMPLEMENTED_ = True

    def __init__(self, name, urgent=0):
        self.name = name
        exc_type, exc_msg = sys.exc_info()[:2]
        self.info = str(exc_msg)
        self.reason = "%s: %s" % (exc_type.__name__, self.info)
        self.urgent = urgent
        if urgent:
            self.warn()

    def __getattr__(self, var):
        if not self.urgent:
            self.warn()
            self.urgent = 1
        missing_msg = "%s module not available (%s)" % (self.name, self.reason)
        raise NotImplementedError(missing_msg)

    def __nonzero__(self):
        return 0

    def warn(self):
        msg_type = 'import' if self.urgent else 'use'
        message = '%s %s: %s\n(%s)' % (msg_type, self.name, self.info, self.reason)
        try:
            import warnings
            level = 4 if self.urgent else 3
            warnings.warn(message, RuntimeWarning, level)
        except ImportError:
            print (message)


# we need to import like this, each at a time. the cleanest way to import
# our modules is with the import command (not the __import__ function)

# first, the "required" modules
from pygame.base import *
from pygame.constants import *
from pygame.version import *
from pygame.rect import Rect
from pygame.compat import PY_MAJOR_VERSION
from pygame.rwobject import encode_string, encode_file_path
import pygame.surflock
import pygame.color
Color = color.Color
import pygame.bufferproxy
BufferProxy = bufferproxy.BufferProxy
import pygame.math
Vector2 = pygame.math.Vector2
Vector3 = pygame.math.Vector3

__version__ = ver

# next, the "standard" modules
# we still allow them to be missing for stripped down pygame distributions
if get_sdl_version() < (2, 0, 0):
    # cdrom only available for SDL 1.2.X
    try:
        import pygame.cdrom
    except (ImportError, IOError):
        cdrom = MissingModule("cdrom", urgent=1)

try:
    import pygame.cursors
except (ImportError, IOError):
    print(1)
    cursors = MissingModule("cursors", urgent=1)

try:
    import pygame.display
except (ImportError, IOError):
    print(2)
    display = MissingModule("display", urgent=1)

try:
    import pygame.draw
except (ImportError, IOError):
    print(3)
    draw = MissingModule("draw", urgent=1)

try:
    import pygame.event
except (ImportError, IOError):
    print(4)
    event = MissingModule("event", urgent=1)

try:
    import pygame.image
except (ImportError, IOError):
    print(5)
    image = MissingModule("image", urgent=1)

try:
    import pygame.joystick
    
except (ImportError, IOError):
    print(6)
    joystick = MissingModule("joystick", urgent=1)

try:
    import pygame.key
    
except (ImportError, IOError):
    print(7)
    key = MissingModule("key", urgent=1)

try:
    import pygame.mouse
    
except (ImportError, IOError):
    print(8)
    mouse = MissingModule("mouse", urgent=1)

try:
    import pygame.sprite
    
except (ImportError, IOError):
    print(9)
    sprite = MissingModule("sprite", urgent=1)

try:
    import pygame.threads
    
except (ImportError, IOError):
    print(10)
    threads = MissingModule("threads", urgent=1)

try:
    import pygame.pixelcopy
except (ImportError, IOError):
    print(11)
    pixelcopy = MissingModule("pixelcopy", urgent=1)


def warn_unwanted_files():
    """warn about unneeded old files"""

    # a temporary hack to warn about camera.so and camera.pyd.
    install_path = os.path.split(pygame.base.__file__)[0]
    extension_ext = os.path.splitext(pygame.base.__file__)[1]

    # here are the .so/.pyd files we need to ask to remove.
    ext_to_remove = ["camera"]

    # here are the .py/.pyo/.pyc files we need to ask to remove.
    py_to_remove = ["color"]

    # Don't warn on Symbian. The color.py is used as a wrapper.
    if os.name == "e32":
        py_to_remove = []

    # See if any of the files are there.
    extension_files = ["%s%s" % (x, extension_ext) for x in ext_to_remove]

    py_files = ["%s%s" % (x, py_ext)
                for py_ext in [".py", ".pyc", ".pyo"]
                for x in py_to_remove]

    files = py_files + extension_files

    unwanted_files = []
    for f in files:
        unwanted_files.append(os.path.join(install_path, f))

    ask_remove = []
    for f in unwanted_files:
        if os.path.exists(f):
            ask_remove.append(f)

    if ask_remove:
        message = "Detected old file(s).  Please remove the old files:\n"

        for f in ask_remove:
            message += "%s " % f
        message += "\nLeaving them there might break pygame.  Cheers!\n\n"

        try:
            import warnings
            level = 4
            warnings.warn(message, RuntimeWarning, level)
        except ImportError:
            print (message)


# disable, because we hopefully don't need it.
# warn_unwanted_files()


try:
    from pygame.surface import *
except (ImportError, IOError):
    print(12)
    Surface = lambda: Missing_Function


try:
    import pygame.mask
    from pygame.mask import Mask
except (ImportError, IOError):
    print(13)
    Mask = lambda: Missing_Function

try:
    from pygame.pixelarray import *
except (ImportError, IOError):
    print(14)
    PixelArray = lambda: Missing_Function

try:
    from pygame.overlay import *
except (ImportError, IOError):
    print(15)
    Overlay = lambda: Missing_Function

try:
    import pygame.time
except (ImportError, IOError):
    print(16)
    time = MissingModule("time", urgent=1)

try:
    import pygame.transform
except (ImportError, IOError):
    print(17)
    transform = MissingModule("transform", urgent=1)

# lastly, the "optional" pygame modules
if 'PYGAME_FREETYPE' in os.environ:
    try:
        import pygame.ftfont as font
        sys.modules['pygame.font'] = font
    except (ImportError, IOError):
        pass
try:
    import pygame.font
    import pygame.sysfont
    pygame.font.SysFont = pygame.sysfont.SysFont
    pygame.font.get_fonts = pygame.sysfont.get_fonts
    pygame.font.match_font = pygame.sysfont.match_font
except (ImportError, IOError):
    print(18)
    font = MissingModule("font", urgent=0)

# try and load pygame.mixer_music before mixer, for py2app...
try:
    import pygame.mixer_music
    #del pygame.mixer_music
    #print ("NOTE2: failed importing pygame.mixer_music in lib/__init__.py")
except (ImportError, IOError):
    pass

try:
    import pygame.mixer
except (ImportError, IOError):
    print(19)
    mixer = MissingModule("mixer", urgent=0)

# try:
#     import pygame.movie
# except (ImportError, IOError):
#     print(20)
#     movie = MissingModule("movie", urgent=0)

# try:
#     import pygame.movieext
# except (ImportError,IOError):
#     movieext=MissingModule("movieext", urgent=0)

try:
    import pygame.scrap
except (ImportError, IOError):
    print(21)
    scrap = MissingModule("scrap", urgent=0)

try:
    import pygame.surfarray
except (ImportError, IOError):
    print(22)
    surfarray = MissingModule("surfarray", urgent=0)

try:
    import pygame.sndarray
except (ImportError, IOError):
    print(23)
    sndarray = MissingModule("sndarray", urgent=0)

try:
    import pygame.fastevent
except (ImportError, IOError):
    print(24)
    fastevent = MissingModule("fastevent", urgent=0)

# there's also a couple "internal" modules not needed
# by users, but putting them here helps "dependency finder"
# programs get everything they need (like py2exe)
try:
    import pygame.imageext
    del pygame.imageext
except (ImportError, IOError):
    pass


def packager_imports():
    """some additional imports that py2app/py2exe will want to see"""
    import atexit
    import numpy
    import OpenGL.GL
    import pygame.macosx
    import pygame.bufferproxy
    import pygame.colordict
    import pygame._view

# make Rects pickleable
if PY_MAJOR_VERSION >= 3:
    import copyreg as copy_reg
else:
    import copy_reg


def __rect_constructor(x, y, w, h):
    return Rect(x, y, w, h)


def __rect_reduce(r):
    assert type(r) == Rect
    return __rect_constructor, (r.x, r.y, r.w, r.h)
copy_reg.pickle(Rect, __rect_reduce, __rect_constructor)


# make Colors pickleable
def __color_constructor(r, g, b, a):
    return Color(r, g, b, a)


def __color_reduce(c):
    assert type(c) == Color
    return __color_constructor, (c.r, c.g, c.b, c.a)
copy_reg.pickle(Color, __color_reduce, __color_constructor)


# Thanks for supporting pygame. Without support now, there won't be pygame later.
if 'PYGAME_HIDE_SUPPORT_PROMPT' not in os.environ:
    print('pygame %s' % ver)
    print('Hello from the pygame community. https://www.pygame.org/contribute.html')


# cleanup namespace
del os, sys, surflock, MissingModule, copy_reg, PY_MAJOR_VERSION

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值