Exemple #1
0
	def __init__(self,title,text):
		wx.Dialog.__init__(self,None,-1,"About "+title,style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)
		hwin=window_t(self,-1,size=(400,200))

		version_text=""
		version_text+="<p>"
		version_text+="<p>Python Version "+sys.version.split()[0]
		version_text+="<br>"
		version_text+="wxWidgets Version "+wx.VERSION_STRING
		version_text+="<br>"
		version_text+="pySerial Version "+sys.version.split()[0]
		version_text+="<br>"
		version_text+="pyGame SDL Version "
		version_text+=str(pygame.get_sdl_version()[0])
		version_text+="."
		version_text+=str(pygame.get_sdl_version()[1])
		version_text+="."
		version_text+=str(pygame.get_sdl_version()[2])
		version_text+="</p>"

		hwin.SetPage(text+version_text)
		btn=hwin.FindWindowById(wx.ID_OK)
		internal_representation=hwin.GetInternalRepresentation()

		width=hwin.GetInternalRepresentation().GetWidth()+25
		height=hwin.GetInternalRepresentation().GetHeight()+10
		hwin.SetSize((width,height))

		self.SetClientSize(hwin.GetSize())
		self.CentreOnParent(wx.BOTH)
		self.SetFocus()
Exemple #2
0
    def test_get_sdl_version(self):

        # __doc__ (as of 2008-06-25) for pygame.base.get_sdl_version:

          # pygame.get_sdl_version(): return major, minor, patch
          # get the version number of SDL

        self.assert_( len(pygame.get_sdl_version()) == 3) 
Exemple #3
0
def main():
	sdlversion=pygame.get_sdl_version()
	if sdlversion[0]<1 or sdlversion[1]<2 or sdlversion[2]<10:
		print "pygame sdl version is {0}. sdl version should be atleast {1}".format( sdlversion, (1,2,10) )
		sys.exit(1)


	pygame.init()
	pygame.init() #  Need it twice for mixer to get inited properly. Due to a debian bug. 


	try:
	        if pygame.mixer and not pygame.mixer.get_init():
		        print ('Warning, no sound')
		        pygame.mixer = None

	  	pygame.key.set_repeat(10, 100)	
		pygame.font.init()                                                             
		game=Game()	

		running=True
		while running:
		    for event in pygame.event.get():
			if event.type == pygame.QUIT: 
				running=False
				break

			if event.type == pygame.KEYDOWN:
			    if (event.key == pygame.K_ESCAPE):
				running=False
				break
			    elif (event.key == pygame.K_RETURN ):
				game.Update(SpriteCommand.cmd_enter)
			    elif (event.key == pygame.K_LEFT):
				game.Update(SpriteCommand.cmd_turnleft)
			    elif (event.key == pygame.K_RIGHT):
				game.Update(SpriteCommand.cmd_turnright)
			    elif (event.key == pygame.K_UP):
				game.Update(SpriteCommand.cmd_move)
		

	
		    pygame.display.update()
	except Exception as e:
	#	print "Exception : ", sys.exc_info()[0], "line ", lineno()
		exc_type, exc_obj, exc_tb = sys.exc_info()
		"""fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
		print(exc_type, fname, exc_tb.tb_lineno)"""
		traceback.print_exception(exc_type, exc_obj, exc_tb)
		
	
	pygame.quit()
Exemple #4
0
def libinfo():
    v = {}
    try:
        import Pmw
        v['pmw'] = Pmw.version()
    except ImportError:
        v['pmw'] = None

    try:
        import PIL.Image
        v['pil'] = PIL.Image.VERSION
    except ImportError:
        v['pil'] = None

    try:
        import Numeric
        v['numeric'] = Numeric.__version__
    except ImportError:
        v['numeric'] = None

    try:
        import pygame
        v['pygame'] = pygame.ver
        try:
            v['sdl'] = string.join(map(str,pygame.get_sdl_version()), '.')
        except AttributeError:
            v['sdl'] = None
    except ImportError:
        v['pygame'] = None
        v['sdl'] = None

    try:
        import OpenGL
        v['opengl'] = OpenGL.__version__
    except ImportError:
        v['opengl'] = None

    return v
    def test_blit_array(self):

        s = pygame.Surface((10, 10), 0, 24)
        a = pygame.surfarray.array3d(s)
        pygame.surfarray.blit_array(s, a)

        # target surfaces
        targets = [
            self._make_surface(8),
            self._make_surface(16),
            self._make_surface(16, srcalpha=True),
            self._make_surface(24),
            self._make_surface(32),
            self._make_surface(32, srcalpha=True),
        ]

        # source arrays
        arrays3d = []
        dtypes = [(8, uint8), (16, uint16), (32, uint32)]
        try:
            dtypes.append((64, uint64))
        except NameError:
            pass
        arrays3d = [(self._make_src_array3d(dtype), None)
                    for __, dtype in dtypes]
        for bitsize in [8, 16, 24, 32]:
            palette = None
            if bitsize == 16:
                s = pygame.Surface((1, 1), 0, 16)
                palette = [
                    s.unmap_rgb(s.map_rgb(c)) for c in self.test_palette
                ]
            if self.pixels3d[bitsize]:
                surf = self._make_src_surface(bitsize)
                arr = pygame.surfarray.pixels3d(surf)
                arrays3d.append((arr, palette))
            if self.array3d[bitsize]:
                surf = self._make_src_surface(bitsize)
                arr = pygame.surfarray.array3d(surf)
                arrays3d.append((arr, palette))
                for sz, dtype in dtypes:
                    arrays3d.append((arr.astype(dtype), palette))

        # tests on arrays
        def do_blit(surf, arr):
            pygame.surfarray.blit_array(surf, arr)

        for surf in targets:
            bitsize = surf.get_bitsize()
            for arr, palette in arrays3d:
                surf.fill((0, 0, 0, 0))
                if bitsize == 8:
                    self.assertRaises(ValueError, do_blit, surf, arr)
                else:
                    pygame.surfarray.blit_array(surf, arr)
                    self._assert_surface(surf, palette)

            if self.pixels2d[bitsize]:
                surf.fill((0, 0, 0, 0))
                s = self._make_src_surface(bitsize,
                                           surf.get_flags() & SRCALPHA)
                arr = pygame.surfarray.pixels2d(s)
                pygame.surfarray.blit_array(surf, arr)
                self._assert_surface(surf)

            if self.array2d[bitsize]:
                s = self._make_src_surface(bitsize,
                                           surf.get_flags() & SRCALPHA)
                arr = pygame.surfarray.array2d(s)
                for sz, dtype in dtypes:
                    surf.fill((0, 0, 0, 0))
                    if sz >= bitsize:
                        pygame.surfarray.blit_array(surf, arr.astype(dtype))
                        self._assert_surface(surf)
                    else:
                        self.assertRaises(ValueError, do_blit, surf,
                                          self._make_array2d(dtype))

        # Check alpha for 2D arrays
        surf = self._make_surface(16, srcalpha=True)
        arr = zeros(surf.get_size(), uint16)
        arr[...] = surf.map_rgb((0, 128, 255, 64))
        color = surf.unmap_rgb(arr[0, 0])
        pygame.surfarray.blit_array(surf, arr)
        self.assertEqual(surf.get_at((5, 5)), color)

        surf = self._make_surface(32, srcalpha=True)
        arr = zeros(surf.get_size(), uint32)
        color = (0, 111, 255, 63)
        arr[...] = surf.map_rgb(color)
        pygame.surfarray.blit_array(surf, arr)
        self.assertEqual(surf.get_at((5, 5)), color)

        # Check shifts
        arr3d = self._make_src_array3d(uint8)

        shift_tests = [
            (16, [12, 0, 8, 4], [0xF000, 0xF, 0xF00, 0xF0]),
            (24, [16, 0, 8, 0], [0xFF0000, 0xFF, 0xFF00, 0]),
            (32, [0, 16, 24, 8], [0xFF, 0xFF0000, 0xFF000000, 0xFF00]),
        ]

        for bitsize, shifts, masks in shift_tests:
            surf = self._make_surface(bitsize, srcalpha=(shifts[3] != 0))
            palette = None
            if bitsize == 16:
                palette = [
                    surf.unmap_rgb(surf.map_rgb(c)) for c in self.test_palette
                ]

            if pygame.get_sdl_version()[0] == 1:
                surf.set_shifts(shifts)
                surf.set_masks(masks)
                pygame.surfarray.blit_array(surf, arr3d)
                self._assert_surface(surf, palette)
            else:
                self.assertRaises(TypeError, surf.set_shifts, shifts)
                self.assertRaises(TypeError, surf.set_masks, masks)

        # Invalid arrays
        surf = pygame.Surface((1, 1), 0, 32)
        t = "abcd"
        self.assertRaises(ValueError, do_blit, surf, t)

        surf_size = self.surf_size
        surf = pygame.Surface(surf_size, 0, 32)
        arr = zeros([surf_size[0], surf_size[1] + 1, 3], uint32)
        self.assertRaises(ValueError, do_blit, surf, arr)
        arr = zeros([surf_size[0] + 1, surf_size[1], 3], uint32)
        self.assertRaises(ValueError, do_blit, surf, arr)

        surf = pygame.Surface((1, 4), 0, 32)
        arr = zeros((4, ), uint32)
        self.assertRaises(ValueError, do_blit, surf, arr)
        arr.shape = (1, 1, 1, 4)
        self.assertRaises(ValueError, do_blit, surf, arr)

        # Issue #81: round from float to int
        try:
            rint
        except NameError:
            pass
        else:
            surf = pygame.Surface((10, 10), pygame.SRCALPHA, 32)
            w, h = surf.get_size()
            length = w * h
            for dtype in [float32, float64]:
                surf.fill((255, 255, 255, 0))
                farr = arange(0, length, dtype=dtype)
                farr.shape = w, h
                pygame.surfarray.blit_array(surf, farr)
                for x in range(w):
                    for y in range(h):
                        self.assertEqual(surf.get_at_mapped((x, y)),
                                         int(rint(farr[x, y])))
Exemple #6
0
import unittest
import os
import platform
import pygame

SDL1 = pygame.get_sdl_version()[0] < 2
DARWIN = "Darwin" in platform.platform()


class MouseTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # The display needs to be initialized for mouse functions.
        pygame.display.init()

    @classmethod
    def tearDownClass(cls):
        pygame.display.quit()


class MouseModuleInteractiveTest(MouseTests):

    __tags__ = ["interactive"]

    @unittest.skipIf(SDL1 and DARWIN,
                     "Can fails on Mac SDL1, window not focused")
    def test_set_pos(self):
        """ Ensures set_pos works correctly.
            Requires tester to move the mouse to be on the window.
        """
        pygame.display.set_mode((500, 500))
Exemple #7
0
octopg_ver = "0.4.0"
octopg_vernum = (0, 4, 0)


def vernum_to_ver(vernum):
    return ".".join(map(str, vernum))


import pygame
import pygame.version

pg_ver = pygame.version.ver
pg_vernum = pygame.version.vernum

sdl_vernum = pygame.get_sdl_version()
sdl_ver = vernum_to_ver(sdl_vernum)

import urllib.request as url
import json
from operator import itemgetter
"""
check_updates()

Check if an update is available for the OctoPG library

@return (bool|dict) False when there is no update, the release info when the update is available
"""


def check_updates():
Exemple #8
0
        y5 = max(self.y, other.y)
        y6 = min(self.y+self.height, other.y+other.height)
        if x5 >= x6 or y5 >= y6:
            return Rect(0, 0, 0, 0)
        return Rect(x5, y5, x6-x5, y6-y5)

    def toPygame(self):
        return self.__pyg_rect


pygame.mixer.pre_init(22050, -16, 2, 512)
pygame.init()
pygame.font.init()

print('PyGame Version', pygame.version.ver)
print('SDL Version', pygame.get_sdl_version())

screenWidth = 800
screenHeight = 800

white = (255, 255, 255)
black = (0, 0, 0)
blue = (0, 0, 255)
red = (255, 7, 58)
green = (50, 255, 50)
teal = (0, 255, 255)

pygame.display.set_caption('Breakout!')

surface = pygame.display.set_mode((screenWidth, screenHeight))
Exemple #9
0
def run(*args, **kwds):
    """Run the Pygame unit test suite and return (total tests run, fails dict)

    Positional arguments (optional):
    The names of tests to include. If omitted then all tests are run. Test
    names need not include the trailing '_test'.

    Keyword arguments:
    incomplete - fail incomplete tests (default False)
    usesubprocess - run all test suites in the current process
                   (default False, use separate subprocesses)
    dump - dump failures/errors as dict ready to eval (default False)
    file - if provided, the name of a file into which to dump failures/errors
    timings - if provided, the number of times to run each individual test to
              get an average run time (default is run each test once)
    exclude - A list of TAG names to exclude from the run. The items may be
              comma or space separated.
    show_output - show silenced stderr/stdout on errors (default False)
    all - dump all results, not just errors (default False)
    randomize - randomize order of tests (default False)
    seed - if provided, a seed randomizer integer
    multi_thread - if provided, the number of THREADS in which to run
                   subprocessed tests
    time_out - if subprocess is True then the time limit in seconds before
               killing a test (default 30)
    fake - if provided, the name of the fake tests package in the
           run_tests__tests subpackage to run instead of the normal
           Pygame tests
    python - the path to a python executable to run subprocessed tests
             (default sys.executable)
    interative - allow tests tagged 'interative'.

    Return value:
    A tuple of total number of tests run, dictionary of error information. The
    dictionary is empty if no errors were recorded.

    By default individual test modules are run in separate subprocesses. This
    recreates normal Pygame usage where pygame.init() and pygame.quit() are
    called only once per program execution, and avoids unfortunate
    interactions between test modules. Also, a time limit is placed on test
    execution, so frozen tests are killed when there time allotment expired.
    Use the single process option if threading is not working properly or if
    tests are taking too long. It is not guaranteed that all tests will pass
    in single process mode.

    Tests are run in a randomized order if the randomize argument is True or a
    seed argument is provided. If no seed integer is provided then the system
    time is used.

    Individual test modules may have a corresponding *_tags.py module,
    defining a __tags__ attribute, a list of tag strings used to selectively
    omit modules from a run. By default only the 'interactive', 'ignore', and
    'subprocess_ignore' tags are ignored. 'interactive' is for modules that
    take user input, like cdrom_test.py. 'ignore' and 'subprocess_ignore' for
    for disabling modules for foreground and subprocess modes respectively.
    These are for disabling tests on optional modules or for experimental
    modules with known problems. These modules can be run from the console as
    a Python program.

    This function can only be called once per Python session. It is not
    reentrant.

    """

    global was_run

    if was_run:
        raise RuntimeError("run() was already called this session")
    was_run = True

    options = kwds.copy()
    option_usesubprocess = options.get('usesubprocess', False)
    option_dump = options.pop('dump', False)
    option_file = options.pop('file', None)
    option_randomize = options.get('randomize', False)
    option_seed = options.get('seed', None)
    option_multi_thread = options.pop('multi_thread', 1)
    option_time_out = options.pop('time_out', 120)
    option_fake = options.pop('fake', None)
    option_python = options.pop('python', sys.executable)
    option_exclude = options.pop('exclude', ())
    option_interactive = options.pop('interactive', False)

    if not option_interactive and 'interactive' not in option_exclude:
        option_exclude += ('interactive',)
    if option_usesubprocess and 'subprocess_ignore' not in option_exclude:
        option_exclude += ('subprocess_ignore',)
    elif 'ignore' not in option_exclude:
        option_exclude += ('ignore',)
    if sys.version_info < (3, 0, 0):
        option_exclude += ('python2_ignore',)
    else:
        option_exclude += ('python3_ignore',)

    if pygame.get_sdl_version() < (2, 0, 0):
        option_exclude += ('SDL1_ignore',)
    else:
        option_exclude += ('SDL2_ignore',)
    main_dir, test_subdir, fake_test_subdir = prepare_test_env()

    ###########################################################################
    # Compile a list of test modules. If fake, then compile list of fake
    # xxxx_test.py from run_tests__tests

    TEST_MODULE_RE = re.compile('^(.+_test)\.py$')

    test_mods_pkg_name = test_pkg_name

    working_dir_temp = tempfile.mkdtemp()

    if option_fake is not None:
        test_mods_pkg_name = '.'.join([test_mods_pkg_name,
                                       'run_tests__tests',
                                       option_fake])
        test_subdir = os.path.join(fake_test_subdir, option_fake)
        working_dir = test_subdir
    else:
        working_dir = working_dir_temp


    # Added in because some machines will need os.environ else there will be
    # false failures in subprocess mode. Same issue as python2.6. Needs some
    # env vars.

    test_env = os.environ

    fmt1 = '%s.%%s' % test_mods_pkg_name
    fmt2 = '%s.%%s_test' % test_mods_pkg_name
    if args:
        test_modules = [
            m.endswith('_test') and (fmt1 % m) or (fmt2 % m) for m in args
        ]
    else:
        test_modules = []
        for f in sorted(os.listdir(test_subdir)):
            for match in TEST_MODULE_RE.findall(f):
                test_modules.append(fmt1 % (match,))

    ###########################################################################
    # Remove modules to be excluded.

    tmp = test_modules
    test_modules = []
    for name in tmp:
        tag_module_name = "%s_tags" % (name[0:-5],)
        try:
            tag_module = import_submodule(tag_module_name)
        except ImportError:
            test_modules.append(name)
        else:
            try:
                tags = tag_module.__tags__
            except AttributeError:
                print ("%s has no tags: ignoring" % (tag_module_name,))
                test_modules.append(name)
            else:
                for tag in tags:
                    if tag in option_exclude:
                        print ("skipping %s (tag '%s')" % (name, tag))
                        break
                else:
                    test_modules.append(name)
    del tmp, tag_module_name, name

    ###########################################################################
    # Meta results

    results = {}
    meta_results = {'__meta__' : {}}
    meta = meta_results['__meta__']

    ###########################################################################
    # Randomization

    if option_randomize or option_seed is not None:
        if option_seed is None:
            option_seed = time.time()
        meta['random_seed'] = option_seed
        print ("\nRANDOM SEED USED: %s\n" % option_seed)
        random.seed(option_seed)
        random.shuffle(test_modules)

    ###########################################################################
    # Single process mode

    if not option_usesubprocess:
        options['exclude'] = option_exclude
        t = time.time()
        for module in test_modules:
            results.update(run_test(module, **options))
        t = time.time() - t

    ###########################################################################
    # Subprocess mode
    #

    else:
        if is_pygame_pkg:
            from pygame.tests.test_utils.async_sub import proc_in_time_or_kill
        else:
            from test.test_utils.async_sub import proc_in_time_or_kill

        pass_on_args = ['--exclude', ','.join(option_exclude)]
        for field in ['randomize', 'incomplete', 'unbuffered']:
            if kwds.get(field, False):
                pass_on_args.append('--'+field)

        def sub_test(module):
            print ('loading %s' % module)

            cmd = [option_python, '-m', test_runner_mod,
                   module] + pass_on_args

            return (module,
                    (cmd, test_env, working_dir),
                    proc_in_time_or_kill(cmd, option_time_out, env=test_env,
                                         wd=working_dir))

        if option_multi_thread > 1:
            def tmap(f, args):
                return pygame.threads.tmap (
                    f, args, stop_on_error = False,
                    num_workers = option_multi_thread
                )
        else:
            tmap = map

        t = time.time()

        for module, cmd, (return_code, raw_return) in tmap(sub_test,
                                                           test_modules):
            test_file = '%s.py' % os.path.join(test_subdir, module)
            cmd, test_env, working_dir = cmd

            test_results = get_test_results(raw_return)
            if test_results:
                results.update(test_results)
            else:
                results[module] = {}

            results[module].update(dict(
                return_code=return_code,
                raw_return=raw_return,
                cmd=cmd,
                test_file=test_file,
                test_env=test_env,
                working_dir=working_dir,
                module=module,
            ))

        t = time.time() - t

    ###########################################################################
    # Output Results
    #

    untrusty_total, combined = combine_results(results, t)
    total, n_errors, n_failures = count_results(results)

    meta['total_tests'] = total
    meta['combined'] = combined
    meta['total_errors'] = n_errors
    meta['total_failures'] = n_failures
    results.update(meta_results)

    if not option_usesubprocess and total != untrusty_total:
        raise AssertionError('Something went wrong in the Test Machinery:\n'
                             'total: %d != untrusty_total: %d' % (total, untrusty_total))

    if not option_dump:
        print (combined)
    else:
        print (TEST_RESULTS_START)
        print (pformat(results))

    if option_file is not None:
        results_file = open(option_file, 'w')
        try:
            results_file.write(pformat(results))
        finally:
            results_file.close()

    shutil.rmtree(working_dir_temp)

    return total, n_errors + n_failures
Exemple #10
0
#!/usr/bin/env python
""" pg.examples.video

Experimental!

* dialog message boxes with messagebox.
* multiple windows with Window
* driver selection
* Renderer, Texture, and Image classes
* Drawing lines, rects, and such onto Renderers.
"""
import os
import pygame as pg

if pg.get_sdl_version()[0] < 2:
    raise SystemExit(
        "This example requires pygame 2 and SDL2. _sdl2 is experimental and will change."
    )
from pygame._sdl2 import Window, Texture, Image, Renderer, get_drivers, messagebox

data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "data")


def load_img(file):
    return pg.image.load(os.path.join(data_dir, file))


pg.display.init()
pg.key.set_repeat(1000, 10)

for driver in get_drivers():
# needed for version numbers
import pygame, sys
import sqlalchemy as sqla
import Version
version=Version.version

### don't make changes below this line ################
spversion = "Childsplay version: %s" % version
plat = "Platform :%s" % sys.platform
pyversion = "Python version: %s" % sys.version.split('\n')[0]
pgversion = "Pygame version: %s" % pygame.version.ver
sdlversion = "SDL version: %s.%s.%s" % pygame.get_sdl_version()
sqlaversion = "Sqlalchemy version: %s" % sqla.__version__
# Needed for the option parser
optversion = '\n'.join(['-'*60,spversion,plat, pyversion, pgversion,\
                        sdlversion,sqlaversion,'-'*60])
Exemple #12
0
def main(winstyle=0):
    pass

    if pygame.get_sdl_version()[0] == 2:
        pygame,mixwe.pre_init(44100, 32, 2, 1024)

    pygame.init()

    winstyle = 0 # |FULLSCREEN
    bestdepth = pygame.desplay.mode_ok(SCREENRECT.size, winstyle, bestdepth)
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)

    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    set_game_obj_images()

    pygame.mouse.set_visible(0)

    background_tile_image = utility.load_image("background.gif")

    background = pygame.Surface(SCREENRECT.size)

    for x_position in range(0, SCREENRECT.width,
                            background_tile_image.get_width()):
        background.blit(background_tile_image, (x_position, 0))

    screen.blit(background, (0, 0))

    pygame.display.flip()

    set_game_sound()

    aliens = pygame.sprite.Group()
    shots = pygame.sprite.Group()
    bombs = pygame.sprite.Group()

    all_game_rects = pygame.sprite.RenderUpdates()
    last_alien = pygame.sprite.GroupSingle()

    Player.containers = all_game_rects

    Alien.containers = aliens, all_game_rects, last_alien
    Shot.containers = shots, all_game_rects
    Bomb.containers = bombs, all_game_rects
    Explosion.containers = all_game_rects
    Score.containers = all_game_rects
    PlayerLives.containers = all_game_rects

    Alien(SCREENRECT)  
    if (pygame.font is not None):
        
        all_game_rects.add(Score())
        all_game_rects.add(PlayerLives())

    game_loop(all_game_rects, screen, background, shots,
              last_alien, aliens, bombs, winstyle, bestdepth, FULLSCREEN)

    if (pygame.mixer is not None):
        
        pygame.mixer.music.fadeout(1000)

    pygame.time.wait(1000)

    pygame.quit()
Exemple #13
0
#  This file is a part of the Heat2D Project and  #
#  distributed under the GPL 3 license            #
#                                                 #
#           HEAT2D Game Engine Project            #
#            Copyright © Kadir Aksoy              #
#       https://github.com/kadir014/heat2d        #

import pygame
import moderngl

HEAT2D_VERSION = "0.0.5"
HEAT2D_VERSION_TUPLE = (0, 0, 5)
HEAT2D_VERSION_STATE = "alpha"
HEAT2D_LICENSE = "GNU General Public License v3.0"

PYGAME_VERSION = pygame.version.ver
PYGAME_VERSION_TUPLE = pygame.version.vernum
SDL_VERSION = pygame.get_sdl_version()

MODERNGL_VERSION = moderngl.__version__
ctx = moderngl.create_standalone_context(size=(1, 1), require=None)
OPENGL_VERSION = ctx.version_code
ctx.release()

del pygame, moderngl, ctx
Exemple #14
0
	UP/DOWN=Next/Previous Song
	ESC/Q=Quit
	F=Fullscreen/Window'
			''')
	print " "
	print "dacapo Version: %s" %(fver(oConfig.getConfig('version', ' ', ' ')))
	print " "
	print "Python Version: %s" %(fver(version_info))
	print " "
	print "GTK+: %s.%s.%s" %(Gtk.MAJOR_VERSION, Gtk.MINOR_VERSION, Gtk.MICRO_VERSION)
	print " "
	print "GStreamer: %s / PyGSt: %s" % (
            fver(gst.version()), fver(gst.pygst_version))
	print " "
	print "pyGame Version: %s / SDL: %s" % (
            pygame.version.ver, fver(pygame.get_sdl_version()))
	print " "
	return

def fver(tup):
    return ".".join(map(str, tup))


# -------------------- showPicsHelp() -----------------------------------------------------------------

def showPicsHelp():
	'''		<!-- showPics: Bilder anzeigen? Mögliche Werte: 
				NO = Keine Bilder anzeigen, nur metadata
				coverOnly = Nur Frontcover anzeigen
				allCover = alle Cover-Bilder anzeigen (Typ 3-6 / Front, Back, Leaflet, Label)
				allPics = alle Bilder
def main(winstyle=0):
    # Initialize pygame
    if pygame.get_sdl_version()[0] == 2:
        pygame.mixer.pre_init(44100, 32, 2, 1024)
    pygame.init()
    if pygame.mixer and not pygame.mixer.get_init():
        print('Warning, no sound')
        pygame.mixer = None

    fullscreen = False
    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    #Load images, assign to sprite classes
    #(do this before the classes are used, after screen setup)
    img = load_image('player1.gif')
    Player.images = [img, pygame.transform.flip(img, 1, 0)]
    img = load_image('explosion1.gif')
    Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
    Alien.images = load_images('alien1.gif', 'alien2.gif', 'alien3.gif')
    Bomb.images = [load_image('bomb.gif')]
    Shot.images = [load_image('shot.gif')]

    #decorate the game window
    icon = pygame.transform.scale(Alien.images[0], (32, 32))
    pygame.display.set_icon(icon)
    pygame.display.set_caption('Pygame Aliens')
    pygame.mouse.set_visible(0)

    #create the background, tile the bgd image
    bgdtile = load_image('background.gif')
    background = pygame.Surface(SCREENRECT.size)
    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
        background.blit(bgdtile, (x, 0))
    screen.blit(background, (0, 0))
    pygame.display.flip()

    #load the sound effects
    boom_sound = load_sound('boom.wav')
    shoot_sound = load_sound('car_door.wav')
    if pygame.mixer:
        music = os.path.join(main_dir, 'data', 'house_lo.ogg')
        pygame.mixer.music.load(music)
        pygame.mixer.music.play(-1)

    # Initialize Game Groups
    aliens = pygame.sprite.Group()
    shots = pygame.sprite.Group()
    bombs = pygame.sprite.Group()
    all = pygame.sprite.RenderUpdates()
    lastalien = pygame.sprite.GroupSingle()

    #assign default groups to each sprite class
    Player.containers = all
    Alien.containers = aliens, all, lastalien
    Shot.containers = shots, all
    Bomb.containers = bombs, all
    Explosion.containers = all
    Score.containers = all

    #Create Some Starting Values
    global score
    alienreload = ALIEN_RELOAD
    kills = 0
    clock = pygame.time.Clock()

    #initialize our starting sprites
    global SCORE
    player = Player()
    Alien()  #note, this 'lives' because it goes into a sprite group
    if pygame.font:
        all.add(Score())

    while player.alive():

        #get input
        for event in pygame.event.get():
            if event.type == QUIT or \
                (event.type == KEYDOWN and event.key == K_ESCAPE):
                return
            elif event.type == KEYDOWN:
                if event.key == pygame.K_f:
                    if not fullscreen:
                        print("Changing to FULLSCREEN")
                        screen_backup = screen.copy()
                        screen = pygame.display.set_mode(
                            SCREENRECT.size, winstyle | FULLSCREEN, bestdepth)
                        screen.blit(screen_backup, (0, 0))
                    else:
                        print("Changing to windowed mode")
                        screen_backup = screen.copy()
                        screen = pygame.display.set_mode(
                            SCREENRECT.size, winstyle, bestdepth)
                        screen.blit(screen_backup, (0, 0))
                    # screen.fill((255, 0, 0))
                    pygame.display.flip()
                    fullscreen = not fullscreen

        keystate = pygame.key.get_pressed()

        # clear/erase the last drawn sprites
        all.clear(screen, background)

        #update all the sprites
        all.update()

        #handle player input
        direction = keystate[K_RIGHT] - keystate[K_LEFT]
        player.move(direction)
        firing = keystate[K_SPACE]
        if not player.reloading and firing and len(shots) < MAX_SHOTS:
            Shot(player.gunpos())
            shoot_sound.play()
        player.reloading = firing

        # Create new alien
        if alienreload:
            alienreload = alienreload - 1
        elif not int(random.random() * ALIEN_ODDS):
            Alien()
            alienreload = ALIEN_RELOAD

        # Drop bombs
        if lastalien and not int(random.random() * BOMB_ODDS):
            Bomb(lastalien.sprite)

        # Detect collisions
        for alien in pygame.sprite.spritecollide(player, aliens, 1):
            boom_sound.play()
            Explosion(alien)
            Explosion(player)
            SCORE = SCORE + 1
            player.kill()

        for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
            boom_sound.play()
            Explosion(alien)
            SCORE = SCORE + 1

        for bomb in pygame.sprite.spritecollide(player, bombs, 1):
            boom_sound.play()
            Explosion(player)
            Explosion(bomb)
            player.kill()

        #draw the scene
        dirty = all.draw(screen)
        pygame.display.update(dirty)

        #cap the framerate
        clock.tick(40)

    if pygame.mixer:
        pygame.mixer.music.fadeout(1000)
    pygame.time.wait(1000)
    pygame.quit()
Exemple #16
0
import unittest
import platform

from pygame.tests.test_utils import example_path, AssertRaisesRegexMixin

import pygame
from pygame import mixer
from pygame.compat import unicode_, as_bytes, bytes_

IS_PYPY = 'PyPy' == platform.python_implementation()

################################### CONSTANTS ##################################

FREQUENCIES = [11025, 22050, 44100, 48000]
SIZES = [-16, -8, 8, 16]
if pygame.get_sdl_version()[0] >= 2:
    SIZES.append(32)

CHANNELS = [1, 2]
BUFFERS = [3024]

CONFIGS = [{
    'frequency': f,
    'size': s,
    'channels': c
} for f in FREQUENCIES for s in SIZES for c in CHANNELS]
# Using all CONFIGS fails on a Mac; probably older SDL_mixer; we could do:
# if platform.system() == 'Darwin':
# But using all CONFIGS is very slow (> 10 sec for example)
# And probably, we don't need to be so exhaustive, hence:
Exemple #17
0
        print "OK"
    else:
        print
        print 'Thank you for giving', __app__, 'a try.'
        print
        print 'This program uses:'
        vernum, release = display_map('info')
        print release
        print 'Pygame 1.9.1release-svn2575'
        print 'SDL 1.2.13'
        print Fore.RED + Style.BRIGHT
        if vernum != '1.0':
            print 'WARNING! Different version of mapper installed:', vernum
            log.warning('WARNING! Different version of mapper installed: ' +
                        vernum)
        if pygame.version.vernum != (1, 9, 1):
            print 'WARNING! Different version of Pygame installed:', pygame.version.ver
        if pygame.get_sdl_version() != (1, 2, 13):
            print 'WARNING! Different version of SDL installed:', pygame.get_sdl_version(
            )
        if not pygame.image.get_extended():
            print 'No extended image file format support for Pygame.' + Fore.RESET + Back.RESET + Style.RESET_ALL
        else:
            print Fore.RESET + Back.RESET + Style.RESET_ALL + 'Extended image file format supported for Pygame.'
        print
        print '----------------------------'
        print __author__
        print

        main(voice_muted, grid_style, zone_style, trade_code, see_thru,
             show_loc, show_grid)
Exemple #18
0
OpenClipart-Vectors (https://pixabay.com/en/users/OpenClipart-Vectors-30363/)
"""

import os

try:
    import pygame_sdl2

    pygame_sdl2.import_as_pygame()
    import pygame

    print "pygame_SDL2 a été trouvé et sera utilisé à la place de pygame -> SDL %d.%d.%d" % pygame_sdl2.get_sdl_version()
except ImportError:
    import pygame

    print "pygame_SDL2 n'a pas été trouvé -> SDL %d.%d.%d" % pygame.get_sdl_version()

from WindowHelper import WindowHelper
from BuzzerMgr import BuzzerMgr
from GamesMgr import GamesMgr


if __name__ == '__main__':

    try:
        print "Bienvenue dans WiiQuizz !"
        print "Répertoire d'exécution :", os.getcwd()
        print

        # Connexion de la manette Master et enregistrement des buzzers à WindowHelper
        buzzerMgr = BuzzerMgr.Instance()
Exemple #19
0
from singularity.code.graphics import g, constants, widget, text, button, listbox

KEYPAD = {
    pygame.K_KP1: 1,
    pygame.K_KP2: 2,
    pygame.K_KP3: 3,
    pygame.K_KP4: 4,
    pygame.K_KP5: 5,
    pygame.K_KP6: 6,
    pygame.K_KP7: 7,
    pygame.K_KP8: 8,
    pygame.K_KP9: 9
}

SDL_V2 = True if pygame.get_sdl_version()[0] == 2 else False


def insort_right_w_key(a, x, lo=0, hi=None, key=lambda v: v):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the right of the rightmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.

    (Basically bisect.insort_right but with support for a key function)
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
Exemple #20
0
    def draw(self):
        # Initialize Title text
        self.settingsText = Text((0,0), "Settings", 50)
        self.settingsText.rect.topleft = ((globs.resolution[0]/2)-(self.settingsText.image.get_width()/2), (globs.resolution[1]/2)-200)

        # Backbutton
        self.backButton = BackButton(self, "menu.main", (25, (globs.resolution[1])-50-25), (100, 50))
        self.buttons.add(self.backButton)

        # Create resolution buttons and container
        resolutions = [(960,540),(1280,720),(1600,900),(1920,1080),(3200,1024)]
        # Container
        self.resolutionContainer = ButtonContainer(self, ((globs.resolution[0]/2)-200-50, (globs.resolution[1]/2)-100), (200,(len(resolutions)*65)+50), text="Display", buttonSpacing=20)
        self.resolutionButtons = []
        # create each button

        for i, r in enumerate(resolutions):
            def resButton_clicked(self):
                globs.resolution = resolutions[self.resolution]
                globs.redraw = True
                globs.initialize_screen()
                globs.config.set("video", "resolution", self.text)
                globs.write_config()
            resButton = self.resolutionContainer.newButton("{}x{}".format(r[0], r[1]), resButton_clicked)
            resButton.resolution = i

        self.versionContainer = Container(self, ((globs.resolution[0]/2)+50, (globs.resolution[1]/2)-100), (300,250), text="Versions")
        self.pythonVersionText = Text((self.versionContainer.rect.topleft[0]+20,self.versionContainer.rect.topleft[1]+50), "Python version: {0[0]}.{0[1]}.{0[2]}".format(sys.version_info), 20)
        self.pygameVersionText = Text((self.versionContainer.rect.topleft[0]+20,self.versionContainer.rect.topleft[1]+80), "PyGame version: {}".format(pygame.version.ver), 20)
        self.sdlVersionText = Text((self.versionContainer.rect.topleft[0]+20,self.versionContainer.rect.topleft[1]+110), "SDL version: {0[0]}.{0[1]}.{0[2]}".format(pygame.get_sdl_version()), 20)
        self.videoDriverText = Text((self.versionContainer.rect.topleft[0]+20,self.versionContainer.rect.topleft[1]+140), "Video driver: {0}".format(pygame.display.get_driver()), 20)
        self.displayInfoText = Text((self.versionContainer.rect.topleft[0]+20,self.versionContainer.rect.topleft[1]+170), "Hardware acceleration: {0}".format(bool(pygame.display.Info().hw)), 20)

        # Fullscreen button
        self.fullscreenButton = ToggleButton(self, (self.versionContainer.rect.topleft[0], self.versionContainer.rect.topleft[1]+self.versionContainer.image.get_height()+20), (230, 50), text="Fullscreen")

        def fullscreenButton_clicked(self):
            globs.fullscreen = not globs.fullscreen
            globs.initialize_screen()
            globs.redraw = True
            globs.config.set("video", "fullscreen", globs.fullscreen)
            globs.write_config()
        self.fullscreenButton.onClick(fullscreenButton_clicked)

        self.buttons.add(self.fullscreenButton)


        # Draw title
        self.settingsText.draw()
def main(winstyle=0):
    from gdpr_consents import gdpr_concents
    player_name, consent = gdpr_concents()
    Telemetry(player_name, consent)

    
    # Initialize pygame
    if pg.get_sdl_version()[0] == 2:
        pg.mixer.pre_init(44100, 32, 2, 1024)
    pg.init()
    if pg.mixer and not pg.mixer.get_init():
        print("Warning, no sound")
        pg.mixer = None
    pg.mixer = None

    fullscreen = False
    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pg.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pg.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    # Load images, assign to sprite classes
    # (do this before the classes are used, after screen setup)
    img = load_image("player1.gif")
    Player.images = [img, pg.transform.flip(img, 1, 0)]
    img = load_image("explosion1.gif")
    Explosion.images = [img, pg.transform.flip(img, 1, 1)]
    Alien.images = [load_image(im) for im in ("alien1.gif", "alien2.gif", "alien3.gif")]
    Bomb.images = [load_image("bomb.gif")]
    Shot.images = [load_image("shot.gif")]

    # decorate the game window
    icon = pg.transform.scale(Alien.images[0], (32, 32))
    pg.display.set_icon(icon)
    pg.display.set_caption("Pygame Aliens")
    pg.mouse.set_visible(0)

    # create the background, tile the bgd image
    bgdtile = load_image("background.gif")
    background = pg.Surface(SCREENRECT.size)
    for x in range(0, SCREENRECT.width, bgdtile.get_width()):
        background.blit(bgdtile, (x, 0))
    screen.blit(background, (0, 0))
    pg.display.flip()

    # load the sound effects
    boom_sound = load_sound("boom.wav")
    shoot_sound = load_sound("car_door.wav")
    if pg.mixer:
        music = os.path.join(main_dir, "data", "house_lo.wav")
        pg.mixer.music.load(music)
        pg.mixer.music.play(-1)

    # Initialize Game Groups
    aliens = pg.sprite.Group()
    shots = pg.sprite.Group()
    bombs = pg.sprite.Group()
    all = pg.sprite.RenderUpdates()
    lastalien = pg.sprite.GroupSingle()

    # assign default groups to each sprite class
    Player.containers = all
    Alien.containers = aliens, all, lastalien
    Shot.containers = shots, all
    Bomb.containers = bombs, all
    Explosion.containers = all
    Score.containers = all

    # Create Some Starting Values
    global score
    alienreload = ALIEN_RELOAD
    clock = pg.time.Clock()

    # initialize our starting sprites
    global SCORE
    player = Player(player_name)
    Alien()  # note, this 'lives' because it goes into a sprite group
    if pg.font:
        all.add(Score())

    # Run our main loop whilst the player is alive.
    while player.alive():

        # get input
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return
            if event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE:
                return
            elif event.type == pg.KEYDOWN:
                if event.key == pg.K_f:
                    if not fullscreen:
                        print("Changing to FULLSCREEN")
                        screen_backup = screen.copy()
                        screen = pg.display.set_mode(
                            SCREENRECT.size, winstyle | pg.FULLSCREEN, bestdepth
                        )
                        screen.blit(screen_backup, (0, 0))
                    else:
                        print("Changing to windowed mode")
                        screen_backup = screen.copy()
                        screen = pg.display.set_mode(
                            SCREENRECT.size, winstyle, bestdepth
                        )
                        screen.blit(screen_backup, (0, 0))
                    pg.display.flip()
                    fullscreen = not fullscreen
       
        keystate = pg.key.get_pressed()

        # clear/erase the last drawn sprites
        all.clear(screen, background)

        # update all the sprites
        all.update()

        # handle player input
        direction = keystate[pg.K_RIGHT] - keystate[pg.K_LEFT]
        player.move(direction)
        firing = keystate[pg.K_SPACE]
        if not player.reloading and firing and len(shots) < MAX_SHOTS:
            Shot(player.gunpos())
            if pg.mixer:
                shoot_sound.play()
        player.reloading = firing

        # Create new alien
        if alienreload:
            alienreload = alienreload - 1
        elif not int(random.random() * ALIEN_ODDS):
            Alien()
            alienreload = ALIEN_RELOAD

        # Drop bombs
        if lastalien and not int(random.random() * BOMB_ODDS):
            Bomb(lastalien.sprite)

        # Detect collisions between aliens and players.
        for alien in pg.sprite.spritecollide(player, aliens, 1):
            if pg.mixer:
                boom_sound.play()
            Explosion(alien)
            Explosion(player)
            SCORE = SCORE + 1
            player.kill()

        # See if shots hit the aliens.
        for alien in pg.sprite.groupcollide(shots, aliens, 1, 1).keys():
            if pg.mixer:
                boom_sound.play()
            Explosion(alien)
            SCORE = SCORE + 1

        # See if alien boms hit the player.
        for bomb in pg.sprite.spritecollide(player, bombs, 1):
            if pg.mixer:
                boom_sound.play()
            Explosion(player)
            Explosion(bomb)
            player.kill()

        fps = pg.font.Font(None, 30).render(str(int(clock.get_fps())), True, pg.Color('white'))
        screen.blit(fps, (50, 50))

        # draw the scene
        dirty = all.draw(screen)
        pg.display.update(dirty)

        # cap the framerate at 40fps. Also called 40HZ or 40 times per second.
        clock.tick(40)
    if pg.mixer:
        pg.mixer.music.fadeout(1000)
    pg.time.wait(1000)
    pg.quit()
Exemple #22
0
 def test_get_sdl_version(self):
     """Ensure the SDL version is valid"""
     self.assertEqual(len(pygame.get_sdl_version()), 3)
Exemple #23
0
    ("FingerUp", pygame.FINGERUP),
    ("MultiGesture", pygame.MULTIGESTURE),
    ("MouseWheel", pygame.MOUSEWHEEL),
    ("TextInput", pygame.TEXTINPUT),
    ("TextEditing", pygame.TEXTEDITING),
    ("ControllerAxisMotion", pygame.CONTROLLERAXISMOTION),
    ("ControllerButtonDown", pygame.CONTROLLERBUTTONDOWN),
    ("ControllerButtonUp", pygame.CONTROLLERBUTTONUP),
    ("ControllerDeviceAdded", pygame.CONTROLLERDEVICEADDED),
    ("ControllerDeviceRemoved", pygame.CONTROLLERDEVICEREMOVED),
    ("ControllerDeviceMapped", pygame.CONTROLLERDEVICEREMAPPED),
    ("DropFile", pygame.DROPFILE),
)

# Add in any SDL 2.0.4 specific events.
if pygame.get_sdl_version() >= (2, 0, 4):
    NAMES_AND_EVENTS += (
        ("AudioDeviceAdded", pygame.AUDIODEVICEADDED),
        ("AudioDeviceRemoved", pygame.AUDIODEVICEREMOVED),
    )

# Add in any SDL 2.0.5 specific events.
if pygame.get_sdl_version() >= (2, 0, 5):
    NAMES_AND_EVENTS += (
        ("DropText", pygame.DROPTEXT),
        ("DropBegin", pygame.DROPBEGIN),
        ("DropComplete", pygame.DROPCOMPLETE),
    )


class EventTypeTest(unittest.TestCase):
Exemple #24
0
def main(winstyle=0):
    # Initialize pygame
    if pygame.get_sdl_version()[0] == 2:
        pygame.mixer.pre_init(44100, 32, 2, 1024)
    pygame.init()
    if pygame.mixer and not pygame.mixer.get_init():
        print('Warning, no sound')
        logfile.write('\nWARNING : no sound')
        pygame.mixer = None

    clock = pygame.time.Clock()

    # Set the display mode
    winstyle = 0
    bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32)
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth)

    #load images

    #Customize the window
    pygame.display.set_caption('Clever mirror display')
    pygame.mouse.set_visible(0)

    #create the background, tile the bgd image
    background = pygame.Surface(SCREENRECT.size)
    background.fill([0, 0, 0])  #Black

    #for x in range(0, SCREENRECT.width, bgdtile.get_width()):
    #    background.blit(bgdtile, (x, 0))

    screen.blit(background, (0, 0))
    pygame.display.flip()

    #Initialize groups
    answer = pygame.sprite.Group()
    weather = pygame.sprite.Group()
    speech_recognition_ouput = pygame.sprite.Group()
    all = pygame.sprite.RenderUpdates()

    #Assign default groups to sprite classes
    TextSurface.containers = all

    debug_surface = TextSurface('debug display')
    debug_surface.changeText('Test text')
    all.add(debug_surface)

    speech_recog_surface = TextSurface('debug display',
                                       area_x=WIDTH - FONT_SIZE * 20,
                                       area_y=HEIGHT - FONT_SIZE * 2)
    speech_recog_surface.changeText('Speech recognition output')
    all.add(speech_recog_surface)

    all.update()
    while 1:

        #clear/erase the last drawn sprites
        all.clear(screen, background)

        #update all the sprites
        all.update()

        #update the display
        pygame.display.update(all.draw(screen))

        clock.tick(40)
Exemple #25
0
def main():
    # init is a convenient way to initialize all subsystems
    # instead we could also initialize the submodules directly - for example by calling pygame.display.init(), pygame.display.quit()
    no_pass, no_fail = pygame.init()

    if no_fail > 0:
        print("Not all pygame modules initialized correctly")
        print(pygame.get_error())
    else:
        print("All pygame modules initializes")

    if not pygame.font:
        print("Pygame - fonts not loaded")
    if not pygame.mixer:
        print("Pygame - audio not loaded")
    if not pygame.display:
        print("Pygame - display not loaded")
    if not pygame.mouse:
        print("Pygame - mouse not loaded")

    print("Did we initialize: {}".format(pygame.get_init()))
    print("Pygame Version: {}".format(pygame.ver))
    print("Pygame runs on SDL Version: {}".format(pygame.get_sdl_version()))
    print("Pygame Display Driver: {}".format(pygame.display.get_driver()))

    # for pontential cleanup of other resources, we register a quit handler. This handler will be invoked whenever
    # pygame enters the quit state.
    pygame.register_quit(on_quit)

    w, h, t = 640, 480, "Elisa - 0 Pygame Initialization"
    c_white = (255, 255, 255)

    # here we create a display surface of width and height: https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode
    # we have different options to create a display surface, such as enabling double buffering, preparing it for opengl
    # removing borders or going full screen. However, we will not do any of this, by using the flags=0
    # this will create a default software rasterizer supported window of size, no full screen and default layout.
    # Setting the display mode will also return a buffer object/ pixel surface, that we can draw to.
    # then we set the window's caption and icon title (for shorter displays)
    # Then we make the mouse cursor visible
    screen_buffer = pygame.display.set_mode(size=(w, h), flags=0)
    pygame.display.set_caption(t, "Elisa 0")
    pygame.mouse.set_visible(True)

    # the next lines are concerned with supporting a double-buffered drawing approach.
    # in double-buffered drawing one does not draw to the display surface directly, in order to avoid drawing/ refresh issues.
    # instead one draws to a back buffer and when time comes then the image fully drawn to the back buffer will be copied to the displayed
    # front buffer.
    #
    # So we setup a back buffer, that matches our visible screen buffer in size, and for the time being clear it with white color.
    # Later on, we constantly copy (blit) our back buffer to the front buffer associated with the display and then flip, such
    # what is drawn to the back buffer becomes visible to our eyes - for the time being only a white canvas.
    back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size())
    back_buffer = back_buffer.convert()
    back_buffer.fill(c_white)

    # here we setup a pygamer clock - we will discuss this in a later example
    fps_watcher = pygame.time.Clock()
    is_done = False
    verbose = False
    # Now, we are ready to setup our game loop, where we loop until our application/ game is done - then we break from the loop.
    # As you can see, there is only condition that exits from the loop - and that is when the application receives a QUIT event message.
    # One way to receive this message is by clicking the closing button of the window.
    # Another way is to send ctrl+c in the console window.
    while not is_done:
        elapsed_millis = fps_watcher.tick(60)
        if verbose:
            print("Milli Seconds Elapsed: ", elapsed_millis)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                is_done = True
                break

        if not is_done:
            screen_buffer.blit(back_buffer, (0, 0))
            pygame.display.flip()

    # after exiting the loop we call it Quit - this will invoke our Quit handler and we are free to perform any heavy clean up lifting
    # such as freeing memory or releasing any other resources
    pygame.quit()
def main():
    # init is a convenient way to initialize all subsystems
    # instead we could also initialize the submodules directly - for example by calling pygame.display.init(), pygame.display.quit()
    no_pass, no_fail = pygame.init()

    if no_fail > 0:
        print("Not all pygame modules initialized correctly")
        print(pygame.get_error())
    else:
        print("All pygame modules initializes")

    if not pygame.font:
        print("Pygame - fonts not loaded")
    if not pygame.mixer:
        print("Pygame - audio not loaded")
    if not pygame.display:
        print("Pygame - display not loaded")
    if not pygame.mouse:
        print("Pygame - mouse not loaded")

    print("Did we initialize: {}".format(pygame.get_init()))
    print("Pygame Version: {}".format(pygame.ver))
    print("Pygame runs on SDL Version: {}".format(pygame.get_sdl_version()))
    print("Pygame Display Driver: {}".format(pygame.display.get_driver()))

    pygame.register_quit(on_quit)

    w, h, t = 640, 480, "Elisa - 19.1 Collision Detection - QuadTree"
    c_white = (255, 255, 255)
    c_black = (0, 0, 0)
    c_blue = (0, 0, 255)
    c_light_blue = (64, 64, 255)
    c_red = (255, 0, 0)

    screen_buffer = pygame.display.set_mode(size=(w, h), flags=0)
    pygame.display.set_caption(t)
    pygame.mouse.set_visible(True)

    back_buffer: pygame.Surface = pygame.Surface(screen_buffer.get_size())
    back_buffer = back_buffer.convert()
    back_buffer.fill(c_white)

    # here we setup a pygamer clock - we will discuss this in a later example
    fps_watcher = pygame.time.Clock()
    is_done = False

    # we compose a scene of ...
    poly1 = Poly2(points=[(50, 150), (150, 125), (200, 100), (150,
                                                              200), (100,
                                                                     175)])
    poly2 = Poly2(points=[(350, 100), (500, 150), (400, 200), (250, 150)])
    poly3 = Poly2(points=[(400, 300), (500, 300), (450, 325)])
    poly4 = Poly2(points=[(600, 400), (630, 400), (600, 420)])
    poly5 = Poly2(points=[(350, 250), (400, 250), (370, 300)])
    poly6 = Poly2(points=[(350, 20), (400, 50), (370, 100)])
    poly7 = Poly2(points=[(10, 10), (50, 10), (30, 30)])

    entities = [poly1, poly2, poly3, poly4, poly5, poly6]

    # in this we assume that the oob is already computed, i.e. we define it here:
    poly1_oob = [(50, 150), (100, 50), (200, 100), (150, 200)]
    poly2_oob = [(350, 100), (500, 150), (400, 200), (250, 150)]

    world_bounds = Rect2.from_points(0, 0, w, h)

    q_tree = QuadTree(area=world_bounds, max_depth=2)

    for p in entities:
        q_tree.insert(p)

    entities.append(poly7)
    q_tree.insert(poly7)

    # for introspection
    print(q_tree)
    print("Removing poly: {}".format(q_tree.remove(poly7)))
    print(q_tree)

    # now we define a query region ... something that we might be interested in
    # when doing our collision detection
    proposal_region = Rect2.from_points(300, 220, 500, 320)

    # we are going to update one poly along the x-axis.
    # this will be based on copying/ creating new objects, which is somewhat wasteful
    # for the purposes of the tutorial and the current code base, this is what we do
    _move_x_min, _move_x_max = 100, 600
    update_poly = poly5
    dir_x = 1.0

    while not is_done:
        _ = fps_watcher.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                is_done = True
                break

        back_buffer.fill(c_black)

        # update the two polys - this is wasteful ...
        _pminx, _pminy, _pmaxx, _pmaxy = update_poly.AABB

        if _pminx + (_pmaxx - _pminx) >= _move_x_max or _pminx <= _move_x_min:
            dir_x *= -1.0

        dx = dir_x * 1.0
        new_poly: Poly2 = Poly2.translate(update_poly, dx, 0.0)
        # update entities
        entities.remove(update_poly)
        entities.append(new_poly)

        # update the quad tree
        q_tree.replace(update_poly, new_poly)

        # replace the object identity
        update_poly = new_poly

        for r in q_tree:
            _r: Rect2 = r.points
            pygame.draw.polygon(back_buffer, c_white, _r, 1)

        pygame.draw.polygon(back_buffer, c_red, poly1_oob, 0)
        pygame.draw.polygon(back_buffer, c_red, poly2_oob, 0)

        for r in entities:
            pygame.draw.polygon(back_buffer, c_white, r.points, 1)

        pygame.draw.rect(back_buffer, c_blue, proposal_region.as_p_wh(), 1)

        proposals = q_tree.query(proposal_region)

        for p in proposals:
            pygame.draw.polygon(back_buffer, c_light_blue, p.points, 0)
            pygame.draw.polygon(back_buffer, c_blue, p.points, 1)

        if not is_done:
            screen_buffer.blit(back_buffer, (0, 0))
            pygame.display.flip()

    pygame.quit()
Exemple #27
0
def main(winstyle = 0):
    # Initialize pygame
    if pygame.get_sdl_version()[0] == 2:
        pygame.mixer.pre_init(44100, 32, 2, 1024)
    pygame.init()
    if pygame.mixer and not pygame.mixer.get_init():
        print ('Warning, no sound')
        pygame.mixer = None

    screenRect = Rect(0, 0, 800, 550)
    clock = pygame.time.Clock()
    dt = clock.tick(800)
    fullscreen = False
    # Set the display mode
    winstyle = 0  # |FULLSCREEN
    bestdepth = pygame.display.mode_ok(screenRect.size, winstyle, 32)
    screen = pygame.display.set_mode(screenRect.size, winstyle, bestdepth)
    white = (255,255,255)
    green = (23, 255, 15)

    #Load images, assign to sprite classes
    #(do this before the classes are used, after screen setup)
    
    img = loadImage('explosion1.gif')
    Explosion.images = [img, pygame.transform.flip(img, 1, 1)]
    Alien.images = loadImages('alien1.gif', 'alien2.gif', 'alien3.gif')
    Bomb.images = [loadImage('bomb.gif')]
    Shot.images = [loadImage('shot.png')]
    Health.images = [loadImage('health.gif')]

    img = loadImage('base1.gif')
    HomeBase.images = [img,pygame.transform.flip(img,1,0)]    

    #decorate the game window, makes app icon the rainbow ship image
    icon = pygame.transform.scale(loadImage("shipRainbow.gif"), (32, 32))
    pygame.display.set_icon(icon)
    pygame.display.set_caption('Jiah Presents: PyInvaders! (V1.2)')

    #create the background and tile the background image
    bgdtile = loadImage('hubbleimage.png')
    background = pygame.Surface(screenRect.size)
    for x in range(0, screenRect.width, bgdtile.get_width()):
        background.blit(bgdtile, (x, 0))
    screen.blit(background, (0,0))
    pygame.display.flip()

    #load the sound effects
    boom_sound = loadSound('boom.wav')
    shoot_sound = loadSound('laserSound.wav')
    #healthSound = loadSound('powerUp1.wav')
    if pygame.mixer:
        music = os.path.join(mainDir, 'data', 'gameMusic2.wav')
        pygame.mixer.music.load(music)
        pygame.mixer.music.play(-1)

    playing = True

    tFile = open("leaderboard.txt",'r+') 

    #Application loop, this only ends once the application is closed.
    while playing:
        clearScreenBG(screen,background)

        printSCText(150,"Click on a ship to select it for gameplay",screen,green,45)

        quitButton = placeImage("quitB.gif",352,470,screen)
        printSCText(480,"Quit",screen,white,40)

        sY =200
        #this loads the rainbow ship button (in the middle)
        rainbowShip = loadImage("shipRainbow.gif")
        xRShip = 352
        yRShip = 200
        screen.blit(rainbowShip,(xRShip,yRShip))
        #pygame.display.flip()

        #This loads the pink ship button to the left
        xPShip = 252
        silverShip = placeImage("shipSilver.gif",xPShip,sY,screen)

        #This loads the green ship button to the right
        xGShip = 452
        greenShip = placeImage("shipGreen.gif",xGShip,sY,screen)

        #Loads the title image
        title = placeCImage("title.gif",20,screen)
        
        shipType = 0

        #This is for the leaderboard. It is in the main loop so it works when replays occur
        names = []
        scores = []
        tFile = open("leaderboard.txt",'r+')
        list = tFile.read().splitlines()
        iterator = True
        i=int(0)
        ender = len(list)-1
        while iterator:
            name,scorez = list.pop(0).split("|") #"scorez" is used because both scores and score are in use
            names.append(name)
            scores.append(int(scorez))
            i = i+1
            if i>ender:
                iterator = False
            else:
                x = 1

        n = len(scores)

        #Simple bubble sort
        for i in range(n):
            for j in range(0, n-i-1):
                if scores[j] < scores[j+1] :
                    scores[j], scores[j+1] = scores[j+1], scores[j]
                    names[j],names[j+1]=names[j+1],names[j]

        #Prints the top 3 scores on the list.
        msgLB1 = names[0]+": "+str(scores[0])
        msgLB2 = names[1]+": "+str(scores[1])
        msgLB3 = names[2]+": "+str(scores[2])

        printCText(310,"HIGH SCORES",screen,green)
        printSCText(360,msgLB1,screen,white,30)
        printSCText(390,msgLB2,screen,white,30)
        printSCText(420,msgLB3,screen,white,30)

        #This loop is for the main menu
        notClicked = True
        while (notClicked):
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    
                    # Set the x, y postions of the mouse click
                    x, y = event.pos

                    if title.get_rect().collidepoint(x, y):
                        #idk what to do with this one atm but maybe this will launch the github project?
                        webbrowser.open_new("https://github.com/JiahLaBeouf/pyInvaders")

                    #Checks for the ships being clicked on
                    if xRShip<=x<=(xRShip+rainbowShip.get_width()) and sY<=y<=(sY+rainbowShip.get_height()):
                        shipType = 1
                        notClicked = False
                    elif xPShip <= x <= (xPShip+silverShip.get_width()) and sY <= y <= (sY+silverShip.get_width()):
                        shipType = 0
                        notClicked = False
                    elif xGShip<=x<=(xGShip+96) and sY<=y<=(sY+96):
                        shipType = 2
                        notClicked = False
                    elif collideP(352,470,quitButton,x,y):
                        pygame.quit()
                        sys.exit(0)
                        raise SystemExit
                        return

        clearScreenBG(screen,background)


        #Starting the layout for the game difficulty screen
        
        #Places the two independent captions
        printSCText(80,"Select Game Difficulty",screen,green,75)
        printSCText(400,"Game controls will appear once difficulty selected",screen,white,30)

        easy = placeImage("easy.gif",216,200,screen)
        printText(218,205,"Easy",screen,white)

        medium = placeImage("medium.png",340,200,screen)
        printCText(205,"Medium",screen,white)

        hard = placeImage("hard.gif",488,200,screen)
        printText(490,205,"Hard",screen,white)

        difficulty = None

        #This while loop is where the difficulty is determined
        #This uses the self made collideP method to detect mouse clicks on objects.
        difficultyChoice = True
        while (difficultyChoice):
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                # Set the x, y postions of the mouse click
                    x, y = event.pos
                    
                    if collideP(216,200,easy,x,y):
                        difficulty = 0
                        difficultyChoice = False
                    elif collideP(340,200,medium,x,y):
                        difficulty = 1
                        difficultyChoice = False
                    elif collideP(488,200,hard,x,y):
                        difficulty = 2
                        difficultyChoice = False

        clearScreenBG(screen,background)

        #This loads the control screen and blits to cover screen.
        sc1 = loadImage("controls.gif")
        clearScreenBG(screen,sc1)

        #This is the controls screen, which waits for a click anywhere, hence no collide methods.
        #This could also go with a spacebar press if time allows
        clicked = False
        while not clicked:
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    clicked = True
                elif (event.type == KEYDOWN and event.key == K_SPACE):
                    clicked = True


        clearScreenBG(screen,background)

        #The mouse is now set invisible so that there is no interruption to gameplay
        pygame.mouse.set_visible(0)


        #The ship is now loaded based on earlier preference from the start menu.
        if shipType == 0:
            imgP = loadImage('shipSilver.gif')
        elif shipType == 1:
            imgP = loadImage('shipRainbow.gif')
        elif shipType == 2:
            imgP = loadImage("shipGreen.gif")
        Player.images = [imgP, pygame.transform.flip(imgP, 1, 0)]

        


        # Initialize Game Groups
        aliens = pygame.sprite.Group()
        shots = pygame.sprite.Group()
        bombs = pygame.sprite.Group()
        healths = pygame.sprite.Group()
        all = pygame.sprite.RenderUpdates()
        lastalien = pygame.sprite.GroupSingle()

        #assign default groups to each sprite class
        Player.containers = all
        Alien.containers = aliens, all, lastalien
        HomeBase.containers = all
        Shot.containers = shots, all
        Bomb.containers = bombs, all
        Explosion.containers = all
        Score.containers = all
        Lives.containers = all
        Timer.containers = all
        Health.containers = healths, all

        #Create Some Starting Values, as well as initialising global variables for the sprites during gameplay
        global score
        global inGameTime
        global lives
        framesPerAlien = ALIEN_RELOAD
        kills = 0
        clock = pygame.time.Clock()
        lives = 3
        inGameTime = 0
        score = 0

        #Init starting sprites (or 'living sprites')
        #adding the homebase, passes in the screen so it can determine it's staring position.
        homeBase = HomeBase(screenRect)
        #player after homebase so it goes in front
        player = Player(screenRect)
        Alien(screenRect) #this 'lives' because it goes into a sprite group

        #adding the value sprites to the game screen
        if pygame.font:
            all.add(Score(score))
            all.add(Lives(lives))
            all.add(Timer(inGameTime))

        

        #This has the potential to be proportional to the score if more challenge is required
        maxShots = 4
        
        aliensDead=0

        #Used later, in the endgame menu
        causeOfDeath = 0

        startTime = pygame.time.get_ticks()

        #This loop is essentially the gameplay loop. It ends whenever the player is killed
        while player.alive():

            #Used to determine difficulty and could potentially be used to determine powerup lengths
            inGameTime = round(((pygame.time.get_ticks()) - startTime)/1000)


            #Increasing difficulty rate here. Uses the time to determine how many aliens spawn and when
            
            #Easy difficulty. Never changes, this has room for improvement
            if difficulty == 0:
                if inGameTime<=10:
                    alienReload = 7
                
            #Medium difficulty
            elif difficulty == 1:
                if inGameTime<=10:
                    alienReload = 6
                elif 10<=inGameTime<=120:
                    #This specific range is due to the divisor, to avoid rounding to zero.
                    alienReload = round(6/((inGameTime/10)+0.001))
                else:
                    alienReload = 2

            #Hard difficulty
            elif difficulty == 2:
                if inGameTime<=10:
                    alienReload = 6
                elif 10<=inGameTime<=70:
                    #This specific range is due to the divisor, to avoid rounding to zero.
                    alienReload = round(6/(inGameTime/6)+0.01)
                else:
                    alienReload = 1

            

            #get input to determine quitting application or changing to fullscreen. May depreciate this.
            for event in pygame.event.get():
                if event.type == QUIT or \
                    (event.type == KEYDOWN and event.key == K_ESCAPE):
                        return
                elif event.type == KEYDOWN:
                    if event.key == pygame.K_f:
                        if not fullscreen:
                            #print("Changing to FULLSCREEN")
                            screen_backup = screen.copy()
                            screen = pygame.display.set_mode(
                                screenRect.size,
                                winstyle | FULLSCREEN,
                                bestdepth
                            )
                            screen.blit(screen_backup, (0, 0))
                        else:
                            #print("Changing to windowed mode")
                            screen_backup = screen.copy()
                            screen = pygame.display.set_mode(
                                screenRect.size,
                                winstyle,
                                bestdepth
                            )
                            screen.blit(screen_backup, (0, 0))
                        # screen.fill((255, 0, 0))
                        pygame.display.flip()
                        fullscreen = not fullscreen


            

            # clear/erase the last drawn sprites
            all.clear(screen, background)

            #update all the sprites
            all.update()
            homeBase.update()

            keystate = pygame.key.get_pressed()

            #handle player input to determine character movement.
            direction = keystate[K_RIGHT] - keystate[K_LEFT]
            player.move(direction,dt)

            #This is incase of 2 player and/or random movement, currently homebase has 0 velocity but this could change in the future
            direction2 = keystate[K_UP] - keystate[K_DOWN]
            homeBase.move(direction2)

            #The firing code
            firing = keystate[K_SPACE]
            if not player.reloading and firing and len(shots) < maxShots:
                Shot(player.gunpos())
                shoot_sound.play()
            player.reloading = firing

            # Create new alien

            #The formula for the odds logic, essentially rounds a random number to 0 or 1
            odds = int(random.random() * ALIEN_ODDS)

            if framesPerAlien>=0:
                framesPerAlien = framesPerAlien - 1
            elif odds ==0:
                #This basically gives the odds of an alien showing up.
                Alien(screenRect)
                framesPerAlien = alienReload
            # Drop bombs
            if lastalien and not int(random.random() * BOMB_ODDS):
                Bomb(lastalien.sprite)

            # Detect collisions

            #This is for if an alien reaches a player, which results in instant death.
            for alien in pygame.sprite.spritecollide(player, aliens, 1):
                boom_sound.play()
                Explosion(alien)
                Explosion(player)
                score += 1

                screen.blit(background,(0,0))
                pygame.time.wait(1000)

                player.kill()

            #Bullet and alien collision
            for alien in pygame.sprite.groupcollide(shots, aliens, 1, 1).keys():
                boom_sound.play()
                aliensDead+=1
                if aliensDead%2==0:
                    Bomb(alien)
                Explosion(alien)
                if aliensDead%10 == 0:
                    Health(alien)
                score += 1

            #bomb hitting player
            for bomb in pygame.sprite.spritecollide(player, bombs, 1):
                boom_sound.play()
                Explosion(player)
                Explosion(bomb)
                #player.kill()
                lives-=1

            #Player collecting health
            for health in pygame.sprite.spritecollide(player,healths,1):
                #healthSound.play()
                lives +=1
                health.kill()
                #play health up sound if interviews suggest it

            #Bombing home base
            for bomb in pygame.sprite.spritecollide(homeBase, bombs, 1):
                boom_sound.play()
                Explosion(homeBase)
                Explosion(bomb)
                causeOfDeath = 1
                player.kill()

            #Creation of this is to introduce new scoring methods, shooting a bomb is worth double points
            for shot in pygame.sprite.groupcollide(bombs, shots, 1, 1).keys():
                boom_sound.play()
                Explosion(shot)
                #Explosion(bomb)
                #player.kill()
                
                #Bonuses for shooting a bomb
                score += 2
                #Potential powerup for every bomb scored? or possibly for the actual score count.


            if lives==0:
                screen.blit(background,(0,0))
                pygame.time.wait(1000)
                causeOfDeath = 2
                player.kill()

            #This is for manual game end without dying from bombs or aliens
            if keystate[K_k]:
                screen.blit(background,(0,0))
                pygame.display.flip()
                pygame.time.wait(1000)
                causeOfDeath = 3

                player.kill()

            #draw the scene
            dirty = all.draw(screen)
            pygame.display.update(dirty)

            #cap the framerate
            clock.tick(40)

        #THIS is where the endgame goes
        #Blanks the screen and then adds all buttons and items to the screen
        #print("about to set to black")
        screen.fill((0,0,0))
        screen.blit(background, (0,0))
        pygame.display.flip()
        #pygame.display.update()
        #print("we've blitted the screen now")

        menuButton = placeImage("mainMenu.gif",325,300,screen)
        printSCText(310,"Main Menu",screen,white,40)

        quitButton = placeImage("quitB.gif",352,400,screen)
        printCText(400,"Quit",screen,white)

        printCText(60,"You scored "+str(score)+" points!",screen, white)
        
        if causeOfDeath == 1:
            msg1 = "Cause of death: Homebase was destroyed!"
        elif causeOfDeath == 2:
            msg1 = "Cause of death: Ran out of lives!"
        elif causeOfDeath == 3:
            msg1 = "Cause of death: k pressed!"
        else:
            msg1 = "unknown cause of death"
        printCText(120,msg1,screen,white)
        
        #Sets the mouse to visible so it can be seen in the menus
        pygame.mouse.set_visible(1)

        textEntry = ''

        # error = False
    
        # while True:
        #     for event in pygame.event.get():
        #         if event.type == QUIT:
        #             pygame.quit()
        #             sys.exit()
        #         if event.type == KEYDOWN:
        #             if event.key == K_BACKSPACE:
        #                 text_entry = text_entry[:-1]
        #             elif event.key == K_RETURN:
        #                 pass
        #             else:
        #                 text_entry += event.unicode

        printCText(200,"Enter Name:            ",screen,green)

        replay = True
        while replay == True:

            printText(400,200,textEntry,screen,white)

            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                # Set the x, y postions of the mouse click
                    x, y = event.pos

                    if collideP(352,400,quitButton,x,y):
                        # pygame.quit()
                        # sys.exit(0)
                        playing = False
                        replay = False
                        

                    elif collideP(325,300,menuButton,x,y):
                        replay = False
                #Text entry code (keylogger)
                elif event.type == KEYDOWN:
                    if event.key == K_BACKSPACE:
                        textEntry = textEntry[:-1]
                        placeImage("textBG.gif",400,200,screen)
                    elif event.key == K_RETURN:
                        pass
                    else:
                        textEntry += event.unicode

        #Writes the name and score to the leaderboard file.
        nameW = str(textEntry)
        tFile.write("\n"+nameW+"|"+str(score))



    #End logic, fades music and quits pygame
    if pygame.mixer:
        pygame.mixer.music.fadeout(1000)
    pygame.time.wait(1000)

    pygame.quit()
Exemple #28
0
#!/usr/bin/env python
""" pg.examples.textinput

A little "console" where you can write in text.

Shows how to use the TEXTEDITING and TEXTINPUT events.
"""
from __future__ import print_function
import sys
import pygame as pg
import pygame.freetype as freetype

# Version check
if pg.get_sdl_version() < (2, 0, 0):
    raise Exception("This example requires pygame 2.")

###CONSTS
# Set to true or add 'showevent' in argv to see IME and KEYDOWN events
PRINT_EVENT = False
# frames per second, the general speed of the program
FPS = 50
# size of window
WINDOWWIDTH, WINDOWHEIGHT = 640, 480
BGCOLOR = (0, 0, 0)

# position of chatlist and chatbox
CHATLIST_POS = pg.Rect(0, 20, WINDOWWIDTH, 400)
CHATBOX_POS = pg.Rect(0, 440, WINDOWWIDTH, 40)
CHATLIST_MAXSIZE = 20

TEXTCOLOR = (0, 255, 0)
Exemple #29
0
TEXTCOLOR = (0, 255, 0)

# Add fontname for each language, otherwise some text can't be correctly displayed.
FONTNAMES = [
    "notosanscjktcregular",
    "notosansmonocjktcregular",
    "notosansregular,",
    "microsoftjhengheimicrosoftjhengheiuilight",
    "microsoftyaheimicrosoftyaheiuilight",
    "msgothicmsuigothicmspgothic",
    "msmincho",
    "Arial",
]

# Version check
if pygame.get_sdl_version() < (2, 0, 0):
    raise Exception("This example requires SDL2.")

# Initalize
pygame.init()
Screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption("TextInput example")
FPSClock = pygame.time.Clock()

# Freetype
# "The font name can be a comma separated list of font names to search for."
FONTNAMES = ",".join(str(x) for x in FONTNAMES)
Font = pygame.freetype.SysFont(FONTNAMES, 24)
FontSmall = pygame.freetype.SysFont(FONTNAMES, 16)
print("Using font: " + Font.name)
Exemple #30
0
def loaderScreen():
    if pygame.get_sdl_version() < (2, 0, 0):
        print("Loading Window requires SDL version 2.0 or greater")
        return False
    screendims = (500, 500)
    pygame.init()
    screen = pygame.display.set_mode(screendims)
    pygame.display.set_caption("Set Demiverse Properties")
    ticker = pygame.time.Clock()
    editfont = pygame.font.SysFont(None, 30)
    displayfont = pygame.font.SysFont(None, 32)
    pygame.key.start_text_input()
    cursor = ['|', 60]  #(cursor char,blinkrate)
    submitButton = displayfont.render("Submit", True, (0, 0, 0))
    submitBound = submitButton.get_rect()
    submitBound.y = screendims[1] - (submitBound.h + 10)
    submitBound.x = int(screendims[0] / 2) - int(submitBound.w / 2)
    blinker = 1
    blinkflag = False
    preInputText = ""
    postInputText = ""
    errorText = ""
    errorFlag = False
    errortime = 3
    errorframes = 0
    prompts = [
        "Screen Height (px) ", "Screen Width (px)  ", "Chunk Height (px)  ",
        "Chunk Width (px)   ", "Framerate (fps)     ", "Duration (sec)       "
    ]
    flatPrompts = [
        "screen_height", "screen_width", "chunk_height", "chunk_width",
        "framerate", "duration"
    ]
    promptLabels = []

    for i, prompt in enumerate(prompts):
        promptLabel = displayfont.render(prompt, True, (0, 0, 0))
        inputx = promptLabel.get_width() + 5
        inputy = int((i * screendims[1]) / len(prompts)) + 10
        inputw = screendims[0] - inputx - 5
        inputh = promptLabel.get_height()
        promptLabels.append(
            [promptLabel,
             pygame.Rect(inputx, inputy, inputw, inputh), ""])

    focus_i = 0
    focus = promptLabels[focus_i][1].inflate(-5, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return False
            if (event.type == pygame.KEYDOWN) and (event.key
                                                   == pygame.K_BACKSPACE):
                if len(preInputText) > 0:
                    preInputText = preInputText[:-1]
                continue
            if (event.type == pygame.KEYDOWN) and (event.key
                                                   == pygame.K_DELETE):
                if len(postInputText) > 0:
                    postInputText = postInputText[1:]
                continue
            if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_TAB):
                promptLabels[focus_i][2] = preInputText + postInputText
                focus_i = 0 if focus_i >= (len(promptLabels) -
                                           1) else focus_i + 1
                focus = promptLabels[focus_i][1].inflate(-5, -5)
                preInputText = promptLabels[focus_i][2]
                postInputText = ""
                continue
            if (event.type
                    == pygame.MOUSEBUTTONUP) and (submitBound.collidepoint(
                        event.pos)):
                promptLabels[focus_i][2] = preInputText + postInputText
                try:
                    retval = []
                    for i, label in enumerate(promptLabels):
                        retval.append((flatPrompts[i], int(label[2])))
                    retval = dict(retval)
                    pygame.quit()
                    return retval
                except:
                    errorText = "Not all values are numeric, try again"
                    errorFlag = True
                    errorframes = errortime * 60
            if event.type == pygame.MOUSEBUTTONUP:
                for i, label in enumerate(promptLabels):
                    if label[1].collidepoint(event.pos):
                        promptLabels[focus_i][2] = preInputText + postInputText
                        focus_i = i
                        focus = promptLabels[focus_i][1].inflate(-5, -5)
                        preInputText = promptLabels[focus_i][2]
                        postInputText = ""
                continue
            if (event.type == pygame.KEYDOWN) and (
                (event.key == pygame.K_LEFT) or event.key == pygame.K_RIGHT):
                if event.key == pygame.K_RIGHT:
                    if len(postInputText) > 0:
                        preInputText = preInputText + postInputText[0]
                        postInputText = postInputText[1:]
                else:
                    if len(preInputText) > 0:
                        postInputText = preInputText[-1] + postInputText
                        preInputText = preInputText[:-1]
                continue
            if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_HOME):
                postInputText = preInputText + postInputText
                preInputText = ""
                continue
            if (event.type == pygame.KEYDOWN) and (event.key == pygame.K_END):
                preInputText = preInputText + postInputText
                postInputText = ""
                continue
            if event.type == pygame.TEXTINPUT:
                preInputText += event.text

        screen.fill((100, 125, 150))
        for promptLabel in promptLabels:
            screen.blit(promptLabel[0], (0, promptLabel[1][1]))
            pygame.draw.rect(screen, (0, 0, 0), promptLabel[1].inflate(4, 4))
            pygame.draw.rect(screen, (255, 255, 255), promptLabel[1])

        pygame.draw.rect(screen, (0, 0, 0), submitBound.inflate(5, 5))
        pygame.draw.rect(screen, (200, 200, 200), submitBound)
        screen.blit(submitButton, submitBound)

        if (cursor[1] % blinker) == 0:
            blinkflag = not blinkflag

        preEditText = editfont.render(preInputText, True, (0, 0, 0))
        postEditText = editfont.render(postInputText, True, (0, 0, 0))
        for i, label in enumerate(promptLabels):
            if focus_i == i:
                screen.blit(preEditText, focus)
                if blinkflag:
                    cursorText = editfont.render(cursor[0], True, (0, 0, 0))
                    screen.blit(
                        cursorText,
                        (preEditText.get_rect().right + focus.x - 2, focus.y))
                screen.blit(postEditText,
                            (preEditText.get_rect().right + focus.x, focus.y))
            else:
                screen.blit(editfont.render(label[2], True, (0, 0, 0)),
                            label[1].inflate(-5, -5))
        if errorFlag:
            errorDisplay = displayfont.render(errorText, True, (255, 0, 0))
            errorRect = errorDisplay.get_rect()
            errorRect.x = 0
            errorRect.y = screendims[1] - errorRect.h
            pygame.draw.rect(screen, (255, 240, 240), errorRect)
            screen.blit(errorDisplay, errorRect)
        errorframes = 0 if errorframes <= 0 else errorframes - 1
        errorFlag = errorframes != 0
        pygame.display.flip()
        blinker = blinker + 1 if blinker <= cursor[1] else 1
        ticker.tick(60)

    pygame.quit()
    return False
@author: jt
"""
"""
Copyright 2017, Silas Gyger, [email protected], All rights reserved.

Borrowed from https://github.com/Nearoo/pygame-text-input under the MIT license.
with jt additions to take advantage of pygame2 features
"""

# import os.path

import pygame as pg
import pygame.freetype
# import pygame.locals as pl

IS_PYGAME2 = pg.get_sdl_version() > (2, 0, 0)


def get_font(font_name, size=None):
    """
    Converts a font_name (string) to a pygame font object
    """

    if size is None: size = 18

    font_object = pg.freetype.SysFont('consolas', size)  # default value

    # First check if font_name is a system font
    if font_name in pg.freetype.get_fonts():
        return pg.freetype.SysFont(font_name, size)
CHATBOX_POS = pygame.Rect(0, 440, WINDOWWIDTH, 40)
CHATLIST_MAXSIZE = 20

TEXTCOLOR = (0, 255, 0)

# Add fontname for each language, otherwise some text can't be correctly displayed.
FONTNAMES = ["notosanscjktcregular", "notosansmonocjktcregular",
             "notosansregular,",
             "microsoftjhengheimicrosoftjhengheiuilight",
             "microsoftyaheimicrosoftyaheiuilight",
             "msgothicmsuigothicmspgothic",
             "msmincho",
             "Arial"]

# Version check
if (pygame.get_sdl_version() < (2, 0, 0)):
    raise Exception("This example requires SDL2.")

# Initalize
pygame.init()
Screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption("TextInput example")
FPSClock = pygame.time.Clock()

# Freetype
# "The font name can be a comma separated list of font names to search for."
FONTNAMES = ",".join(str(x) for x in FONTNAMES)
Font = pygame.freetype.SysFont(FONTNAMES, 24)
FontSmall = pygame.freetype.SysFont(FONTNAMES, 16)
print("Using font: " + Font.name)
Exemple #33
0
renderpyg is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
pytmx is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with renderpyg.

If not, see <http://www.gnu.org/licenses/>.
'''
import os, sys
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "1"
import pygame as pg

_version = '0.0.1'
if pg.get_sdl_version()[0] < 2:
    raise SystemExit("This example requires pygame 2 and SDL2.")
print('renderpy {} running on pygame {} (SDL {}.{}.{}, python {}.{}.{})\n'.
      format(_version, pg.version.ver,
             *pg.get_sdl_version() + sys.version_info[0:3]))

from .base import fetch_images, load_texture, load_images, scale_rect, scale_rect_ip
from .sprite import keyfr, keyframes, keyrange
from .sprite import GPUAniSprite as Sprite
from .tilemap import load_tmx, load_tilemap_string, load_tileset, render_tilemap, Tilemap
from .tfont import TextureFont, NinePatch
Exemple #34
0
 def build(self):
     import pygame
     print 'pygame version:', pygame.ver
     print 'SDL version:', pygame.get_sdl_version()
Exemple #35
0
import os
import sys
import unittest
import collections

import pygame
from pygame.compat import as_unicode


PY3 = sys.version_info >= (3, 0, 0)
SDL1 = pygame.get_sdl_version()[0] < 2

################################################################################

EVENT_TYPES = (
    #   pygame.NOEVENT,
    #   pygame.ACTIVEEVENT,
    pygame.KEYDOWN,
    pygame.KEYUP,
    pygame.MOUSEMOTION,
    pygame.MOUSEBUTTONDOWN,
    pygame.MOUSEBUTTONUP,
    pygame.JOYAXISMOTION,
    pygame.JOYBALLMOTION,
    pygame.JOYHATMOTION,
    pygame.JOYBUTTONDOWN,
    pygame.JOYBUTTONUP,
    pygame.VIDEORESIZE,
    pygame.VIDEOEXPOSE,
    pygame.QUIT,
    pygame.SYSWMEVENT,
Exemple #36
0
# -*- coding: utf-8 -*-

import unittest
import os
import time

import pygame, pygame.transform
from pygame.compat import unicode_
from pygame.locals import *
from pygame.tests.test_utils import question

from pygame import display

SDL2 = pygame.get_sdl_version()[0] >= 2


class DisplayModuleTest(unittest.TestCase):
    default_caption = "pygame window"

    def setUp(self):
        display.init()

    def tearDown(self):
        display.quit()

    def test_update(self):
        """ see if pygame.display.update takes rects with negative values.
            "|Tags:display|"
        """
        screen = pygame.display.set_mode((100, 100))
        screen.fill((55, 55, 55))
Exemple #37
0
import pygame

if pygame.get_sdl_version()[0] < 2:
    raise SystemExit('This example requires pygame 2 and SDL2.')

import os
data_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], 'data')

from pygame._sdl2 import (
    Window,
    Texture,
    Renderer,
    get_drivers,
    messagebox,
)


def load_img(file):
    return pygame.image.load(os.path.join(data_dir, file))


pygame.display.init()
pygame.key.set_repeat(1000, 10)

for driver in get_drivers():
    print(driver)

import random
answer = messagebox("I will open two windows! Continue?",
                    "Hello!",
                    info=True,
Exemple #38
0
pybgimg = pygame.image.load("/usr/share/wallpapers/Sky.jpg");
pybgimg = pygame.transform.scale(pybgimg, (width, height));
'''
barcodeobj={};
barcodedrw={};
barcodeimg={};
position={};
dirx={};
diry={};
randbarcode={};
randsubbarcode={};
randchck={};
count=0;
maxnum=numbarcodes;
print("Python Version: "+platform.python_version());
pygamesdlver=pygame.get_sdl_version();
pygamesdlstr=str(pygamesdlver[0])+"."+str(pygamesdlver[1])+"."+str(pygamesdlver[2]);
del(pygamesdlver);
print("SDL Version: "+pygamesdlstr);
del(pygamesdlstr);
pygamever=pygame.version.vernum;
pygamestr=str(pygamever[0])+"."+str(pygamever[1])+"."+str(pygamever[2]);
del(pygamever);
print("PyGame Version: "+pygamestr);
del(pygamestr);
print("PIL Version: "+Image.VERSION);
try:
 print("Pillow Version: "+Image.PILLOW_VERSION);
except AttributeError:
 pass;
except NameError:
Exemple #39
0
snake_tail_2.move_ip(0, -10)
snake_tail_positions = [snake_tail, snake_tail_2]

# Création d'un sprite pomme
apple_x = random.randint(0, 9) * 10
apple_y = random.randint(0, 9) * 10
while apple_x == 40:
    apple_x = random.randint(0, 9) * 10
while apple_y == 40:
    apple_y = random.randint(0, 9) * 10
apple = pygame.draw.rect(fenetre, [250, 0, 0], (apple_x, apple_y, 10, 10))
apple_ate = False

# print des infos
print(pygame.display.Info())
print(pygame.get_sdl_version())

# Boucle
continuer = 1
while continuer:
    for event in pygame.event.get():
        if event.type == QUIT:
            continuer = 0
        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                snake_direction = "R"
            if event.key == K_LEFT:
                snake_direction = "L"
            if event.key == K_DOWN:
                snake_direction = "D"
            if event.key == K_UP:
Exemple #40
0
octopg_ver = "0.4.0"
octopg_vernum = (0, 4, 0)


def vernum_to_ver(vernum):
    return ".".join(map(str, vernum))


import pygame
import pygame.version

pg_ver = pygame.version.ver
pg_vernum = pygame.version.vernum

sdl_vernum = pygame.get_sdl_version()
sdl_ver = vernum_to_ver(sdl_vernum)


import urllib.request as url
import json
from operator import itemgetter

"""
check_updates()

Check if an update is available for the OctoPG library

@return (bool|dict) False when there is no update, the release info when the update is available
"""
Exemple #41
0
 def version(self):
     print(pygame.get_sdl_version())