Compare commits

...
15 Commits
Author SHA1 Message Date
Rbanh b8eeaa4739 Major code restructuring: Reorganized project structure, added AI components - Added new module structure (ai, config, core, ui) - Moved snake and food logic into core module - Added training configuration - Updated gitignore for project-specific files - Modified tests to match new structure 2025-02-24 18:38:44 -05:00
Rbanh 251822ec35 Fix menu crash: - Add back MenuItem.draw method - Remove duplicate MenuItem class - Fix menu item imports 2025-02-23 13:06:09 -05:00
Rbanh d1fb3a58b4 Fix menu navigation: - Add proper item highlighting - Improve keyboard and mouse controls - Fix settings menu interaction - Update menu items continuously 2025-02-23 13:04:38 -05:00
Rbanh be7b7caf28 Fix game issues: - Prevent rapid direction changes - Add proper settings menu - Fix menu highlighting - Add wrap-around toggle in settings 2025-02-23 12:58:32 -05:00
Rbanh 766355a2b9 Improve game mechanics and UI: - Add wrap-around mode and speed increase - Implement proper movement cooldown - Enhance menu UI with better layout and interactions - Add visual feedback and mouse support 2025-02-23 12:53:41 -05:00
Rbanh 31e9771ba0 Fix package structure and entry point 2025-02-23 12:41:06 -05:00
Rbanh 0571392afe Improve package structure and add proper setup.py 2025-02-23 12:38:45 -05:00
Rbanh 75a9cc5ba8 Fix test discovery by adding __init__.py files 2025-02-23 12:32:32 -05:00
Rbanh afd17d257e Fix food spawn test and optimize test performance 2025-02-23 12:30:39 -05:00
Rbanh fcab6ec766 Fix food spawn test and optimize test execution 2025-02-23 12:25:28 -05:00
Rbanh cb626dfe7d Add testing framework and debug mode 2025-02-23 12:20:23 -05:00
Rbanh 33cca6cd3c Add main menu system with game mode selection 2025-02-23 12:16:14 -05:00
Rbanh 3cbf7b8981 Update .gitignore to properly exclude virtual environments 2025-02-23 12:14:17 -05:00
Rbanh 68b3c03423 Remove virtual environment from git tracking 2025-02-23 12:13:55 -05:00
Rbanh 18ff38fe47 Add game restart functionality and update roadmap 2025-02-23 12:13:24 -05:00
83 changed files with 4430 additions and 10425 deletions

No files matched your search

+17
View File
@@ -1,7 +1,13 @@
# Virtual Environment
.venv/
venv/
env/
ENV/
.env/
.virtualenv/
virtualenv/
*venv/
Activate.ps1
# Python
__pycache__/
@@ -34,3 +40,14 @@ wheels/
# OS
.DS_Store
Thumbs.db
# Project specific
logs/
models/
.pytest_cache/
path/
training_data/
*.log
*.pth
*.ckpt
*.h5
@@ -1,21 +0,0 @@
#define NO_PYGAME_C_API
#include "_surface.h"
/* The structure passed to the low level blit functions */
typedef struct {
int width;
int height;
Uint8 *s_pixels;
int s_pxskip;
int s_skip;
Uint8 *d_pixels;
int d_pxskip;
int d_skip;
SDL_PixelFormat *src;
SDL_PixelFormat *dst;
Uint8 src_blanket_alpha;
int src_has_colorkey;
Uint32 src_colorkey;
SDL_BlendMode src_blend;
SDL_BlendMode dst_blend;
} SDL_BlitInfo;
@@ -1,26 +0,0 @@
/*
pygame - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _CAMERA_H
#define _CAMERA_H
#include "_pygame.h"
#include "camera.h"
#endif
@@ -1,374 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* This will use PYGAMEAPI_EXTERN_SLOTS instead
* of PYGAMEAPI_DEFINE_SLOTS for base modules.
*/
#ifndef _PYGAME_INTERNAL_H
#define _PYGAME_INTERNAL_H
#include "pgplatform.h"
/*
If PY_SSIZE_T_CLEAN is defined before including Python.h, length is a
Py_ssize_t rather than an int for all # variants of formats (s#, y#, etc.)
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
/* Ensure PyPy-specific code is not in use when running on GraalPython (PR
* #2580) */
#if defined(GRAALVM_PYTHON) && defined(PYPY_VERSION)
#undef PYPY_VERSION
#endif
#include <SDL.h>
/* SDL 1.2 constants removed from SDL 2 */
typedef enum {
SDL_HWSURFACE = 0,
SDL_RESIZABLE = SDL_WINDOW_RESIZABLE,
SDL_ASYNCBLIT = 0,
SDL_OPENGL = SDL_WINDOW_OPENGL,
SDL_OPENGLBLIT = 0,
SDL_ANYFORMAT = 0,
SDL_HWPALETTE = 0,
SDL_DOUBLEBUF = 0,
SDL_FULLSCREEN = SDL_WINDOW_FULLSCREEN,
SDL_HWACCEL = 0,
SDL_SRCCOLORKEY = 0,
SDL_RLEACCELOK = 0,
SDL_SRCALPHA = 0,
SDL_NOFRAME = SDL_WINDOW_BORDERLESS,
SDL_GL_SWAP_CONTROL = 0,
TIMER_RESOLUTION = 0
} PygameVideoFlags;
/* the wheel button constants were removed from SDL 2 */
typedef enum {
PGM_BUTTON_LEFT = SDL_BUTTON_LEFT,
PGM_BUTTON_RIGHT = SDL_BUTTON_RIGHT,
PGM_BUTTON_MIDDLE = SDL_BUTTON_MIDDLE,
PGM_BUTTON_WHEELUP = 4,
PGM_BUTTON_WHEELDOWN = 5,
PGM_BUTTON_X1 = SDL_BUTTON_X1 + 2,
PGM_BUTTON_X2 = SDL_BUTTON_X2 + 2,
PGM_BUTTON_KEEP = 0x80
} PygameMouseFlags;
typedef enum {
/* Any SDL_* events here are for backward compatibility. */
SDL_NOEVENT = 0,
SDL_ACTIVEEVENT = SDL_USEREVENT,
SDL_VIDEORESIZE,
SDL_VIDEOEXPOSE,
PGE_MIDIIN,
PGE_MIDIOUT,
PGE_KEYREPEAT, /* Special internal pygame event, for managing key-presses
*/
/* DO NOT CHANGE THE ORDER OF EVENTS HERE */
PGE_WINDOWSHOWN,
PGE_WINDOWHIDDEN,
PGE_WINDOWEXPOSED,
PGE_WINDOWMOVED,
PGE_WINDOWRESIZED,
PGE_WINDOWSIZECHANGED,
PGE_WINDOWMINIMIZED,
PGE_WINDOWMAXIMIZED,
PGE_WINDOWRESTORED,
PGE_WINDOWENTER,
PGE_WINDOWLEAVE,
PGE_WINDOWFOCUSGAINED,
PGE_WINDOWFOCUSLOST,
PGE_WINDOWCLOSE,
PGE_WINDOWTAKEFOCUS,
PGE_WINDOWHITTEST,
PGE_WINDOWICCPROFCHANGED,
PGE_WINDOWDISPLAYCHANGED,
/* Here we define PGPOST_* events, events that act as a one-to-one
* proxy for SDL events (and some extra events too!), the proxy is used
* internally when pygame users use event.post()
*
* At a first glance, these may look redundant, but they are really
* important, especially with event blocking. If proxy events are
* not there, blocked events dont make it to our event filter, and
* that can break a lot of stuff.
*
* IMPORTANT NOTE: Do not post events directly with these proxy types,
* use the appropriate functions from event.c, that handle these proxy
* events for you.
* Proxy events are for internal use only */
PGPOST_EVENTBEGIN, /* mark start of proxy-events */
PGPOST_ACTIVEEVENT = PGPOST_EVENTBEGIN,
PGPOST_APP_TERMINATING,
PGPOST_APP_LOWMEMORY,
PGPOST_APP_WILLENTERBACKGROUND,
PGPOST_APP_DIDENTERBACKGROUND,
PGPOST_APP_WILLENTERFOREGROUND,
PGPOST_APP_DIDENTERFOREGROUND,
PGPOST_AUDIODEVICEADDED,
PGPOST_AUDIODEVICEREMOVED,
PGPOST_CLIPBOARDUPDATE,
PGPOST_CONTROLLERAXISMOTION,
PGPOST_CONTROLLERBUTTONDOWN,
PGPOST_CONTROLLERBUTTONUP,
PGPOST_CONTROLLERDEVICEADDED,
PGPOST_CONTROLLERDEVICEREMOVED,
PGPOST_CONTROLLERDEVICEREMAPPED,
PGPOST_CONTROLLERTOUCHPADDOWN,
PGPOST_CONTROLLERTOUCHPADMOTION,
PGPOST_CONTROLLERTOUCHPADUP,
PGPOST_CONTROLLERSENSORUPDATE,
PGPOST_DOLLARGESTURE,
PGPOST_DOLLARRECORD,
PGPOST_DROPFILE,
PGPOST_DROPTEXT,
PGPOST_DROPBEGIN,
PGPOST_DROPCOMPLETE,
PGPOST_FINGERMOTION,
PGPOST_FINGERDOWN,
PGPOST_FINGERUP,
PGPOST_KEYDOWN,
PGPOST_KEYMAPCHANGED,
PGPOST_KEYUP,
PGPOST_JOYAXISMOTION,
PGPOST_JOYBALLMOTION,
PGPOST_JOYHATMOTION,
PGPOST_JOYBUTTONDOWN,
PGPOST_JOYBUTTONUP,
PGPOST_JOYDEVICEADDED,
PGPOST_JOYDEVICEREMOVED,
PGPOST_LOCALECHANGED,
PGPOST_MIDIIN,
PGPOST_MIDIOUT,
PGPOST_MOUSEMOTION,
PGPOST_MOUSEBUTTONDOWN,
PGPOST_MOUSEBUTTONUP,
PGPOST_MOUSEWHEEL,
PGPOST_MULTIGESTURE,
PGPOST_NOEVENT,
PGPOST_QUIT,
PGPOST_RENDER_TARGETS_RESET,
PGPOST_RENDER_DEVICE_RESET,
PGPOST_SYSWMEVENT,
PGPOST_TEXTEDITING,
PGPOST_TEXTINPUT,
PGPOST_VIDEORESIZE,
PGPOST_VIDEOEXPOSE,
PGPOST_WINDOWSHOWN,
PGPOST_WINDOWHIDDEN,
PGPOST_WINDOWEXPOSED,
PGPOST_WINDOWMOVED,
PGPOST_WINDOWRESIZED,
PGPOST_WINDOWSIZECHANGED,
PGPOST_WINDOWMINIMIZED,
PGPOST_WINDOWMAXIMIZED,
PGPOST_WINDOWRESTORED,
PGPOST_WINDOWENTER,
PGPOST_WINDOWLEAVE,
PGPOST_WINDOWFOCUSGAINED,
PGPOST_WINDOWFOCUSLOST,
PGPOST_WINDOWCLOSE,
PGPOST_WINDOWTAKEFOCUS,
PGPOST_WINDOWHITTEST,
PGPOST_WINDOWICCPROFCHANGED,
PGPOST_WINDOWDISPLAYCHANGED,
PGE_USEREVENT, /* this event must stay in this position only */
PG_NUMEVENTS =
SDL_LASTEVENT /* Not an event. Indicates end of user events. */
} PygameEventCode;
/* SDL1 ACTIVEEVENT state attribute can take the following values */
/* These constant values are directly picked from SDL1 source */
#define SDL_APPMOUSEFOCUS 0x01
#define SDL_APPINPUTFOCUS 0x02
#define SDL_APPACTIVE 0x04
/* Surface flags: based on SDL 1.2 flags */
typedef enum {
PGS_SWSURFACE = 0x00000000,
PGS_HWSURFACE = 0x00000001,
PGS_ASYNCBLIT = 0x00000004,
PGS_ANYFORMAT = 0x10000000,
PGS_HWPALETTE = 0x20000000,
PGS_DOUBLEBUF = 0x40000000,
PGS_FULLSCREEN = 0x80000000,
PGS_SCALED = 0x00000200,
PGS_OPENGL = 0x00000002,
PGS_OPENGLBLIT = 0x0000000A,
PGS_RESIZABLE = 0x00000010,
PGS_NOFRAME = 0x00000020,
PGS_SHOWN = 0x00000040, /* Added from SDL 2 */
PGS_HIDDEN = 0x00000080, /* Added from SDL 2 */
PGS_HWACCEL = 0x00000100,
PGS_SRCCOLORKEY = 0x00001000,
PGS_RLEACCELOK = 0x00002000,
PGS_RLEACCEL = 0x00004000,
PGS_SRCALPHA = 0x00010000,
PGS_PREALLOC = 0x01000000
} PygameSurfaceFlags;
// TODO Implement check below in a way that does not break CI
/* New buffer protocol (PEP 3118) implemented on all supported Py versions.
#if !defined(Py_TPFLAGS_HAVE_NEWBUFFER)
#error No support for PEP 3118/Py_TPFLAGS_HAVE_NEWBUFFER. Please use a
supported Python version. #endif */
#define RAISE(x, y) (PyErr_SetString((x), (y)), NULL)
#define DEL_ATTR_NOT_SUPPORTED_CHECK(name, value) \
do { \
if (!value) { \
PyErr_Format(PyExc_AttributeError, "Cannot delete attribute %s", \
name); \
return -1; \
} \
} while (0)
#define DEL_ATTR_NOT_SUPPORTED_CHECK_NO_NAME(value) \
do { \
if (!value) { \
PyErr_SetString(PyExc_AttributeError, "Cannot delete attribute"); \
return -1; \
} \
} while (0)
/*
* Initialization checks
*/
#define VIDEO_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_VIDEO)) \
return RAISE(pgExc_SDLError, "video system not initialized")
#define JOYSTICK_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_JOYSTICK)) \
return RAISE(pgExc_SDLError, "joystick system not initialized")
/* thread check */
#ifdef WITH_THREAD
#define PG_CHECK_THREADS() (1)
#else /* ~WITH_THREAD */
#define PG_CHECK_THREADS() \
(RAISE(PyExc_NotImplementedError, "Python built without thread support"))
#endif /* ~WITH_THREAD */
#define PyType_Init(x) (((x).ob_type) = &PyType_Type)
/* CPython 3.6 had initial and undocumented FASTCALL support, but we play it
* safe by not relying on implementation details */
#if PY_VERSION_HEX < 0x03070000
/* Macro for naming a pygame fastcall wrapper function */
#define PG_FASTCALL_NAME(func) _##func##_fastcall_wrap
/* used to forward declare compat functions */
#define PG_DECLARE_FASTCALL_FUNC(func, self_type) \
static PyObject *PG_FASTCALL_NAME(func)(self_type * self, PyObject * args)
/* Using this macro on a function defined with the FASTCALL calling convention
* adds a wrapper definition that uses regular python VARARGS convention.
* Since it is guaranteed that the 'args' object is a tuple, we can directly
* call PySequence_Fast_ITEMS and PyTuple_GET_SIZE on it (which are macros that
* assume the same, and don't do error checking) */
#define PG_WRAP_FASTCALL_FUNC(func, self_type) \
PG_DECLARE_FASTCALL_FUNC(func, self_type) \
{ \
return func(self, (PyObject *const *)PySequence_Fast_ITEMS(args), \
PyTuple_GET_SIZE(args)); \
}
#define PG_FASTCALL METH_VARARGS
#else /* PY_VERSION_HEX >= 0x03070000 */
/* compat macros are no-op on python versions that support fastcall */
#define PG_FASTCALL_NAME(func) func
#define PG_DECLARE_FASTCALL_FUNC(func, self_type)
#define PG_WRAP_FASTCALL_FUNC(func, self_type)
#define PG_FASTCALL METH_FASTCALL
#endif /* PY_VERSION_HEX >= 0x03070000 */
/*
* event module internals
*/
struct pgEventObject {
PyObject_HEAD int type;
PyObject *dict;
};
/*
* surflock module internals
*/
typedef struct {
PyObject_HEAD PyObject *surface;
PyObject *lockobj;
PyObject *weakrefs;
} pgLifetimeLockObject;
/*
* surface module internals
*/
struct pgSubSurface_Data {
PyObject *owner;
int pixeloffset;
int offsetx, offsety;
};
/*
* color module internals
*/
struct pgColorObject {
PyObject_HEAD Uint8 data[4];
Uint8 len;
};
/*
* include public API
*/
#include "include/_pygame.h"
/* Slot counts.
* Remember to keep these constants up to date.
*/
#define PYGAMEAPI_RECT_NUMSLOTS 5
#define PYGAMEAPI_JOYSTICK_NUMSLOTS 2
#define PYGAMEAPI_DISPLAY_NUMSLOTS 2
#define PYGAMEAPI_SURFACE_NUMSLOTS 4
#define PYGAMEAPI_SURFLOCK_NUMSLOTS 8
#define PYGAMEAPI_RWOBJECT_NUMSLOTS 6
#define PYGAMEAPI_PIXELARRAY_NUMSLOTS 2
#define PYGAMEAPI_COLOR_NUMSLOTS 5
#define PYGAMEAPI_MATH_NUMSLOTS 2
#define PYGAMEAPI_BASE_NUMSLOTS 27
#define PYGAMEAPI_EVENT_NUMSLOTS 6
#endif /* _PYGAME_INTERNAL_H */
@@ -1,30 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef _SURFACE_H
#define _SURFACE_H
#include "_pygame.h"
#include "surface.h"
#endif
@@ -1,252 +0,0 @@
#ifndef CAMERA_H
#define CAMERA_H
/*
pygame - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "pygame.h"
#include "pgcompat.h"
#include "doc/camera_doc.h"
#if defined(__unix__)
#include <structmember.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
/* on freebsd there is no asm/types */
#ifdef linux
#include <asm/types.h> /* for videodev2.h */
#endif
#include <linux/videodev2.h>
#endif
#if defined(__WIN32__)
#define PYGAME_WINDOWS_CAMERA 1
#include <mfapi.h>
#include <mfobjects.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <combaseapi.h>
#include <mftransform.h>
#endif
/* some constants used which are not defined on non-v4l machines. */
#ifndef V4L2_PIX_FMT_RGB24
#define V4L2_PIX_FMT_RGB24 'RGB3'
#endif
#ifndef V4L2_PIX_FMT_RGB444
#define V4L2_PIX_FMT_RGB444 'R444'
#endif
#ifndef V4L2_PIX_FMT_YUYV
#define V4L2_PIX_FMT_YUYV 'YUYV'
#endif
#ifndef V4L2_PIX_FMT_XBGR32
#define V4L2_PIX_FMT_XBGR32 'XR24'
#endif
#define CLEAR(x) memset(&(x), 0, sizeof(x))
#define SAT(c) \
if (c & (~255)) { \
if (c < 0) \
c = 0; \
else \
c = 255; \
}
#define SAT2(c) ((c) & (~255) ? ((c) < 0 ? 0 : 255) : (c))
#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480
#define RGB_OUT 1
#define YUV_OUT 2
#define HSV_OUT 4
#define CAM_V4L \
1 /* deprecated. the incomplete support in pygame was removed */
#define CAM_V4L2 2
struct buffer {
void *start;
size_t length;
};
#if defined(__unix__)
typedef struct pgCameraObject {
PyObject_HEAD char *device_name;
int camera_type;
unsigned long pixelformat;
unsigned int color_out;
struct buffer *buffers;
unsigned int n_buffers;
int width;
int height;
int size;
int hflip;
int vflip;
int brightness;
int fd;
} pgCameraObject;
#elif defined(PYGAME_WINDOWS_CAMERA)
typedef struct pgCameraObject {
PyObject_HEAD WCHAR *device_name;
IMFSourceReader *reader;
IMFTransform *transform;
IMFVideoProcessorControl *control;
IMFMediaBuffer *buf;
IMFMediaBuffer *raw_buf;
int buffer_ready;
short open; /* used to signal the update_function to exit */
HANDLE t_handle;
HRESULT t_error;
int t_error_line;
int width;
int height;
int hflip;
int vflip;
int last_vflip;
int color_out;
unsigned long pixelformat;
} pgCameraObject;
#else
/* generic definition.
*/
typedef struct pgCameraObject {
PyObject_HEAD char *device_name;
int camera_type;
unsigned long pixelformat;
unsigned int color_out;
struct buffer *buffers;
unsigned int n_buffers;
int width;
int height;
int size;
int hflip;
int vflip;
int brightness;
int fd;
} pgCameraObject;
#endif
/* internal functions for colorspace conversion */
void
colorspace(SDL_Surface *src, SDL_Surface *dst, int cspace);
void
rgb24_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
bgr32_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
rgb444_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
rgb_to_yuv(const void *src, void *dst, int length, unsigned long source,
SDL_PixelFormat *format);
void
rgb_to_hsv(const void *src, void *dst, int length, unsigned long source,
SDL_PixelFormat *format);
void
yuyv_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
yuyv_to_yuv(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
uyvy_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
uyvy_to_yuv(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
sbggr8_to_rgb(const void *src, void *dst, int width, int height,
SDL_PixelFormat *format);
void
yuv420_to_rgb(const void *src, void *dst, int width, int height,
SDL_PixelFormat *format);
void
yuv420_to_yuv(const void *src, void *dst, int width, int height,
SDL_PixelFormat *format);
#if defined(__unix__)
/* internal functions specific to v4l2 */
char **
v4l2_list_cameras(int *num_devices);
int
v4l2_get_control(int fd, int id, int *value);
int
v4l2_set_control(int fd, int id, int value);
PyObject *
v4l2_read_raw(pgCameraObject *self);
int
v4l2_xioctl(int fd, int request, void *arg);
int
v4l2_process_image(pgCameraObject *self, const void *image, int buffer_size,
SDL_Surface *surf);
int
v4l2_query_buffer(pgCameraObject *self);
int
v4l2_read_frame(pgCameraObject *self, SDL_Surface *surf, int *errno_code);
int
v4l2_stop_capturing(pgCameraObject *self);
int
v4l2_start_capturing(pgCameraObject *self);
int
v4l2_uninit_device(pgCameraObject *self);
int
v4l2_init_mmap(pgCameraObject *self);
int
v4l2_init_device(pgCameraObject *self);
int
v4l2_close_device(pgCameraObject *self);
int
v4l2_open_device(pgCameraObject *self);
#elif defined(PYGAME_WINDOWS_CAMERA)
/* internal functions specific to WINDOWS */
WCHAR **
windows_list_cameras(int *num_devices);
int
windows_init_device(pgCameraObject *self);
int
windows_open_device(pgCameraObject *self);
IMFActivate *
windows_device_from_name(WCHAR *device_name);
int
windows_close_device(pgCameraObject *self);
int
windows_read_frame(pgCameraObject *self, SDL_Surface *surf);
int
windows_frame_ready(pgCameraObject *self, int *result);
PyObject *
windows_read_raw(pgCameraObject *self);
int
windows_process_image(pgCameraObject *self, BYTE *data, DWORD buffer_size,
SDL_Surface *surf);
void
windows_dealloc_device(pgCameraObject *self);
int
windows_init_device(pgCameraObject *self);
#endif
#endif /* !CAMERA_H */
@@ -1,15 +0,0 @@
#ifndef PGFONT_INTERNAL_H
#define PGFONT_INTERNAL_H
#include <SDL_ttf.h>
/* test font initialization */
#define FONT_INIT_CHECK() \
if (!(*(int *)PyFONT_C_API[2])) \
return RAISE(pgExc_SDLError, "font system not initialized")
#include "include/pygame_font.h"
#define PYGAMEAPI_FONT_NUMSLOTS 3
#endif /* ~PGFONT_INTERNAL_H */
@@ -1,114 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2009 Vicent Marti
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _PYGAME_FREETYPE_INTERNAL_H_
#define _PYGAME_FREETYPE_INTERNAL_H_
#include "pgcompat.h"
#include "pgplatform.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_CACHE_H
#include FT_XFREE86_H
#include FT_TRIGONOMETRY_H
/**********************************************************
* Global module constants
**********************************************************/
/* Render styles */
#define FT_STYLE_NORMAL 0x00
#define FT_STYLE_STRONG 0x01
#define FT_STYLE_OBLIQUE 0x02
#define FT_STYLE_UNDERLINE 0x04
#define FT_STYLE_WIDE 0x08
#define FT_STYLE_DEFAULT 0xFF
/* Bounding box modes */
#define FT_BBOX_EXACT FT_GLYPH_BBOX_SUBPIXELS
#define FT_BBOX_EXACT_GRIDFIT FT_GLYPH_BBOX_GRIDFIT
#define FT_BBOX_PIXEL FT_GLYPH_BBOX_TRUNCATE
#define FT_BBOX_PIXEL_GRIDFIT FT_GLYPH_BBOX_PIXELS
/* Rendering flags */
#define FT_RFLAG_NONE (0)
#define FT_RFLAG_ANTIALIAS (1 << 0)
#define FT_RFLAG_AUTOHINT (1 << 1)
#define FT_RFLAG_VERTICAL (1 << 2)
#define FT_RFLAG_HINTED (1 << 3)
#define FT_RFLAG_KERNING (1 << 4)
#define FT_RFLAG_TRANSFORM (1 << 5)
#define FT_RFLAG_PAD (1 << 6)
#define FT_RFLAG_ORIGIN (1 << 7)
#define FT_RFLAG_UCS4 (1 << 8)
#define FT_RFLAG_USE_BITMAP_STRIKES (1 << 9)
#define FT_RFLAG_DEFAULTS \
(FT_RFLAG_HINTED | FT_RFLAG_USE_BITMAP_STRIKES | FT_RFLAG_ANTIALIAS)
#define FT_RENDER_NEWBYTEARRAY 0x0
#define FT_RENDER_NEWSURFACE 0x1
#define FT_RENDER_EXISTINGSURFACE 0x2
/**********************************************************
* Global module types
**********************************************************/
typedef struct _scale_s {
FT_UInt x, y;
} Scale_t;
typedef FT_Angle Angle_t;
struct fontinternals_;
struct freetypeinstance_;
typedef struct {
FT_Long font_index;
FT_Open_Args open_args;
} pgFontId;
typedef struct {
PyObject_HEAD pgFontId id;
PyObject *path;
int is_scalable;
int is_bg_col_set;
Scale_t face_size;
FT_Int16 style;
FT_Int16 render_flags;
double strength;
double underline_adjustment;
FT_UInt resolution;
Angle_t rotation;
FT_Matrix transform;
FT_Byte fgcolor[4];
FT_Byte bgcolor[4];
struct freetypeinstance_ *freetype; /* Personal reference */
struct fontinternals_ *_internals;
} pgFontObject;
#define pgFont_IS_ALIVE(o) (((pgFontObject *)(o))->_internals != 0)
/* import public API */
#include "include/pygame_freetype.h"
#define PYGAMEAPI_FREETYPE_NUMSLOTS 2
#endif /* ~_PYGAME_FREETYPE_INTERNAL_H_ */
@@ -1,949 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef _PYGAME_H
#define _PYGAME_H
/** This header file includes all the definitions for the
** base pygame extensions. This header only requires
** Python includes (and SDL.h for functions that use SDL types).
** The reason for functions prototyped with #define's is
** to allow for maximum Python portability. It also uses
** Python as the runtime linker, which allows for late binding.
'' For more information on this style of development, read
** the Python docs on this subject.
** http://www.python.org/doc/current/ext/using-cobjects.html
**
** If using this to build your own derived extensions,
** you'll see that the functions available here are mainly
** used to help convert between python objects and SDL objects.
** Since this library doesn't add a lot of functionality to
** the SDL library, it doesn't need to offer a lot either.
**
** When initializing your extension module, you must manually
** import the modules you want to use. (this is the part about
** using python as the runtime linker). Each module has its
** own import_xxx() routine. You need to perform this import
** after you have initialized your own module, and before
** you call any routines from that module. Since every module
** in pygame does this, there are plenty of examples.
**
** The base module does include some useful conversion routines
** that you are free to use in your own extension.
**/
#include "pgplatform.h"
#include <Python.h>
/* version macros (defined since version 1.9.5) */
#define PG_MAJOR_VERSION 2
#define PG_MINOR_VERSION 5
#define PG_PATCH_VERSION 2
#define PG_VERSIONNUM(MAJOR, MINOR, PATCH) \
(1000 * (MAJOR) + 100 * (MINOR) + (PATCH))
#define PG_VERSION_ATLEAST(MAJOR, MINOR, PATCH) \
(PG_VERSIONNUM(PG_MAJOR_VERSION, PG_MINOR_VERSION, PG_PATCH_VERSION) >= \
PG_VERSIONNUM(MAJOR, MINOR, PATCH))
#include "pgcompat.h"
/* Flag indicating a pg_buffer; used for assertions within callbacks */
#ifndef NDEBUG
#define PyBUF_PYGAME 0x4000
#endif
#define PyBUF_HAS_FLAG(f, F) (((f) & (F)) == (F))
/* Array information exchange struct C type; inherits from Py_buffer
*
* Pygame uses its own Py_buffer derived C struct as an internal representation
* of an imported array buffer. The extended Py_buffer allows for a
* per-instance release callback,
*/
typedef void (*pybuffer_releaseproc)(Py_buffer *);
typedef struct pg_bufferinfo_s {
Py_buffer view;
PyObject *consumer; /* Input: Borrowed reference */
pybuffer_releaseproc release_buffer;
} pg_buffer;
#include "pgimport.h"
/*
* BASE module
*/
#ifndef PYGAMEAPI_BASE_INTERNAL
#define pgExc_SDLError ((PyObject *)PYGAMEAPI_GET_SLOT(base, 0))
#define pg_RegisterQuit \
(*(void (*)(void (*)(void)))PYGAMEAPI_GET_SLOT(base, 1))
/**
* \brief Convert number like object *obj* to C int and in *val*.
*
* \param obj The Python object to convert.
* \param val A pointer to the C integer to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
* \note This function will convert floats to integers.
*/
#define pg_IntFromObj \
(*(int (*)(PyObject *, int *))PYGAMEAPI_GET_SLOT(base, 2))
/**
* \brief Convert number like object at position *i* in sequence *obj*
* to C int and place in argument *val*.
*
* \param obj The Python object to convert.
* \param i The index of the object to convert.
* \param val A pointer to the C integer to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
* \note This function will convert floats to integers.
*/
#define pg_IntFromObjIndex \
(*(int (*)(PyObject *, int, int *))PYGAMEAPI_GET_SLOT(base, 3))
/**
* \brief Convert the two number like objects in length 2 sequence *obj* to C
* int and place in arguments *val1* and *val2*.
*
* \param obj The Python two element sequence object to convert.
* \param val A pointer to the C integer to store the result.
* \param val2 A pointer to the C integer to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
* \note This function will convert floats to integers.
*/
#define pg_TwoIntsFromObj \
(*(int (*)(PyObject *, int *, int *))PYGAMEAPI_GET_SLOT(base, 4))
/**
* \brief Convert number like object *obj* to C float and in *val*.
*
* \param obj The Python object to convert.
* \param val A pointer to the C float to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
*/
#define pg_FloatFromObj \
(*(int (*)(PyObject *, float *))PYGAMEAPI_GET_SLOT(base, 5))
/**
* \brief Convert number like object at position *i* in sequence *obj* to C
* float and place in argument *val*.
*
* \param obj The Python object to convert.
* \param i The index of the object to convert.
* \param val A pointer to the C float to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
*/
#define pg_FloatFromObjIndex \
(*(int (*)(PyObject *, int, float *))PYGAMEAPI_GET_SLOT(base, 6))
/**
* \brief Convert the two number like objects in length 2 sequence *obj* to C
* float and place in arguments *val1* and *val2*.
*
* \param obj The Python two element sequence object to convert.
* \param val A pointer to the C float to store the result.
* \param val2 A pointer to the C float to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
*/
#define pg_TwoFloatsFromObj \
(*(int (*)(PyObject *, float *, float *))PYGAMEAPI_GET_SLOT(base, 7))
/**
* \brief Convert number like object *obj* to C Uint32 and in *val*.
*
* \param obj The Python object to convert.
* \param val A pointer to the C int to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*/
#define pg_UintFromObj \
(*(int (*)(PyObject *, Uint32 *))PYGAMEAPI_GET_SLOT(base, 8))
/**
* \brief Convert number like object at position *i* in sequence *obj* to C
* Uint32 and place in argument *val*.
*
* \param obj The Python object to convert.
* \param i The index of the object to convert.
* \param val A pointer to the C int to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*/
#define pg_UintFromObjIndex \
(*(int (*)(PyObject *, int, Uint32 *))PYGAMEAPI_GET_SLOT(base, 9))
/**
* \brief Initialize all of the pygame modules.
* \returns 1 on success, 0 on failure with PyErr set.
*/
#define pg_mod_autoinit (*(int (*)(const char *))PYGAMEAPI_GET_SLOT(base, 10))
/**
* \brief Quit all of the pygame modules.
*/
#define pg_mod_autoquit (*(void (*)(const char *))PYGAMEAPI_GET_SLOT(base, 11))
/**
* \brief Convert the color represented by object *obj* into a red, green,
* blue, alpha length 4 C array *RGBA*.
*
* The object must be a length 3 or 4 sequence of numbers having values between
* 0 and 255 inclusive. For a length 3 sequence an alpha value of 255 is
* assumed.
*
* \param obj The Python object to convert.
* \param RGBA A pointer to the C array to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*/
#define pg_RGBAFromObj \
(*(int (*)(PyObject *, Uint8 *))PYGAMEAPI_GET_SLOT(base, 12))
/**
* \brief Given a Py_buffer, return a python dictionary representing the array
* interface.
*
* \param view_p A pointer to the Py_buffer to convert to a dictionary.
*
* \returns A Python dictionary representing the array interface of the object.
*/
#define pgBuffer_AsArrayInterface \
(*(PyObject * (*)(Py_buffer *)) PYGAMEAPI_GET_SLOT(base, 13))
/**
* \brief Given a Py_buffer, return a python capsule representing the array
* interface.
*
* \param view_p A pointer to the Py_buffer to convert to a capsule.
*
* \returns A Python capsule representing the array interface of the object.
*/
#define pgBuffer_AsArrayStruct \
(*(PyObject * (*)(Py_buffer *)) PYGAMEAPI_GET_SLOT(base, 14))
/**
* \brief Get a buffer object from a given Python object.
*
* \param obj The Python object to get the buffer from.
* \param pg_view_p A pointer to a pg_buffer struct to store the buffer in.
* \param flags The desired buffer access mode.
*
* \returns 0 on success, -1 on failure.
*
* \note This function attempts to get a buffer object from a given Python
* object. If the object supports the buffer protocol, it will be used to
* create the buffer. If not, it will try to get an array interface or
* dictionary representation of the object and use that to create the buffer.
* If none of these methods work, it will raise a ValueError.
*
*/
#define pgObject_GetBuffer \
(*(int (*)(PyObject *, pg_buffer *, int))PYGAMEAPI_GET_SLOT(base, 15))
/**
* \brief Release a pg_buffer object.
*
* \param pg_view_p The pg_buffer object to release.
*
* \note This function releases a pg_buffer object.
* \note some calls to this function expect this function to not clear
* previously set errors.
*/
#define pgBuffer_Release (*(void (*)(pg_buffer *))PYGAMEAPI_GET_SLOT(base, 16))
/**
* \brief Write the array interface dictionary buffer description *dict* into a
* Pygame buffer description struct *pg_view_p*.
*
* \param pg_view_p The Pygame buffer description struct to write into.
* \param dict The array interface dictionary to read from.
* \param flags The PyBUF flags describing the view type requested.
*
* \returns 0 on success, or -1 on failure.
*/
#define pgDict_AsBuffer \
(*(int (*)(pg_buffer *, PyObject *, int))PYGAMEAPI_GET_SLOT(base, 17))
#define pgExc_BufferError ((PyObject *)PYGAMEAPI_GET_SLOT(base, 18))
/**
* \brief Get the default SDL window created by a pygame.display.set_mode()
* call, or *NULL*.
*
* \return The default window, or *NULL* if no window has been created.
*/
#define pg_GetDefaultWindow \
(*(SDL_Window * (*)(void)) PYGAMEAPI_GET_SLOT(base, 19))
/**
* \brief Set the default SDL window created by a pygame.display.set_mode()
* call. The previous window, if any, is destroyed. Argument *win* may be
* *NULL*. This function is called by pygame.display.set_mode().
*
* \param win The new default window. May be NULL.
*/
#define pg_SetDefaultWindow \
(*(void (*)(SDL_Window *))PYGAMEAPI_GET_SLOT(base, 20))
/**
* \brief Return a borrowed reference to the Pygame default window display
* surface, or *NULL* if no default window is open.
*
* \return The default renderer, or *NULL* if no renderer has been created.
*/
#define pg_GetDefaultWindowSurface \
(*(pgSurfaceObject * (*)(void)) PYGAMEAPI_GET_SLOT(base, 21))
/**
* \brief Set the Pygame default window display surface. The previous
* surface, if any, is destroyed. Argument *screen* may be *NULL*. This
* function is called by pygame.display.set_mode().
*
* \param screen The new default window display surface. May be NULL.
*/
#define pg_SetDefaultWindowSurface \
(*(void (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(base, 22))
/**
* \returns NULL if the environment variable PYGAME_BLEND_ALPHA_SDL2 is not
* set, otherwise returns a pointer to the environment variable.
*/
#define pg_EnvShouldBlendAlphaSDL2 \
(*(char *(*)(void))PYGAMEAPI_GET_SLOT(base, 23))
/**
* \brief Convert number like object *obj* to C double and in *val*.
*
* \param obj The Python object to convert.
* \param val A pointer to the C double to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
*/
#define pg_DoubleFromObj \
(*(int (*)(PyObject *, double *))PYGAMEAPI_GET_SLOT(base, 24))
/**
* \brief Convert number like object at position *i* in sequence *obj* to C
* double and place in argument *val*.
*
* \param obj The Python object to convert.
* \param i The index of the object to convert.
* \param val A pointer to the C double to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*
* \note This function will clear any Python errors.
*/
#define pg_DoubleFromObjIndex \
(*(int (*)(PyObject *, int, double *))PYGAMEAPI_GET_SLOT(base, 25))
/**
* \brief Convert the two number like objects in length 2 sequence *obj* to C
* double and place in arguments *val1* and *val2*.
*
* \param obj The Python two element sequence object to convert.
* \param val A pointer to the C double to store the result.
* \param val2 A pointer to the C double to store the result.
* \returns 1 if the conversion was successful, 0 otherwise.
*/
#define pg_TwoDoublesFromObj \
(*(int (*)(PyObject *, double *, double *))PYGAMEAPI_GET_SLOT(base, 26))
#define import_pygame_base() IMPORT_PYGAME_MODULE(base)
#endif /* ~PYGAMEAPI_BASE_INTERNAL */
typedef struct {
/**
* \brief The SDL rect wrapped by this object.
*/
PyObject_HEAD SDL_Rect r;
/**
* \brief A list of weak references to this rect.
*/
PyObject *weakreflist;
} pgRectObject;
/**
* \brief Convert a pgRectObject to an SDL_Rect.
*
* \param obj A pgRectObject instance.
* \returns the SDL_Rect field of *obj*, a pgRect_Type instance.
*
* \note SDL_Rect pgRect_AsRect(PyObject *obj)
*/
#define pgRect_AsRect(x) (((pgRectObject *)x)->r)
#ifndef PYGAMEAPI_RECT_INTERNAL
/**
* \brief The Pygame rectangle object type pygame.Rect.
*/
#define pgRect_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(rect, 0))
/**
* \brief Check if *obj* is a `pygame.Rect` instance.
*
* \returns true if *obj* is a `pygame.Rect` instance
*/
#define pgRect_Check(obj) ((obj)->ob_type == &pgRect_Type)
/**
* \brief Create a new `pygame.Rect` instance.
*
* \param r A pointer to an SDL_Rect struct.
* \returns a new `pygame.Rect` object for the SDL_Rect *r*.
* Returns *NULL* on error.
*
* \note PyObject* pgRect_New(SDL_Rect *r)
*/
#define pgRect_New (*(PyObject * (*)(SDL_Rect *)) PYGAMEAPI_GET_SLOT(rect, 1))
/**
* \brief Create a new `pygame.Rect` instance from x, y, w, h.
*
* \param x The x coordinate of the rectangle.
* \param y The y coordinate of the rectangle.
* \param w The width of the rectangle.
* \param h The height of the rectangle.
* \returns a new `pygame.Rect` object. Returns *NULL* on error.
*
* \note PyObject* pgRect_New4(int x, int y, int w, int h)
*/
#define pgRect_New4 \
(*(PyObject * (*)(int, int, int, int)) PYGAMEAPI_GET_SLOT(rect, 2))
/**
* \brief Convert a Python object to a `pygame.Rect` instance.
*
* \param obj A Python object.
* A rectangle can be a length 4 sequence integers (x, y, w, h), or a length 2
* sequence of position (x, y) and size (w, h), or a length 1 tuple containing
* a rectangle representation, or have a method *rect* that returns a
* rectangle.
*
* \param temp A pointer to an SDL_Rect struct to store the result in.
* \returns a pointer to the SDL_Rect field of the `pygame.Rect` instance
* *obj*. Returns *NULL* on error.
*
* \note This function will clear any Python errors.
* \note SDL_Rect* pgRect_FromObject(PyObject *obj, SDL_Rect *temp)
*/
#define pgRect_FromObject \
(*(SDL_Rect * (*)(PyObject *, SDL_Rect *)) PYGAMEAPI_GET_SLOT(rect, 3))
/**
* \brief Normalize a `pygame.Rect` instance. A rect with a negative size
* (negative width and/or height) will be adjusted to have a positive size.
*
* \param rect A pointer to a `pygame.Rect` instance.
* \returns *rect* normalized with positive values only.
*
* \note void pgRect_Normalize(SDL_Rect *rect)
*/
#define pgRect_Normalize (*(void (*)(SDL_Rect *))PYGAMEAPI_GET_SLOT(rect, 4))
#define import_pygame_rect() IMPORT_PYGAME_MODULE(rect)
#endif /* ~PYGAMEAPI_RECT_INTERNAL */
/*
* JOYSTICK module
*/
typedef struct pgJoystickObject {
PyObject_HEAD int id;
SDL_Joystick *joy;
/* Joysticks form an intrusive linked list.
*
* Note that we don't maintain refcounts for these so they are weakrefs
* from the Python side.
*/
struct pgJoystickObject *next;
struct pgJoystickObject *prev;
} pgJoystickObject;
#define pgJoystick_AsID(x) (((pgJoystickObject *)x)->id)
#define pgJoystick_AsSDL(x) (((pgJoystickObject *)x)->joy)
#ifndef PYGAMEAPI_JOYSTICK_INTERNAL
#define pgJoystick_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(joystick, 0))
#define pgJoystick_Check(x) ((x)->ob_type == &pgJoystick_Type)
#define pgJoystick_New (*(PyObject * (*)(int)) PYGAMEAPI_GET_SLOT(joystick, 1))
#define import_pygame_joystick() IMPORT_PYGAME_MODULE(joystick)
#endif
/*
* DISPLAY module
*/
typedef struct {
Uint32 hw_available : 1;
Uint32 wm_available : 1;
Uint32 blit_hw : 1;
Uint32 blit_hw_CC : 1;
Uint32 blit_hw_A : 1;
Uint32 blit_sw : 1;
Uint32 blit_sw_CC : 1;
Uint32 blit_sw_A : 1;
Uint32 blit_fill : 1;
Uint32 video_mem;
SDL_PixelFormat *vfmt;
SDL_PixelFormat vfmt_data;
int current_w;
int current_h;
} pg_VideoInfo;
/**
* A pygame object that wraps an SDL_VideoInfo struct.
* The object returned by `pygame.display.Info()`
*/
typedef struct {
PyObject_HEAD pg_VideoInfo info;
} pgVidInfoObject;
/**
* \brief Convert a pgVidInfoObject to an SDL_VideoInfo.
*
* \note SDL_VideoInfo pgVidInfo_AsVidInfo(PyObject *obj)
*
* \returns the SDL_VideoInfo field of *obj*, a pgVidInfo_Type instance.
* \param obj A pgVidInfo_Type instance.
*
* \note Does not check that *obj* is not `NULL` or an `pgVidInfoObject`
* object.
*/
#define pgVidInfo_AsVidInfo(x) (((pgVidInfoObject *)x)->info)
#ifndef PYGAMEAPI_DISPLAY_INTERNAL
/**
* \brief The pgVidInfoObject object Python type.
* \note pgVideoInfo_Type is used for the `pygame.display.Info()` object.
*/
#define pgVidInfo_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(display, 0))
/**
* \brief Check if *obj* is a pgVidInfoObject.
*
* \returns true if *x* is a `pgVidInfo_Type` instance
* \note Will return false if *x* is a subclass of `pgVidInfo_Type`.
* \note This macro does not check that *x* is not ``NULL``.
* \note int pgVidInfo_Check(PyObject *x)
*/
#define pgVidInfo_Check(x) ((x)->ob_type == &pgVidInfo_Type)
/**
* \brief Create a new pgVidInfoObject.
*
* \param i A pointer to an SDL_VideoInfo struct.
* \returns a new `pgVidInfoObject` object for the SDL_VideoInfo *i*.
*
* \note PyObject* pgVidInfo_New(SDL_VideoInfo *i)
* \note On failure, raise a Python exception and return `NULL`.
*/
#define pgVidInfo_New \
(*(PyObject * (*)(pg_VideoInfo *)) PYGAMEAPI_GET_SLOT(display, 1))
#define import_pygame_display() IMPORT_PYGAME_MODULE(display)
#endif /* ~PYGAMEAPI_DISPLAY_INTERNAL */
/*
* SURFACE module
*/
struct pgSubSurface_Data;
struct SDL_Surface;
/**
* \brief A pygame object that wraps an SDL_Surface. A `pygame.Surface`
* instance.
*/
typedef struct {
PyObject_HEAD struct SDL_Surface *surf;
/**
* \brief If true, the surface will be freed when the python object is
* destroyed.
*/
int owner;
/**
* \brief The subsurface data for this surface (if a subsurface).
*/
struct pgSubSurface_Data *subsurface;
/**
* \brief A list of weak references to this surface.
*/
PyObject *weakreflist;
/**
* \brief A list of locks for this surface.
*/
PyObject *locklist;
/**
* \brief Usually a buffer object which the surface gets its data from.
*/
PyObject *dependency;
} pgSurfaceObject;
/**
* \brief Convert a `pygame.Surface` instance to an SDL_Surface.
*
* \param x A `pygame.Surface` instance.
* \returns the SDL_Surface field of *x*, a `pygame.Surface` instance.
*
* \note SDL_Surface* pgSurface_AsSurface(PyObject *x)
*/
#define pgSurface_AsSurface(x) (((pgSurfaceObject *)x)->surf)
#ifndef PYGAMEAPI_SURFACE_INTERNAL
/**
* \brief The `pygame.Surface` object Python type.
*/
#define pgSurface_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(surface, 0))
/**
* \brief Check if *x* is a `pygame.Surface` instance.
*
* \param x The object to check.
* \returns true if *x* is a `pygame.Surface` instance
*
* \note Will return false if *x* is a subclass of `pygame.Surface`.
* \note This macro does not check that *x* is not ``NULL``.
* \note int pgSurface_Check(PyObject *x)
*/
#define pgSurface_Check(x) \
(PyObject_IsInstance((x), (PyObject *)&pgSurface_Type))
/**
* \brief Create a new `pygame.Surface` instance.
*
* \param s The SDL surface to wrap in a python object.
* \param owner If true, the surface will be freed when the python object is
* destroyed. \returns A new new pygame surface instance for SDL surface *s*.
* Returns *NULL* on error.
*
* \note pgSurfaceObject* pgSurface_New2(SDL_Surface *s, int owner)
*/
#define pgSurface_New2 \
(*(pgSurfaceObject * (*)(SDL_Surface *, int)) \
PYGAMEAPI_GET_SLOT(surface, 1))
/**
* \brief Sets the SDL surface for a `pygame.Surface` instance.
*
* \param self The `pygame.Surface` instance to set the surface for.
* \param s The SDL surface to set.
* \param owner If true, the surface will be freed when the python object is
* destroyed. \returns 0 on success, -1 on failure.
*
* \note int pgSurface_SetSurface(pgSurfaceObject *self, SDL_Surface *s, int
* owner)
*/
#define pgSurface_SetSurface \
(*(int (*)(pgSurfaceObject *, SDL_Surface *, int))PYGAMEAPI_GET_SLOT( \
surface, 3))
/**
* \brief Blit one surface onto another.
*
* \param dstobj The destination surface.
* \param srcobj The source surface.
* \param dstrect The destination rectangle.
* \param srcrect The source rectangle.
* \param the_args The blit flags.
* \return 0 for success, -1 or -2 for error.
*
* \note Is accessible through the C api.
* \note int pgSurface_Blit(PyObject *dstobj, PyObject *srcobj, SDL_Rect
* *dstrect, SDL_Rect *srcrect, int the_args)
*/
#define pgSurface_Blit \
(*(int (*)(pgSurfaceObject *, pgSurfaceObject *, SDL_Rect *, SDL_Rect *, \
int))PYGAMEAPI_GET_SLOT(surface, 2))
#define import_pygame_surface() \
do { \
IMPORT_PYGAME_MODULE(surface); \
if (PyErr_Occurred() != NULL) \
break; \
IMPORT_PYGAME_MODULE(surflock); \
} while (0)
#define pgSurface_New(surface) pgSurface_New2((surface), 1)
#define pgSurface_NewNoOwn(surface) pgSurface_New2((surface), 0)
#endif /* ~PYGAMEAPI_SURFACE_INTERNAL */
/*
* SURFLOCK module
* auto imported/initialized by surface
*/
#ifndef PYGAMEAPI_SURFLOCK_INTERNAL
#define pgLifetimeLock_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(surflock, 0))
#define pgLifetimeLock_Check(x) ((x)->ob_type == &pgLifetimeLock_Type)
#define pgSurface_Prep(x) \
if ((x)->subsurface) \
(*(*(void (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 1)))(x)
#define pgSurface_Unprep(x) \
if ((x)->subsurface) \
(*(*(void (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 2)))(x)
#define pgSurface_Lock \
(*(int (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 3))
#define pgSurface_Unlock \
(*(int (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 4))
#define pgSurface_LockBy \
(*(int (*)(pgSurfaceObject *, PyObject *))PYGAMEAPI_GET_SLOT(surflock, 5))
#define pgSurface_UnlockBy \
(*(int (*)(pgSurfaceObject *, PyObject *))PYGAMEAPI_GET_SLOT(surflock, 6))
#define pgSurface_LockLifetime \
(*(PyObject * (*)(PyObject *, PyObject *)) PYGAMEAPI_GET_SLOT(surflock, 7))
#endif
/*
* EVENT module
*/
typedef struct pgEventObject pgEventObject;
#ifndef PYGAMEAPI_EVENT_INTERNAL
#define pgEvent_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(event, 0))
#define pgEvent_Check(x) ((x)->ob_type == &pgEvent_Type)
#define pgEvent_New \
(*(PyObject * (*)(SDL_Event *)) PYGAMEAPI_GET_SLOT(event, 1))
#define pgEvent_New2 \
(*(PyObject * (*)(int, PyObject *)) PYGAMEAPI_GET_SLOT(event, 2))
#define pgEvent_FillUserEvent \
(*(int (*)(pgEventObject *, SDL_Event *))PYGAMEAPI_GET_SLOT(event, 3))
#define pg_EnableKeyRepeat (*(int (*)(int, int))PYGAMEAPI_GET_SLOT(event, 4))
#define pg_GetKeyRepeat (*(void (*)(int *, int *))PYGAMEAPI_GET_SLOT(event, 5))
#define import_pygame_event() IMPORT_PYGAME_MODULE(event)
#endif
/*
* RWOBJECT module
* the rwobject are only needed for C side work, not accessible from python.
*/
#ifndef PYGAMEAPI_RWOBJECT_INTERNAL
#define pgRWops_FromObject \
(*(SDL_RWops * (*)(PyObject *, char **)) PYGAMEAPI_GET_SLOT(rwobject, 0))
#define pgRWops_IsFileObject \
(*(int (*)(SDL_RWops *))PYGAMEAPI_GET_SLOT(rwobject, 1))
#define pg_EncodeFilePath \
(*(PyObject * (*)(PyObject *, PyObject *)) PYGAMEAPI_GET_SLOT(rwobject, 2))
#define pg_EncodeString \
(*(PyObject * (*)(PyObject *, const char *, const char *, PyObject *)) \
PYGAMEAPI_GET_SLOT(rwobject, 3))
#define pgRWops_FromFileObject \
(*(SDL_RWops * (*)(PyObject *)) PYGAMEAPI_GET_SLOT(rwobject, 4))
#define pgRWops_ReleaseObject \
(*(int (*)(SDL_RWops *))PYGAMEAPI_GET_SLOT(rwobject, 5))
#define import_pygame_rwobject() IMPORT_PYGAME_MODULE(rwobject)
#endif
/*
* PixelArray module
*/
#ifndef PYGAMEAPI_PIXELARRAY_INTERNAL
#define PyPixelArray_Type ((PyTypeObject *)PYGAMEAPI_GET_SLOT(pixelarray, 0))
#define PyPixelArray_Check(x) ((x)->ob_type == &PyPixelArray_Type)
#define PyPixelArray_New (*(PyObject * (*)) PYGAMEAPI_GET_SLOT(pixelarray, 1))
#define import_pygame_pixelarray() IMPORT_PYGAME_MODULE(pixelarray)
#endif /* PYGAMEAPI_PIXELARRAY_INTERNAL */
/*
* Color module
*/
typedef struct pgColorObject pgColorObject;
#ifndef PYGAMEAPI_COLOR_INTERNAL
#define pgColor_Type (*(PyObject *)PYGAMEAPI_GET_SLOT(color, 0))
#define pgColor_Check(x) ((x)->ob_type == &pgColor_Type)
#define pgColor_New (*(PyObject * (*)(Uint8 *)) PYGAMEAPI_GET_SLOT(color, 1))
#define pgColor_NewLength \
(*(PyObject * (*)(Uint8 *, Uint8)) PYGAMEAPI_GET_SLOT(color, 3))
#define pg_RGBAFromColorObj \
(*(int (*)(PyObject *, Uint8 *))PYGAMEAPI_GET_SLOT(color, 2))
#define pg_RGBAFromFuzzyColorObj \
(*(int (*)(PyObject *, Uint8 *))PYGAMEAPI_GET_SLOT(color, 4))
#define pgColor_AsArray(x) (((pgColorObject *)x)->data)
#define pgColor_NumComponents(x) (((pgColorObject *)x)->len)
#define import_pygame_color() IMPORT_PYGAME_MODULE(color)
#endif /* PYGAMEAPI_COLOR_INTERNAL */
/*
* Math module
*/
#ifndef PYGAMEAPI_MATH_INTERNAL
#define pgVector2_Check(x) \
((x)->ob_type == (PyTypeObject *)PYGAMEAPI_GET_SLOT(math, 0))
#define pgVector3_Check(x) \
((x)->ob_type == (PyTypeObject *)PYGAMEAPI_GET_SLOT(math, 1))
/*
#define pgVector2_New \
(*(PyObject*(*)) \
PYGAMEAPI_GET_SLOT(PyGAME_C_API, 1))
*/
#define import_pygame_math() IMPORT_PYGAME_MODULE(math)
#endif /* PYGAMEAPI_MATH_INTERNAL */
#define IMPORT_PYGAME_MODULE _IMPORT_PYGAME_MODULE
/*
* base pygame API slots
* disable slots with NO_PYGAME_C_API
*/
#ifdef PYGAME_H
PYGAMEAPI_DEFINE_SLOTS(base);
PYGAMEAPI_DEFINE_SLOTS(rect);
PYGAMEAPI_DEFINE_SLOTS(cdrom);
PYGAMEAPI_DEFINE_SLOTS(joystick);
PYGAMEAPI_DEFINE_SLOTS(display);
PYGAMEAPI_DEFINE_SLOTS(surface);
PYGAMEAPI_DEFINE_SLOTS(surflock);
PYGAMEAPI_DEFINE_SLOTS(event);
PYGAMEAPI_DEFINE_SLOTS(rwobject);
PYGAMEAPI_DEFINE_SLOTS(pixelarray);
PYGAMEAPI_DEFINE_SLOTS(color);
PYGAMEAPI_DEFINE_SLOTS(math);
#else /* ~PYGAME_H */
PYGAMEAPI_EXTERN_SLOTS(base);
PYGAMEAPI_EXTERN_SLOTS(rect);
PYGAMEAPI_EXTERN_SLOTS(cdrom);
PYGAMEAPI_EXTERN_SLOTS(joystick);
PYGAMEAPI_EXTERN_SLOTS(display);
PYGAMEAPI_EXTERN_SLOTS(surface);
PYGAMEAPI_EXTERN_SLOTS(surflock);
PYGAMEAPI_EXTERN_SLOTS(event);
PYGAMEAPI_EXTERN_SLOTS(rwobject);
PYGAMEAPI_EXTERN_SLOTS(pixelarray);
PYGAMEAPI_EXTERN_SLOTS(color);
PYGAMEAPI_EXTERN_SLOTS(math);
#endif /* ~PYGAME_H */
#endif /* PYGAME_H */
/* Use the end of this file for other cross module inline utility
* functions There seems to be no good reason to stick to macro only
* functions in Python 3.
*/
static PG_INLINE PyObject *
pg_tuple_couple_from_values_int(int val1, int val2)
{
/* This function turns two input integers into a python tuple object.
* Currently, 5th November 2022, this is faster than using Py_BuildValue
* to do the same thing.
*/
PyObject *tup = PyTuple_New(2);
if (!tup) {
return NULL;
}
PyObject *tmp = PyLong_FromLong(val1);
if (!tmp) {
Py_DECREF(tup);
return NULL;
}
PyTuple_SET_ITEM(tup, 0, tmp);
tmp = PyLong_FromLong(val2);
if (!tmp) {
Py_DECREF(tup);
return NULL;
}
PyTuple_SET_ITEM(tup, 1, tmp);
return tup;
}
static PG_INLINE PyObject *
pg_tuple_triple_from_values_int(int val1, int val2, int val3)
{
/* This function turns three input integers into a python tuple object.
* Currently, 5th November 2022, this is faster than using Py_BuildValue
* to do the same thing.
*/
PyObject *tup = PyTuple_New(3);
if (!tup) {
return NULL;
}
PyObject *tmp = PyLong_FromLong(val1);
if (!tmp) {
Py_DECREF(tup);
return NULL;
}
PyTuple_SET_ITEM(tup, 0, tmp);
tmp = PyLong_FromLong(val2);
if (!tmp) {
Py_DECREF(tup);
return NULL;
}
PyTuple_SET_ITEM(tup, 1, tmp);
tmp = PyLong_FromLong(val3);
if (!tmp) {
Py_DECREF(tup);
return NULL;
}
PyTuple_SET_ITEM(tup, 2, tmp);
return tup;
}
@@ -1,171 +0,0 @@
/*
Bitmask 1.7 - A pixel-perfect collision detection library.
Copyright (C) 2002-2005 Ulf Ekstrom except for the bitcount
function which is copyright (C) Donald W. Gillies, 1992.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef BITMASK_H
#define BITMASK_H
#ifdef __cplusplus
extern "C" {
#endif
#include <limits.h>
/* Define INLINE for different compilers. If your compiler does not
support inlining then there might be a performance hit in
bitmask_overlap_area().
*/
#ifndef INLINE
#ifdef __GNUC__
#define INLINE inline
#else
#ifdef _MSC_VER
#define INLINE __inline
#else
#define INLINE
#endif
#endif
#endif
#define BITMASK_W unsigned long int
#define BITMASK_W_LEN (sizeof(BITMASK_W) * CHAR_BIT)
#define BITMASK_W_MASK (BITMASK_W_LEN - 1)
#define BITMASK_N(n) ((BITMASK_W)1 << (n))
typedef struct bitmask {
int w, h;
BITMASK_W bits[1];
} bitmask_t;
/* Creates a bitmask of width w and height h, where
w and h must both be greater than or equal to 0.
The mask is automatically cleared when created.
*/
bitmask_t *
bitmask_create(int w, int h);
/* Frees all the memory allocated by bitmask_create for m. */
void
bitmask_free(bitmask_t *m);
/* Create a copy of the given bitmask. */
bitmask_t *
bitmask_copy(bitmask_t *m);
/* Clears all bits in the mask */
void
bitmask_clear(bitmask_t *m);
/* Sets all bits in the mask */
void
bitmask_fill(bitmask_t *m);
/* Flips all bits in the mask */
void
bitmask_invert(bitmask_t *m);
/* Counts the bits in the mask */
unsigned int
bitmask_count(bitmask_t *m);
/* Returns nonzero if the bit at (x,y) is set. Coordinates start at
(0,0) */
static INLINE int
bitmask_getbit(const bitmask_t *m, int x, int y)
{
return (m->bits[x / BITMASK_W_LEN * m->h + y] &
BITMASK_N(x & BITMASK_W_MASK)) != 0;
}
/* Sets the bit at (x,y) */
static INLINE void
bitmask_setbit(bitmask_t *m, int x, int y)
{
m->bits[x / BITMASK_W_LEN * m->h + y] |= BITMASK_N(x & BITMASK_W_MASK);
}
/* Clears the bit at (x,y) */
static INLINE void
bitmask_clearbit(bitmask_t *m, int x, int y)
{
m->bits[x / BITMASK_W_LEN * m->h + y] &= ~BITMASK_N(x & BITMASK_W_MASK);
}
/* Returns nonzero if the masks overlap with the given offset.
The overlap tests uses the following offsets (which may be negative):
+----+----------..
|A | yoffset
| +-+----------..
+--|B
|xoffset
| |
: :
*/
int
bitmask_overlap(const bitmask_t *a, const bitmask_t *b, int xoffset,
int yoffset);
/* Like bitmask_overlap(), but will also give a point of intersection.
x and y are given in the coordinates of mask a, and are untouched
if there is no overlap. */
int
bitmask_overlap_pos(const bitmask_t *a, const bitmask_t *b, int xoffset,
int yoffset, int *x, int *y);
/* Returns the number of overlapping 'pixels' */
int
bitmask_overlap_area(const bitmask_t *a, const bitmask_t *b, int xoffset,
int yoffset);
/* Fills a mask with the overlap of two other masks. A bitwise AND. */
void
bitmask_overlap_mask(const bitmask_t *a, const bitmask_t *b, bitmask_t *c,
int xoffset, int yoffset);
/* Draws mask b onto mask a (bitwise OR). Can be used to compose large
(game background?) mask from several submasks, which may speed up
the testing. */
void
bitmask_draw(bitmask_t *a, const bitmask_t *b, int xoffset, int yoffset);
void
bitmask_erase(bitmask_t *a, const bitmask_t *b, int xoffset, int yoffset);
/* Return a new scaled bitmask, with dimensions w*h. The quality of the
scaling may not be perfect for all circumstances, but it should
be reasonable. If either w or h is 0 a clear 1x1 mask is returned. */
bitmask_t *
bitmask_scale(const bitmask_t *m, int w, int h);
/* Convolve b into a, drawing the output into o, shifted by offset. If offset
* is 0, then the (x,y) bit will be set if and only if
* bitmask_overlap(a, b, x - b->w - 1, y - b->h - 1) returns true.
*
* Modifies bits o[xoffset ... xoffset + a->w + b->w - 1)
* [yoffset ... yoffset + a->h + b->h - 1). */
void
bitmask_convolve(const bitmask_t *a, const bitmask_t *b, bitmask_t *o,
int xoffset, int yoffset);
#ifdef __cplusplus
} /* End of extern "C" { */
#endif
#endif
@@ -1,102 +0,0 @@
#if !defined(PGCOMPAT_H)
#define PGCOMPAT_H
#include <Python.h>
/* In CPython, Py_Exit finalises the python interpreter before calling C exit()
* This does not exist on PyPy, so use exit() directly here */
#ifdef PYPY_VERSION
#define PG_EXIT(n) exit(n)
#else
#define PG_EXIT(n) Py_Exit(n)
#endif
/* define common types where SDL is not included */
#ifndef SDL_VERSION_ATLEAST
#ifdef _MSC_VER
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
#else
#include <stdint.h>
#endif
typedef uint32_t Uint32;
typedef uint8_t Uint8;
#endif /* no SDL */
#if defined(SDL_VERSION_ATLEAST)
#ifndef SDL_WINDOW_VULKAN
#define SDL_WINDOW_VULKAN 0
#endif
#ifndef SDL_WINDOW_ALWAYS_ON_TOP
#define SDL_WINDOW_ALWAYS_ON_TOP 0
#endif
#ifndef SDL_WINDOW_SKIP_TASKBAR
#define SDL_WINDOW_SKIP_TASKBAR 0
#endif
#ifndef SDL_WINDOW_UTILITY
#define SDL_WINDOW_UTILITY 0
#endif
#ifndef SDL_WINDOW_TOOLTIP
#define SDL_WINDOW_TOOLTIP 0
#endif
#ifndef SDL_WINDOW_POPUP_MENU
#define SDL_WINDOW_POPUP_MENU 0
#endif
#ifndef SDL_WINDOW_INPUT_GRABBED
#define SDL_WINDOW_INPUT_GRABBED 0
#endif
#ifndef SDL_WINDOW_INPUT_FOCUS
#define SDL_WINDOW_INPUT_FOCUS 0
#endif
#ifndef SDL_WINDOW_MOUSE_FOCUS
#define SDL_WINDOW_MOUSE_FOCUS 0
#endif
#ifndef SDL_WINDOW_FOREIGN
#define SDL_WINDOW_FOREIGN 0
#endif
#ifndef SDL_WINDOW_ALLOW_HIGHDPI
#define SDL_WINDOW_ALLOW_HIGHDPI 0
#endif
#ifndef SDL_WINDOW_MOUSE_CAPTURE
#define SDL_WINDOW_MOUSE_CAPTURE 0
#endif
#ifndef SDL_WINDOW_ALWAYS_ON_TOP
#define SDL_WINDOW_ALWAYS_ON_TOP 0
#endif
#ifndef SDL_WINDOW_SKIP_TASKBAR
#define SDL_WINDOW_SKIP_TASKBAR 0
#endif
#ifndef SDL_WINDOW_UTILITY
#define SDL_WINDOW_UTILITY 0
#endif
#ifndef SDL_WINDOW_TOOLTIP
#define SDL_WINDOW_TOOLTIP 0
#endif
#ifndef SDL_WINDOW_POPUP_MENU
#define SDL_WINDOW_POPUP_MENU 0
#endif
#ifndef SDL_MOUSEWHEEL_FLIPPED
#define NO_SDL_MOUSEWHEEL_FLIPPED
#endif
#endif /* defined(SDL_VERSION_ATLEAST) */
#endif /* ~defined(PGCOMPAT_H) */
@@ -1,67 +0,0 @@
#ifndef PGIMPORT_H
#define PGIMPORT_H
/* Prefix when importing module */
#define IMPPREFIX "pygame."
#include "pgcompat.h"
#define PYGAMEAPI_LOCAL_ENTRY "_PYGAME_C_API"
#define PG_CAPSULE_NAME(m) (IMPPREFIX m "." PYGAMEAPI_LOCAL_ENTRY)
/*
* fill API slots defined by PYGAMEAPI_DEFINE_SLOTS/PYGAMEAPI_EXTERN_SLOTS
*/
#define _IMPORT_PYGAME_MODULE(module) \
{ \
PyObject *_mod_##module = PyImport_ImportModule(IMPPREFIX #module); \
\
if (_mod_##module != NULL) { \
PyObject *_c_api = \
PyObject_GetAttrString(_mod_##module, PYGAMEAPI_LOCAL_ENTRY); \
\
Py_DECREF(_mod_##module); \
if (_c_api != NULL && PyCapsule_CheckExact(_c_api)) { \
void **localptr = (void **)PyCapsule_GetPointer( \
_c_api, PG_CAPSULE_NAME(#module)); \
_PGSLOTS_##module = localptr; \
} \
Py_XDECREF(_c_api); \
} \
}
#define PYGAMEAPI_IS_IMPORTED(module) (_PGSLOTS_##module != NULL)
/*
* source file must include one of these in order to use _IMPORT_PYGAME_MODULE.
* this is set by import_pygame_*() functions.
* disable with NO_PYGAME_C_API
*/
#define PYGAMEAPI_DEFINE_SLOTS(module) void **_PGSLOTS_##module = NULL
#define PYGAMEAPI_EXTERN_SLOTS(module) extern void **_PGSLOTS_##module
#define PYGAMEAPI_GET_SLOT(module, index) _PGSLOTS_##module[(index)]
/*
* disabled API with NO_PYGAME_C_API; do nothing instead
*/
#ifdef NO_PYGAME_C_API
#undef PYGAMEAPI_DEFINE_SLOTS
#undef PYGAMEAPI_EXTERN_SLOTS
#define PYGAMEAPI_DEFINE_SLOTS(module)
#define PYGAMEAPI_EXTERN_SLOTS(module)
/* intentionally leave this defined to cause a compiler error *
#define PYGAMEAPI_GET_SLOT(api_root, index)
#undef PYGAMEAPI_GET_SLOT*/
#undef _IMPORT_PYGAME_MODULE
#define _IMPORT_PYGAME_MODULE(module)
#endif /* NO_PYGAME_C_API */
#define encapsulate_api(ptr, module) \
PyCapsule_New(ptr, PG_CAPSULE_NAME(module), NULL)
#endif /* ~PGIMPORT_H */
@@ -1,87 +0,0 @@
/* platform/compiler adjustments */
#ifndef PG_PLATFORM_H
#define PG_PLATFORM_H
#if defined(HAVE_SNPRINTF) /* defined in python.h (pyerrors.h) and SDL.h \
(SDL_config.h) */
#undef HAVE_SNPRINTF /* remove GCC redefine warning */
#endif /* HAVE_SNPRINTF */
#ifndef PG_INLINE
#if defined(__clang__)
#define PG_INLINE __inline__ __attribute__((__unused__))
#elif defined(__GNUC__)
#define PG_INLINE __inline__
#elif defined(_MSC_VER)
#define PG_INLINE __inline
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define PG_INLINE inline
#else
#define PG_INLINE
#endif
#endif /* ~PG_INLINE */
// Worth trying this on MSVC/win32 builds to see if provides any speed up
#ifndef PG_FORCEINLINE
#if defined(__clang__)
#define PG_FORCEINLINE __inline__ __attribute__((__unused__))
#elif defined(__GNUC__)
#define PG_FORCEINLINE __inline__
#elif defined(_MSC_VER)
#define PG_FORCEINLINE __forceinline
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define PG_FORCEINLINE inline
#else
#define PG_FORCEINLINE
#endif
#endif /* ~PG_FORCEINLINE */
/* This is unconditionally defined in Python.h */
#if defined(_POSIX_C_SOURCE)
#undef _POSIX_C_SOURCE
#endif
#if defined(HAVE_SNPRINTF)
#undef HAVE_SNPRINTF
#endif
/* SDL needs WIN32 */
#if !defined(WIN32) && \
(defined(MS_WIN32) || defined(_WIN32) || defined(__WIN32) || \
defined(__WIN32__) || defined(_WINDOWS))
#define WIN32
#endif
/* Commenting out SSE4_2 stuff because it does not do runtime detection.
#ifndef PG_TARGET_SSE4_2
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ == 4 &&
__GNUC_MINOR__ >= 9) || __GNUC__ >= 5 ))
//The old gcc 4.8 on centos used by manylinux1 does not seem to get sse4.2
intrinsics #define PG_FUNCTION_TARGET_SSE4_2 __attribute__((target("sse4.2")))
// No else; we define the fallback later
#endif
#endif
*/
/* ~PG_TARGET_SSE4_2 */
/*
#ifdef PG_FUNCTION_TARGET_SSE4_2
#if !defined(__SSE4_2__) && !defined(PG_COMPILE_SSE4_2)
#if defined(__x86_64__) || defined(__i386__)
#define PG_COMPILE_SSE4_2 1
#endif
#endif
#endif
*/
/* ~PG_TARGET_SSE4_2 */
/* Fallback definition of target attribute */
#ifndef PG_FUNCTION_TARGET_SSE4_2
#define PG_FUNCTION_TARGET_SSE4_2
#endif
#ifndef PG_COMPILE_SSE4_2
#define PG_COMPILE_SSE4_2 0
#endif
#endif /* ~PG_PLATFORM_H */
@@ -1,34 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* To allow the Pygame C api to be globally shared by all code within an
* extension module built from multiple C files, only include the pygame.h
* header within the top level C file, the one which calls the
* 'import_pygame_*' macros. All other C source files of the module should
* include _pygame.h instead.
*/
#ifndef PYGAME_H
#define PYGAME_H
#include "_pygame.h"
#endif
@@ -1,56 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* Bufferproxy module C api. */
#if !defined(PG_BUFPROXY_HEADER)
#define PG_BUFPROXY_HEADER
#include <Python.h>
typedef PyObject *(*_pgbufproxy_new_t)(PyObject *, getbufferproc);
typedef PyObject *(*_pgbufproxy_get_obj_t)(PyObject *);
typedef int (*_pgbufproxy_trip_t)(PyObject *);
#ifndef PYGAMEAPI_BUFPROXY_INTERNAL
#include "pgimport.h"
PYGAMEAPI_DEFINE_SLOTS(bufferproxy);
#define pgBufproxy_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(bufferproxy, 0))
#define pgBufproxy_Check(x) ((x)->ob_type == &pgBufproxy_Type)
#define pgBufproxy_New (*(_pgbufproxy_new_t)PYGAMEAPI_GET_SLOT(bufferproxy, 1))
#define pgBufproxy_GetParent \
(*(_pgbufproxy_get_obj_t)PYGAMEAPI_GET_SLOT(bufferproxy, 2))
#define pgBufproxy_Trip \
(*(_pgbufproxy_trip_t)PYGAMEAPI_GET_SLOT(bufferproxy, 3))
#define import_pygame_bufferproxy() _IMPORT_PYGAME_MODULE(bufferproxy)
#endif /* ~PYGAMEAPI_BUFPROXY_INTERNAL */
#endif /* ~defined(PG_BUFPROXY_HEADER) */
@@ -1,50 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#include <Python.h>
#include "pgplatform.h"
struct TTF_Font;
typedef struct {
PyObject_HEAD TTF_Font *font;
PyObject *weakreflist;
unsigned int ttf_init_generation;
} PyFontObject;
#define PyFont_AsFont(x) (((PyFontObject *)x)->font)
#ifndef PYGAMEAPI_FONT_INTERNAL
#include "pgimport.h"
PYGAMEAPI_DEFINE_SLOTS(font);
#define PyFont_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(font, 0))
#define PyFont_Check(x) ((x)->ob_type == &PyFont_Type)
#define PyFont_New (*(PyObject * (*)(TTF_Font *)) PYGAMEAPI_GET_SLOT(font, 1))
/*slot 2 taken by FONT_INIT_CHECK*/
#define import_pygame_font() _IMPORT_PYGAME_MODULE(font)
#endif
@@ -1,42 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2009 Vicent Marti
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PYGAME_FREETYPE_H_
#define PYGAME_FREETYPE_H_
#include "pgplatform.h"
#include "pgimport.h"
#include "pgcompat.h"
#ifndef PYGAME_FREETYPE_INTERNAL
PYGAMEAPI_DEFINE_SLOTS(_freetype);
#define pgFont_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(_freetype, 0))
#define pgFont_Check(x) ((x)->ob_type == &pgFont_Type)
#define pgFont_New \
(*(PyObject * (*)(const char *, long)) PYGAMEAPI_GET_SLOT(_freetype, 1))
#define import_pygame_freetype() _IMPORT_PYGAME_MODULE(_freetype)
#endif /* PYGAME_FREETYPE_INTERNAL */
#endif /* PYGAME_FREETYPE_H_ */
@@ -1,45 +0,0 @@
/*
pygame - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PGMASK_H
#define PGMASK_H
#include <Python.h>
#include "bitmask.h"
typedef struct {
PyObject_HEAD bitmask_t *mask;
void *bufdata;
} pgMaskObject;
#define pgMask_AsBitmap(x) (((pgMaskObject *)x)->mask)
#ifndef PYGAMEAPI_MASK_INTERNAL
#include "pgimport.h"
PYGAMEAPI_DEFINE_SLOTS(mask);
#define pgMask_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(mask, 0))
#define pgMask_Check(x) ((x)->ob_type == &pgMask_Type)
#define import_pygame_mask() _IMPORT_PYGAME_MODULE(mask)
#endif /* ~PYGAMEAPI_MASK_INTERNAL */
#endif /* ~PGMASK_H */
@@ -1,71 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef PGMIXER_H
#define PGMIXER_H
#include <Python.h>
#include <structmember.h>
#include "pgcompat.h"
struct Mix_Chunk;
typedef struct {
PyObject_HEAD Mix_Chunk *chunk;
Uint8 *mem;
PyObject *weakreflist;
} pgSoundObject;
typedef struct {
PyObject_HEAD int chan;
} pgChannelObject;
#define pgSound_AsChunk(x) (((pgSoundObject *)x)->chunk)
#define pgChannel_AsInt(x) (((pgChannelObject *)x)->chan)
#include "pgimport.h"
#ifndef PYGAMEAPI_MIXER_INTERNAL
PYGAMEAPI_DEFINE_SLOTS(mixer);
#define pgSound_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(mixer, 0))
#define pgSound_Check(x) ((x)->ob_type == &pgSound_Type)
#define pgSound_New \
(*(PyObject * (*)(Mix_Chunk *)) PYGAMEAPI_GET_SLOT(mixer, 1))
#define pgSound_Play \
(*(PyObject * (*)(PyObject *, PyObject *)) PYGAMEAPI_GET_SLOT(mixer, 2))
#define pgChannel_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(mixer, 3))
#define pgChannel_Check(x) ((x)->ob_type == &pgChannel_Type)
#define pgChannel_New (*(PyObject * (*)(int)) PYGAMEAPI_GET_SLOT(mixer, 4))
#define import_pygame_mixer() _IMPORT_PYGAME_MODULE(mixer)
#endif /* PYGAMEAPI_MIXER_INTERNAL */
#endif /* ~PGMIXER_H */
File diff suppressed because it is too large. Load diff
@@ -1,7 +0,0 @@
#ifndef PGMASK_INTERNAL_H
#define PGMASK_INTERNAL_H
#include "include/pygame_mask.h"
#define PYGAMEAPI_MASK_NUMSLOTS 1
#endif /* ~PGMASK_INTERNAL_H */
@@ -1,14 +0,0 @@
#ifndef MIXER_INTERNAL_H
#define MIXER_INTERNAL_H
#include <SDL_mixer.h>
/* test mixer initializations */
#define MIXER_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_AUDIO)) \
return RAISE(pgExc_SDLError, "mixer not initialized")
#define PYGAMEAPI_MIXER_NUMSLOTS 5
#include "include/pygame_mixer.h"
#endif /* ~MIXER_INTERNAL_H */
@@ -1,123 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef PALETTE_H
#define PALETTE_H
#include <SDL.h>
/* SDL 2 does not assign a default palette color scheme to a new 8 bit
* surface. Instead, the palette is set all white. This defines the SDL 1.2
* default palette.
*/
static const SDL_Color default_palette_colors[] = {
{0, 0, 0, 255}, {0, 0, 85, 255}, {0, 0, 170, 255},
{0, 0, 255, 255}, {0, 36, 0, 255}, {0, 36, 85, 255},
{0, 36, 170, 255}, {0, 36, 255, 255}, {0, 73, 0, 255},
{0, 73, 85, 255}, {0, 73, 170, 255}, {0, 73, 255, 255},
{0, 109, 0, 255}, {0, 109, 85, 255}, {0, 109, 170, 255},
{0, 109, 255, 255}, {0, 146, 0, 255}, {0, 146, 85, 255},
{0, 146, 170, 255}, {0, 146, 255, 255}, {0, 182, 0, 255},
{0, 182, 85, 255}, {0, 182, 170, 255}, {0, 182, 255, 255},
{0, 219, 0, 255}, {0, 219, 85, 255}, {0, 219, 170, 255},
{0, 219, 255, 255}, {0, 255, 0, 255}, {0, 255, 85, 255},
{0, 255, 170, 255}, {0, 255, 255, 255}, {85, 0, 0, 255},
{85, 0, 85, 255}, {85, 0, 170, 255}, {85, 0, 255, 255},
{85, 36, 0, 255}, {85, 36, 85, 255}, {85, 36, 170, 255},
{85, 36, 255, 255}, {85, 73, 0, 255}, {85, 73, 85, 255},
{85, 73, 170, 255}, {85, 73, 255, 255}, {85, 109, 0, 255},
{85, 109, 85, 255}, {85, 109, 170, 255}, {85, 109, 255, 255},
{85, 146, 0, 255}, {85, 146, 85, 255}, {85, 146, 170, 255},
{85, 146, 255, 255}, {85, 182, 0, 255}, {85, 182, 85, 255},
{85, 182, 170, 255}, {85, 182, 255, 255}, {85, 219, 0, 255},
{85, 219, 85, 255}, {85, 219, 170, 255}, {85, 219, 255, 255},
{85, 255, 0, 255}, {85, 255, 85, 255}, {85, 255, 170, 255},
{85, 255, 255, 255}, {170, 0, 0, 255}, {170, 0, 85, 255},
{170, 0, 170, 255}, {170, 0, 255, 255}, {170, 36, 0, 255},
{170, 36, 85, 255}, {170, 36, 170, 255}, {170, 36, 255, 255},
{170, 73, 0, 255}, {170, 73, 85, 255}, {170, 73, 170, 255},
{170, 73, 255, 255}, {170, 109, 0, 255}, {170, 109, 85, 255},
{170, 109, 170, 255}, {170, 109, 255, 255}, {170, 146, 0, 255},
{170, 146, 85, 255}, {170, 146, 170, 255}, {170, 146, 255, 255},
{170, 182, 0, 255}, {170, 182, 85, 255}, {170, 182, 170, 255},
{170, 182, 255, 255}, {170, 219, 0, 255}, {170, 219, 85, 255},
{170, 219, 170, 255}, {170, 219, 255, 255}, {170, 255, 0, 255},
{170, 255, 85, 255}, {170, 255, 170, 255}, {170, 255, 255, 255},
{255, 0, 0, 255}, {255, 0, 85, 255}, {255, 0, 170, 255},
{255, 0, 255, 255}, {255, 36, 0, 255}, {255, 36, 85, 255},
{255, 36, 170, 255}, {255, 36, 255, 255}, {255, 73, 0, 255},
{255, 73, 85, 255}, {255, 73, 170, 255}, {255, 73, 255, 255},
{255, 109, 0, 255}, {255, 109, 85, 255}, {255, 109, 170, 255},
{255, 109, 255, 255}, {255, 146, 0, 255}, {255, 146, 85, 255},
{255, 146, 170, 255}, {255, 146, 255, 255}, {255, 182, 0, 255},
{255, 182, 85, 255}, {255, 182, 170, 255}, {255, 182, 255, 255},
{255, 219, 0, 255}, {255, 219, 85, 255}, {255, 219, 170, 255},
{255, 219, 255, 255}, {255, 255, 0, 255}, {255, 255, 85, 255},
{255, 255, 170, 255}, {255, 255, 255, 255}, {0, 0, 0, 255},
{0, 0, 85, 255}, {0, 0, 170, 255}, {0, 0, 255, 255},
{0, 36, 0, 255}, {0, 36, 85, 255}, {0, 36, 170, 255},
{0, 36, 255, 255}, {0, 73, 0, 255}, {0, 73, 85, 255},
{0, 73, 170, 255}, {0, 73, 255, 255}, {0, 109, 0, 255},
{0, 109, 85, 255}, {0, 109, 170, 255}, {0, 109, 255, 255},
{0, 146, 0, 255}, {0, 146, 85, 255}, {0, 146, 170, 255},
{0, 146, 255, 255}, {0, 182, 0, 255}, {0, 182, 85, 255},
{0, 182, 170, 255}, {0, 182, 255, 255}, {0, 219, 0, 255},
{0, 219, 85, 255}, {0, 219, 170, 255}, {0, 219, 255, 255},
{0, 255, 0, 255}, {0, 255, 85, 255}, {0, 255, 170, 255},
{0, 255, 255, 255}, {85, 0, 0, 255}, {85, 0, 85, 255},
{85, 0, 170, 255}, {85, 0, 255, 255}, {85, 36, 0, 255},
{85, 36, 85, 255}, {85, 36, 170, 255}, {85, 36, 255, 255},
{85, 73, 0, 255}, {85, 73, 85, 255}, {85, 73, 170, 255},
{85, 73, 255, 255}, {85, 109, 0, 255}, {85, 109, 85, 255},
{85, 109, 170, 255}, {85, 109, 255, 255}, {85, 146, 0, 255},
{85, 146, 85, 255}, {85, 146, 170, 255}, {85, 146, 255, 255},
{85, 182, 0, 255}, {85, 182, 85, 255}, {85, 182, 170, 255},
{85, 182, 255, 255}, {85, 219, 0, 255}, {85, 219, 85, 255},
{85, 219, 170, 255}, {85, 219, 255, 255}, {85, 255, 0, 255},
{85, 255, 85, 255}, {85, 255, 170, 255}, {85, 255, 255, 255},
{170, 0, 0, 255}, {170, 0, 85, 255}, {170, 0, 170, 255},
{170, 0, 255, 255}, {170, 36, 0, 255}, {170, 36, 85, 255},
{170, 36, 170, 255}, {170, 36, 255, 255}, {170, 73, 0, 255},
{170, 73, 85, 255}, {170, 73, 170, 255}, {170, 73, 255, 255},
{170, 109, 0, 255}, {170, 109, 85, 255}, {170, 109, 170, 255},
{170, 109, 255, 255}, {170, 146, 0, 255}, {170, 146, 85, 255},
{170, 146, 170, 255}, {170, 146, 255, 255}, {170, 182, 0, 255},
{170, 182, 85, 255}, {170, 182, 170, 255}, {170, 182, 255, 255},
{170, 219, 0, 255}, {170, 219, 85, 255}, {170, 219, 170, 255},
{170, 219, 255, 255}, {170, 255, 0, 255}, {170, 255, 85, 255},
{170, 255, 170, 255}, {170, 255, 255, 255}, {255, 0, 0, 255},
{255, 0, 85, 255}, {255, 0, 170, 255}, {255, 0, 255, 255},
{255, 36, 0, 255}, {255, 36, 85, 255}, {255, 36, 170, 255},
{255, 36, 255, 255}, {255, 73, 0, 255}, {255, 73, 85, 255},
{255, 73, 170, 255}, {255, 73, 255, 255}, {255, 109, 0, 255},
{255, 109, 85, 255}, {255, 109, 170, 255}, {255, 109, 255, 255},
{255, 146, 0, 255}, {255, 146, 85, 255}, {255, 146, 170, 255},
{255, 146, 255, 255}, {255, 182, 0, 255}, {255, 182, 85, 255},
{255, 182, 170, 255}, {255, 182, 255, 255}, {255, 219, 0, 255},
{255, 219, 85, 255}, {255, 219, 170, 255}, {255, 219, 255, 255},
{255, 255, 0, 255}, {255, 255, 85, 255}, {255, 255, 170, 255},
{255, 255, 255, 255}};
static const int default_palette_size =
(int)(sizeof(default_palette_colors) / sizeof(SDL_Color));
#endif
@@ -1,26 +0,0 @@
/* array structure interface version 3 declarations */
#if !defined(PG_ARRAYINTER_HEADER)
#define PG_ARRAYINTER_HEADER
static const int PAI_CONTIGUOUS = 0x01;
static const int PAI_FORTRAN = 0x02;
static const int PAI_ALIGNED = 0x100;
static const int PAI_NOTSWAPPED = 0x200;
static const int PAI_WRITEABLE = 0x400;
static const int PAI_ARR_HAS_DESCR = 0x800;
typedef struct {
int two; /* contains the integer 2 -- simple sanity check */
int nd; /* number of dimensions */
char typekind; /* kind in array -- character code of typestr */
int itemsize; /* size of each element */
int flags; /* flags indicating how the data should be */
/* interpreted */
Py_intptr_t *shape; /* A length-nd array of shape information */
Py_intptr_t *strides; /* A length-nd array of stride information */
void *data; /* A pointer to the first element of the array */
PyObject *descr; /* NULL or a data-description */
} PyArrayInterface;
#endif
@@ -1,7 +0,0 @@
#ifndef PG_BUFPROXY_INTERNAL_H
#define PG_BUFPROXY_INTERNAL_H
#include "include/pygame_bufferproxy.h"
#define PYGAMEAPI_BUFPROXY_NUMSLOTS 4
#endif /* ~PG_BUFPROXY_INTERNAL_H */
@@ -1,27 +0,0 @@
/* Python 2.x/3.x compatibility tools (internal)
*/
#ifndef PGCOMPAT_INTERNAL_H
#define PGCOMPAT_INTERNAL_H
#include "include/pgcompat.h"
/* Module init function returns new module instance. */
#define MODINIT_DEFINE(mod_name) PyMODINIT_FUNC PyInit_##mod_name(void)
/* Defaults for unicode file path encoding */
#if defined(MS_WIN32)
#define UNICODE_DEF_FS_ERROR "replace"
#else
#define UNICODE_DEF_FS_ERROR "surrogateescape"
#endif
#define RELATIVE_MODULE(m) ("." m)
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#define Slice_GET_INDICES_EX(slice, length, start, stop, step, slicelength) \
PySlice_GetIndicesEx(slice, length, start, stop, step, slicelength)
#endif /* ~PGCOMPAT_INTERNAL_H */
@@ -1,20 +0,0 @@
#if !defined(PGOPENGL_H)
#define PGOPENGL_H
/** This header includes definitions of Opengl functions as pointer types for
** use with the SDL function SDL_GL_GetProcAddress.
**/
#if defined(_WIN32)
#define GL_APIENTRY __stdcall
#else
#define GL_APIENTRY
#endif
typedef void(GL_APIENTRY *GL_glReadPixels_Func)(int, int, int, int,
unsigned int, unsigned int,
void *);
typedef void(GL_APIENTRY *GL_glViewport_Func)(int, int, unsigned int,
unsigned int);
#endif
@@ -1,23 +0,0 @@
/* platform/compiler adjustments (internal) */
#ifndef PG_PLATFORM_INTERNAL_H
#define PG_PLATFORM_INTERNAL_H
#include "include/pgplatform.h"
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef ABS
#define ABS(a) (((a) < 0) ? -(a) : (a))
#endif
/* warnings */
#define PG_STRINGIZE_HELPER(x) #x
#define PG_STRINGIZE(x) PG_STRINGIZE_HELPER(x)
#define PG_WARN(desc) \
message(__FILE__ "(" PG_STRINGIZE(__LINE__) "): WARNING: " #desc)
#endif /* ~PG_PLATFORM_INTERNAL_H */
@@ -1,32 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* This will use PYGAMEAPI_DEFINE_SLOTS instead
* of PYGAMEAPI_EXTERN_SLOTS for base modules.
*/
#ifndef PYGAME_INTERNAL_H
#define PYGAME_INTERNAL_H
#define PYGAME_H
#include "_pygame.h"
#endif /* ~PYGAME_INTERNAL_H */
@@ -1,147 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef SCRAP_H
#define SCRAP_H
/* This is unconditionally defined in Python.h */
#if defined(_POSIX_C_SOURCE)
#undef _POSIX_C_SOURCE
#endif
#include <Python.h>
/* Handle clipboard text and data in arbitrary formats */
/**
* Predefined supported pygame scrap types.
*/
#define PYGAME_SCRAP_TEXT "text/plain"
#define PYGAME_SCRAP_BMP "image/bmp"
#define PYGAME_SCRAP_PPM "image/ppm"
#define PYGAME_SCRAP_PBM "image/pbm"
/**
* The supported scrap clipboard types.
*
* This is only relevant in a X11 environment, which supports mouse
* selections as well. For Win32 and MacOS environments the default
* clipboard is used, no matter what value is passed.
*/
typedef enum {
SCRAP_CLIPBOARD,
SCRAP_SELECTION /* only supported in X11 environments. */
} ScrapClipType;
/**
* Macro for initialization checks.
*/
#define PYGAME_SCRAP_INIT_CHECK() \
if (!pygame_scrap_initialized()) \
return (PyErr_SetString(pgExc_SDLError, "scrap system not initialized."), \
NULL)
/**
* \brief Checks, whether the pygame scrap module was initialized.
*
* \return 1 if the modules was initialized, 0 otherwise.
*/
extern int
pygame_scrap_initialized(void);
/**
* \brief Initializes the pygame scrap module internals. Call this before any
* other method.
*
* \return 1 on successful initialization, 0 otherwise.
*/
extern int
pygame_scrap_init(void);
/**
* \brief Checks, whether the pygame window lost the clipboard focus or not.
*
* \return 1 if the window lost the focus, 0 otherwise.
*/
extern int
pygame_scrap_lost(void);
/**
* \brief Places content of a specific type into the clipboard.
*
* \note For X11 the following notes are important: The following types
* are reserved for internal usage and thus will throw an error on
* setting them: "TIMESTAMP", "TARGETS", "SDL_SELECTION".
* Setting PYGAME_SCRAP_TEXT ("text/plain") will also automatically
* set the X11 types "STRING" (XA_STRING), "TEXT" and "UTF8_STRING".
*
* For Win32 the following notes are important: Setting
* PYGAME_SCRAP_TEXT ("text/plain") will also automatically set
* the Win32 type "TEXT" (CF_TEXT).
*
* For QNX the following notes are important: Setting
* PYGAME_SCRAP_TEXT ("text/plain") will also automatically set
* the QNX type "TEXT" (Ph_CL_TEXT).
*
* \param type The type of the content.
* \param srclen The length of the content.
* \param src The NULL terminated content.
* \return 1, if the content could be successfully pasted into the clipboard,
* 0 otherwise.
*/
extern int
pygame_scrap_put(char *type, Py_ssize_t srclen, char *src);
/**
* \brief Gets the current content from the clipboard.
*
* \note The received content does not need to be the content previously
* placed in the clipboard using pygame_put_scrap(). See the
* pygame_put_scrap() notes for more details.
*
* \param type The type of the content to receive.
* \param count The size of the returned content.
* \return The content or NULL in case of an error or if no content of the
* specified type was available.
*/
extern char *
pygame_scrap_get(char *type, size_t *count);
/**
* \brief Gets the currently available content types from the clipboard.
*
* \return The different available content types or NULL in case of an
* error or if no content type is available.
*/
extern char **
pygame_scrap_get_types(void);
/**
* \brief Checks whether content for the specified scrap type is currently
* available in the clipboard.
*
* \param type The type to check for.
* \return 1, if there is content and 0 otherwise.
*/
extern int
pygame_scrap_contains(char *type);
#endif /* SCRAP_H */
@@ -1,84 +0,0 @@
#define NO_PYGAME_C_API
#include "_surface.h"
#include "_blit_info.h"
#if !defined(PG_ENABLE_ARM_NEON) && defined(__aarch64__)
// arm64 has neon optimisations enabled by default, even when fpu=neon is not
// passed
#define PG_ENABLE_ARM_NEON 1
#endif
int
pg_sse2_at_runtime_but_uncompiled();
int
pg_neon_at_runtime_but_uncompiled();
int
pg_avx2_at_runtime_but_uncompiled();
#if (defined(__SSE2__) || defined(PG_ENABLE_ARM_NEON))
void
alphablit_alpha_sse2_argb_surf_alpha(SDL_BlitInfo *info);
void
alphablit_alpha_sse2_argb_no_surf_alpha(SDL_BlitInfo *info);
void
alphablit_alpha_sse2_argb_no_surf_alpha_opaque_dst(SDL_BlitInfo *info);
void
blit_blend_rgba_mul_sse2(SDL_BlitInfo *info);
void
blit_blend_rgb_mul_sse2(SDL_BlitInfo *info);
void
blit_blend_rgba_add_sse2(SDL_BlitInfo *info);
void
blit_blend_rgb_add_sse2(SDL_BlitInfo *info);
void
blit_blend_rgba_sub_sse2(SDL_BlitInfo *info);
void
blit_blend_rgb_sub_sse2(SDL_BlitInfo *info);
void
blit_blend_rgba_max_sse2(SDL_BlitInfo *info);
void
blit_blend_rgb_max_sse2(SDL_BlitInfo *info);
void
blit_blend_rgba_min_sse2(SDL_BlitInfo *info);
void
blit_blend_rgb_min_sse2(SDL_BlitInfo *info);
void
blit_blend_premultiplied_sse2(SDL_BlitInfo *info);
#endif /* (defined(__SSE2__) || defined(PG_ENABLE_ARM_NEON)) */
/* Deliberately putting these outside of the preprocessor guards as I want to
move to a system of trusting the runtime checks to head to the right
function and having a fallback function there if pygame is not compiled
with the right stuff (this is the strategy used for AVX2 right now.
Potentially I might want to shift both these into a slightly different
file as they are not exactly blits (though v. similar) - or I could rename
the SIMD trilogy of files to replace the word blit with something more
generic like surface_ops*/
void
premul_surf_color_by_alpha_non_simd(SDL_Surface *src, SDL_Surface *dst);
void
premul_surf_color_by_alpha_sse2(SDL_Surface *src, SDL_Surface *dst);
int
pg_has_avx2();
void
blit_blend_rgba_mul_avx2(SDL_BlitInfo *info);
void
blit_blend_rgb_mul_avx2(SDL_BlitInfo *info);
void
blit_blend_rgba_add_avx2(SDL_BlitInfo *info);
void
blit_blend_rgb_add_avx2(SDL_BlitInfo *info);
void
blit_blend_rgba_sub_avx2(SDL_BlitInfo *info);
void
blit_blend_rgb_sub_avx2(SDL_BlitInfo *info);
void
blit_blend_rgba_max_avx2(SDL_BlitInfo *info);
void
blit_blend_rgb_max_avx2(SDL_BlitInfo *info);
void
blit_blend_rgba_min_avx2(SDL_BlitInfo *info);
void
blit_blend_rgb_min_avx2(SDL_BlitInfo *info);
@@ -1,361 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef SURFACE_H
#define SURFACE_H
/* This is defined in SDL.h */
#if defined(_POSIX_C_SOURCE)
#undef _POSIX_C_SOURCE
#endif
#include <SDL.h>
#include "pygame.h"
/* Blend modes */
#define PYGAME_BLEND_ADD 0x1
#define PYGAME_BLEND_SUB 0x2
#define PYGAME_BLEND_MULT 0x3
#define PYGAME_BLEND_MIN 0x4
#define PYGAME_BLEND_MAX 0x5
#define PYGAME_BLEND_RGB_ADD 0x1
#define PYGAME_BLEND_RGB_SUB 0x2
#define PYGAME_BLEND_RGB_MULT 0x3
#define PYGAME_BLEND_RGB_MIN 0x4
#define PYGAME_BLEND_RGB_MAX 0x5
#define PYGAME_BLEND_RGBA_ADD 0x6
#define PYGAME_BLEND_RGBA_SUB 0x7
#define PYGAME_BLEND_RGBA_MULT 0x8
#define PYGAME_BLEND_RGBA_MIN 0x9
#define PYGAME_BLEND_RGBA_MAX 0x10
#define PYGAME_BLEND_PREMULTIPLIED 0x11
#define PYGAME_BLEND_ALPHA_SDL2 0x12
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define GET_PIXEL_24(b) (b[0] + (b[1] << 8) + (b[2] << 16))
#else
#define GET_PIXEL_24(b) (b[2] + (b[1] << 8) + (b[0] << 16))
#endif
#define GET_PIXEL(pxl, bpp, source) \
switch (bpp) { \
case 2: \
pxl = *((Uint16 *)(source)); \
break; \
case 4: \
pxl = *((Uint32 *)(source)); \
break; \
default: { \
Uint8 *b = (Uint8 *)source; \
pxl = GET_PIXEL_24(b); \
} break; \
}
#define GET_PIXELVALS(_sR, _sG, _sB, _sA, px, fmt, ppa) \
SDL_GetRGBA(px, fmt, &(_sR), &(_sG), &(_sB), &(_sA)); \
if (!ppa) { \
_sA = 255; \
}
#define GET_PIXELVALS_1(sr, sg, sb, sa, _src, _fmt) \
sr = _fmt->palette->colors[*((Uint8 *)(_src))].r; \
sg = _fmt->palette->colors[*((Uint8 *)(_src))].g; \
sb = _fmt->palette->colors[*((Uint8 *)(_src))].b; \
sa = 255;
/* For 1 byte palette pixels */
#define SET_PIXELVAL(px, fmt, _dR, _dG, _dB, _dA) \
*(px) = (Uint8)SDL_MapRGBA(fmt, _dR, _dG, _dB, _dA)
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define SET_OFFSETS_24(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 0 : fmt->Rshift == 8 ? 1 : 2); \
og = (fmt->Gshift == 0 ? 0 : fmt->Gshift == 8 ? 1 : 2); \
ob = (fmt->Bshift == 0 ? 0 : fmt->Bshift == 8 ? 1 : 2); \
}
#define SET_OFFSETS_32(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 0 \
: fmt->Rshift == 8 ? 1 \
: fmt->Rshift == 16 ? 2 \
: 3); \
og = (fmt->Gshift == 0 ? 0 \
: fmt->Gshift == 8 ? 1 \
: fmt->Gshift == 16 ? 2 \
: 3); \
ob = (fmt->Bshift == 0 ? 0 \
: fmt->Bshift == 8 ? 1 \
: fmt->Bshift == 16 ? 2 \
: 3); \
}
#else
#define SET_OFFSETS_24(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 2 : fmt->Rshift == 8 ? 1 : 0); \
og = (fmt->Gshift == 0 ? 2 : fmt->Gshift == 8 ? 1 : 0); \
ob = (fmt->Bshift == 0 ? 2 : fmt->Bshift == 8 ? 1 : 0); \
}
#define SET_OFFSETS_32(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 3 \
: fmt->Rshift == 8 ? 2 \
: fmt->Rshift == 16 ? 1 \
: 0); \
og = (fmt->Gshift == 0 ? 3 \
: fmt->Gshift == 8 ? 2 \
: fmt->Gshift == 16 ? 1 \
: 0); \
ob = (fmt->Bshift == 0 ? 3 \
: fmt->Bshift == 8 ? 2 \
: fmt->Bshift == 16 ? 1 \
: 0); \
}
#endif
#define CREATE_PIXEL(buf, r, g, b, a, bp, ft) \
switch (bp) { \
case 2: \
*((Uint16 *)(buf)) = ((r >> ft->Rloss) << ft->Rshift) | \
((g >> ft->Gloss) << ft->Gshift) | \
((b >> ft->Bloss) << ft->Bshift) | \
((a >> ft->Aloss) << ft->Ashift); \
break; \
case 4: \
*((Uint32 *)(buf)) = ((r >> ft->Rloss) << ft->Rshift) | \
((g >> ft->Gloss) << ft->Gshift) | \
((b >> ft->Bloss) << ft->Bshift) | \
((a >> ft->Aloss) << ft->Ashift); \
break; \
}
/* Pretty good idea from Tom Duff :-). */
#define LOOP_UNROLLED4(code, n, width) \
n = (width + 3) / 4; \
switch (width & 3) { \
case 0: \
do { \
code; \
case 3: \
code; \
case 2: \
code; \
case 1: \
code; \
} while (--n > 0); \
}
/* Used in the srcbpp == dstbpp == 1 blend functions */
#define REPEAT_3(code) \
code; \
code; \
code;
#define REPEAT_4(code) \
code; \
code; \
code; \
code;
#define BLEND_ADD(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR + sR; \
dR = (tmp <= 255 ? tmp : 255); \
tmp = dG + sG; \
dG = (tmp <= 255 ? tmp : 255); \
tmp = dB + sB; \
dB = (tmp <= 255 ? tmp : 255);
#define BLEND_SUB(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR - sR; \
dR = (tmp >= 0 ? tmp : 0); \
tmp = dG - sG; \
dG = (tmp >= 0 ? tmp : 0); \
tmp = dB - sB; \
dB = (tmp >= 0 ? tmp : 0);
#define BLEND_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \
dR = (dR && sR) ? ((dR * sR) + 255) >> 8 : 0; \
dG = (dG && sG) ? ((dG * sG) + 255) >> 8 : 0; \
dB = (dB && sB) ? ((dB * sB) + 255) >> 8 : 0;
#define BLEND_MIN(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR < dR) { \
dR = sR; \
} \
if (sG < dG) { \
dG = sG; \
} \
if (sB < dB) { \
dB = sB; \
}
#define BLEND_MAX(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR > dR) { \
dR = sR; \
} \
if (sG > dG) { \
dG = sG; \
} \
if (sB > dB) { \
dB = sB; \
}
#define BLEND_RGBA_ADD(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR + sR; \
dR = (tmp <= 255 ? tmp : 255); \
tmp = dG + sG; \
dG = (tmp <= 255 ? tmp : 255); \
tmp = dB + sB; \
dB = (tmp <= 255 ? tmp : 255); \
tmp = dA + sA; \
dA = (tmp <= 255 ? tmp : 255);
#define BLEND_RGBA_SUB(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR - sR; \
dR = (tmp >= 0 ? tmp : 0); \
tmp = dG - sG; \
dG = (tmp >= 0 ? tmp : 0); \
tmp = dB - sB; \
dB = (tmp >= 0 ? tmp : 0); \
tmp = dA - sA; \
dA = (tmp >= 0 ? tmp : 0);
#define BLEND_RGBA_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \
dR = (dR && sR) ? ((dR * sR) + 255) >> 8 : 0; \
dG = (dG && sG) ? ((dG * sG) + 255) >> 8 : 0; \
dB = (dB && sB) ? ((dB * sB) + 255) >> 8 : 0; \
dA = (dA && sA) ? ((dA * sA) + 255) >> 8 : 0;
#define BLEND_RGBA_MIN(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR < dR) { \
dR = sR; \
} \
if (sG < dG) { \
dG = sG; \
} \
if (sB < dB) { \
dB = sB; \
} \
if (sA < dA) { \
dA = sA; \
}
#define BLEND_RGBA_MAX(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR > dR) { \
dR = sR; \
} \
if (sG > dG) { \
dG = sG; \
} \
if (sB > dB) { \
dB = sB; \
} \
if (sA > dA) { \
dA = sA; \
}
#if 1
/* Choose an alpha blend equation. If the sign is preserved on a right shift
* then use a specialized, faster, equation. Otherwise a more general form,
* where all additions are done before the shift, is needed.
*/
#if (-1 >> 1) < 0
#define ALPHA_BLEND_COMP(sC, dC, sA) ((((sC - dC) * sA + sC) >> 8) + dC)
#else
#define ALPHA_BLEND_COMP(sC, dC, sA) (((dC << 8) + (sC - dC) * sA + sC) >> 8)
#endif
#define ALPHA_BLEND(sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
if (dA) { \
dR = ALPHA_BLEND_COMP(sR, dR, sA); \
dG = ALPHA_BLEND_COMP(sG, dG, sA); \
dB = ALPHA_BLEND_COMP(sB, dB, sA); \
dA = sA + dA - ((sA * dA) / 255); \
} \
else { \
dR = sR; \
dG = sG; \
dB = sB; \
dA = sA; \
} \
} while (0)
#define ALPHA_BLEND_PREMULTIPLIED_COMP(sC, dC, sA) \
(sC + dC - ((dC + 1) * sA >> 8))
#define ALPHA_BLEND_PREMULTIPLIED(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
dR = ALPHA_BLEND_PREMULTIPLIED_COMP(sR, dR, sA); \
dG = ALPHA_BLEND_PREMULTIPLIED_COMP(sG, dG, sA); \
dB = ALPHA_BLEND_PREMULTIPLIED_COMP(sB, dB, sA); \
dA = ALPHA_BLEND_PREMULTIPLIED_COMP(sA, dA, sA); \
} while (0)
#elif 0
#define ALPHA_BLEND(sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
if (sA) { \
if (dA && sA < 255) { \
int dContrib = dA * (255 - sA) / 255; \
dA = sA + dA - ((sA * dA) / 255); \
dR = (dR * dContrib + sR * sA) / dA; \
dG = (dG * dContrib + sG * sA) / dA; \
dB = (dB * dContrib + sB * sA) / dA; \
} \
else { \
dR = sR; \
dG = sG; \
dB = sB; \
dA = sA; \
} \
} \
} while (0)
#endif
int
surface_fill_blend(SDL_Surface *surface, SDL_Rect *rect, Uint32 color,
int blendargs);
void
surface_respect_clip_rect(SDL_Surface *surface, SDL_Rect *rect);
int
pygame_AlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst,
SDL_Rect *dstrect, int the_args);
int
pygame_Blit(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst,
SDL_Rect *dstrect, int the_args);
int
premul_surf_color_by_alpha(SDL_Surface *src, SDL_Surface *dst);
int
pg_warn_simd_at_runtime_but_uncompiled();
#endif /* SURFACE_H */
-472
View File
@@ -1,472 +0,0 @@
<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
$env:VIRTUAL_ENV_PROMPT = $Prompt
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"
# SIG # Begin signature block
# MIIpigYJKoZIhvcNAQcCoIIpezCCKXcCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCBnL745ElCYk8vk
# dBtMuQhLeWJ3ZGfzKW4DHCYzAn+QB6CCDi8wggawMIIEmKADAgECAhAIrUCyYNKc
# TJ9ezam9k67ZMA0GCSqGSIb3DQEBDAUAMGIxCzAJBgNVBAYTAlVTMRUwEwYDVQQK
# EwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5jb20xITAfBgNV
# BAMTGERpZ2lDZXJ0IFRydXN0ZWQgUm9vdCBHNDAeFw0yMTA0MjkwMDAwMDBaFw0z
# NjA0MjgyMzU5NTlaMGkxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5EaWdpQ2VydCwg
# SW5jLjFBMD8GA1UEAxM4RGlnaUNlcnQgVHJ1c3RlZCBHNCBDb2RlIFNpZ25pbmcg
# UlNBNDA5NiBTSEEzODQgMjAyMSBDQTEwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw
# ggIKAoICAQDVtC9C0CiteLdd1TlZG7GIQvUzjOs9gZdwxbvEhSYwn6SOaNhc9es0
# JAfhS0/TeEP0F9ce2vnS1WcaUk8OoVf8iJnBkcyBAz5NcCRks43iCH00fUyAVxJr
# Q5qZ8sU7H/Lvy0daE6ZMswEgJfMQ04uy+wjwiuCdCcBlp/qYgEk1hz1RGeiQIXhF
# LqGfLOEYwhrMxe6TSXBCMo/7xuoc82VokaJNTIIRSFJo3hC9FFdd6BgTZcV/sk+F
# LEikVoQ11vkunKoAFdE3/hoGlMJ8yOobMubKwvSnowMOdKWvObarYBLj6Na59zHh
# 3K3kGKDYwSNHR7OhD26jq22YBoMbt2pnLdK9RBqSEIGPsDsJ18ebMlrC/2pgVItJ
# wZPt4bRc4G/rJvmM1bL5OBDm6s6R9b7T+2+TYTRcvJNFKIM2KmYoX7BzzosmJQay
# g9Rc9hUZTO1i4F4z8ujo7AqnsAMrkbI2eb73rQgedaZlzLvjSFDzd5Ea/ttQokbI
# YViY9XwCFjyDKK05huzUtw1T0PhH5nUwjewwk3YUpltLXXRhTT8SkXbev1jLchAp
# QfDVxW0mdmgRQRNYmtwmKwH0iU1Z23jPgUo+QEdfyYFQc4UQIyFZYIpkVMHMIRro
# OBl8ZhzNeDhFMJlP/2NPTLuqDQhTQXxYPUez+rbsjDIJAsxsPAxWEQIDAQABo4IB
# WTCCAVUwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4EFgQUaDfg67Y7+F8Rhvv+
# YXsIiGX0TkIwHwYDVR0jBBgwFoAU7NfjgtJxXWRM3y5nP+e6mK4cD08wDgYDVR0P
# AQH/BAQDAgGGMBMGA1UdJQQMMAoGCCsGAQUFBwMDMHcGCCsGAQUFBwEBBGswaTAk
# BggrBgEFBQcwAYYYaHR0cDovL29jc3AuZGlnaWNlcnQuY29tMEEGCCsGAQUFBzAC
# hjVodHRwOi8vY2FjZXJ0cy5kaWdpY2VydC5jb20vRGlnaUNlcnRUcnVzdGVkUm9v
# dEc0LmNydDBDBgNVHR8EPDA6MDigNqA0hjJodHRwOi8vY3JsMy5kaWdpY2VydC5j
# b20vRGlnaUNlcnRUcnVzdGVkUm9vdEc0LmNybDAcBgNVHSAEFTATMAcGBWeBDAED
# MAgGBmeBDAEEATANBgkqhkiG9w0BAQwFAAOCAgEAOiNEPY0Idu6PvDqZ01bgAhql
# +Eg08yy25nRm95RysQDKr2wwJxMSnpBEn0v9nqN8JtU3vDpdSG2V1T9J9Ce7FoFF
# UP2cvbaF4HZ+N3HLIvdaqpDP9ZNq4+sg0dVQeYiaiorBtr2hSBh+3NiAGhEZGM1h
# mYFW9snjdufE5BtfQ/g+lP92OT2e1JnPSt0o618moZVYSNUa/tcnP/2Q0XaG3Ryw
# YFzzDaju4ImhvTnhOE7abrs2nfvlIVNaw8rpavGiPttDuDPITzgUkpn13c5Ubdld
# AhQfQDN8A+KVssIhdXNSy0bYxDQcoqVLjc1vdjcshT8azibpGL6QB7BDf5WIIIJw
# 8MzK7/0pNVwfiThV9zeKiwmhywvpMRr/LhlcOXHhvpynCgbWJme3kuZOX956rEnP
# LqR0kq3bPKSchh/jwVYbKyP/j7XqiHtwa+aguv06P0WmxOgWkVKLQcBIhEuWTatE
# QOON8BUozu3xGFYHKi8QxAwIZDwzj64ojDzLj4gLDb879M4ee47vtevLt/B3E+bn
# KD+sEq6lLyJsQfmCXBVmzGwOysWGw/YmMwwHS6DTBwJqakAwSEs0qFEgu60bhQji
# WQ1tygVQK+pKHJ6l/aCnHwZ05/LWUpD9r4VIIflXO7ScA+2GRfS0YW6/aOImYIbq
# yK+p/pQd52MbOoZWeE4wggd3MIIFX6ADAgECAhAHHxQbizANJfMU6yMM0NHdMA0G
# CSqGSIb3DQEBCwUAMGkxCzAJBgNVBAYTAlVTMRcwFQYDVQQKEw5EaWdpQ2VydCwg
# SW5jLjFBMD8GA1UEAxM4RGlnaUNlcnQgVHJ1c3RlZCBHNCBDb2RlIFNpZ25pbmcg
# UlNBNDA5NiBTSEEzODQgMjAyMSBDQTEwHhcNMjIwMTE3MDAwMDAwWhcNMjUwMTE1
# MjM1OTU5WjB8MQswCQYDVQQGEwJVUzEPMA0GA1UECBMGT3JlZ29uMRIwEAYDVQQH
# EwlCZWF2ZXJ0b24xIzAhBgNVBAoTGlB5dGhvbiBTb2Z0d2FyZSBGb3VuZGF0aW9u
# MSMwIQYDVQQDExpQeXRob24gU29mdHdhcmUgRm91bmRhdGlvbjCCAiIwDQYJKoZI
# hvcNAQEBBQADggIPADCCAgoCggIBAKgc0BTT+iKbtK6f2mr9pNMUTcAJxKdsuOiS
# YgDFfwhjQy89koM7uP+QV/gwx8MzEt3c9tLJvDccVWQ8H7mVsk/K+X+IufBLCgUi
# 0GGAZUegEAeRlSXxxhYScr818ma8EvGIZdiSOhqjYc4KnfgfIS4RLtZSrDFG2tN1
# 6yS8skFa3IHyvWdbD9PvZ4iYNAS4pjYDRjT/9uzPZ4Pan+53xZIcDgjiTwOh8VGu
# ppxcia6a7xCyKoOAGjvCyQsj5223v1/Ig7Dp9mGI+nh1E3IwmyTIIuVHyK6Lqu35
# 2diDY+iCMpk9ZanmSjmB+GMVs+H/gOiofjjtf6oz0ki3rb7sQ8fTnonIL9dyGTJ0
# ZFYKeb6BLA66d2GALwxZhLe5WH4Np9HcyXHACkppsE6ynYjTOd7+jN1PRJahN1oE
# RzTzEiV6nCO1M3U1HbPTGyq52IMFSBM2/07WTJSbOeXjvYR7aUxK9/ZkJiacl2iZ
# I7IWe7JKhHohqKuceQNyOzxTakLcRkzynvIrk33R9YVqtB4L6wtFxhUjvDnQg16x
# ot2KVPdfyPAWd81wtZADmrUtsZ9qG79x1hBdyOl4vUtVPECuyhCxaw+faVjumapP
# Unwo8ygflJJ74J+BYxf6UuD7m8yzsfXWkdv52DjL74TxzuFTLHPyARWCSCAbzn3Z
# Ily+qIqDAgMBAAGjggIGMIICAjAfBgNVHSMEGDAWgBRoN+Drtjv4XxGG+/5hewiI
# ZfROQjAdBgNVHQ4EFgQUt/1Teh2XDuUj2WW3siYWJgkZHA8wDgYDVR0PAQH/BAQD
# AgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMDMIG1BgNVHR8Ega0wgaowU6BRoE+GTWh0
# dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNENvZGVTaWdu
# aW5nUlNBNDA5NlNIQTM4NDIwMjFDQTEuY3JsMFOgUaBPhk1odHRwOi8vY3JsNC5k
# aWdpY2VydC5jb20vRGlnaUNlcnRUcnVzdGVkRzRDb2RlU2lnbmluZ1JTQTQwOTZT
# SEEzODQyMDIxQ0ExLmNybDA+BgNVHSAENzA1MDMGBmeBDAEEATApMCcGCCsGAQUF
# BwIBFhtodHRwOi8vd3d3LmRpZ2ljZXJ0LmNvbS9DUFMwgZQGCCsGAQUFBwEBBIGH
# MIGEMCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wXAYIKwYB
# BQUHMAKGUGh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0
# ZWRHNENvZGVTaWduaW5nUlNBNDA5NlNIQTM4NDIwMjFDQTEuY3J0MAwGA1UdEwEB
# /wQCMAAwDQYJKoZIhvcNAQELBQADggIBABxv4AeV/5ltkELHSC63fXAFYS5tadcW
# TiNc2rskrNLrfH1Ns0vgSZFoQxYBFKI159E8oQQ1SKbTEubZ/B9kmHPhprHya08+
# VVzxC88pOEvz68nA82oEM09584aILqYmj8Pj7h/kmZNzuEL7WiwFa/U1hX+XiWfL
# IJQsAHBla0i7QRF2de8/VSF0XXFa2kBQ6aiTsiLyKPNbaNtbcucaUdn6vVUS5izW
# OXM95BSkFSKdE45Oq3FForNJXjBvSCpwcP36WklaHL+aHu1upIhCTUkzTHMh8b86
# WmjRUqbrnvdyR2ydI5l1OqcMBjkpPpIV6wcc+KY/RH2xvVuuoHjlUjwq2bHiNoX+
# W1scCpnA8YTs2d50jDHUgwUo+ciwpffH0Riq132NFmrH3r67VaN3TuBxjI8SIZM5
# 8WEDkbeoriDk3hxU8ZWV7b8AW6oyVBGfM06UgkfMb58h+tJPrFx8VI/WLq1dTqMf
# ZOm5cuclMnUHs2uqrRNtnV8UfidPBL4ZHkTcClQbCoz0UbLhkiDvIS00Dn+BBcxw
# /TKqVL4Oaz3bkMSsM46LciTeucHY9ExRVt3zy7i149sd+F4QozPqn7FrSVHXmem3
# r7bjyHTxOgqxRCVa18Vtx7P/8bYSBeS+WHCKcliFCecspusCDSlnRUjZwyPdP0VH
# xaZg2unjHY3rMYIasTCCGq0CAQEwfTBpMQswCQYDVQQGEwJVUzEXMBUGA1UEChMO
# RGlnaUNlcnQsIEluYy4xQTA/BgNVBAMTOERpZ2lDZXJ0IFRydXN0ZWQgRzQgQ29k
# ZSBTaWduaW5nIFJTQTQwOTYgU0hBMzg0IDIwMjEgQ0ExAhAHHxQbizANJfMU6yMM
# 0NHdMA0GCWCGSAFlAwQCAQUAoIHEMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEE
# MBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMC8GCSqGSIb3DQEJBDEiBCBn
# AZ6P7YvTwq0fbF62o7E75R0LxsW5OtyYiFESQckLhjBYBgorBgEEAYI3AgEMMUow
# SKBGgEQAQgB1AGkAbAB0ADoAIABSAGUAbABlAGEAcwBlAF8AdgAzAC4AMQAxAC4A
# MABfADIAMAAyADIAMQAwADIANAAuADAAMTANBgkqhkiG9w0BAQEFAASCAgAu2uG5
# zPAAKY4N8BVMzMPRSoTqq2HAcX+oqvto72DGzHLKlfAuuyf59saf7TQZQ04Ao1ni
# EvpzZ8C4Wv7yu8RyPwJQThIuFQuhMgB+Zscl+YDnAo5+GFTBpevgcG2n2ClHAPuT
# 7aXe3+5wChDpMqyusrBYws+8R6tg8rKFyRhQndxIJkIMlZhoh1qI3tRypW6e2r5l
# Uf4pPDkNBBySzjNOupTyv1/d2Y31Ise8xLrLbuMLYxtir/5A0z6GlUueoecpe9TS
# uEqz2bI+HZbGC6xK2BU4vW8s7qefVTmPFAf3JiCjZZ46qFAg9jnWCRzAA/3jOtu6
# V345rFhCRJxPKz4M96B5mUCnMU0BB4cHJFKZfezd5phtExi1///WcnKNkpNTto+d
# etpWbJ87DibBro3ZhDPh9FpHW2jxy2IQBZo02Udbwfd7aoKhRf7MCLqZUIziPjRS
# FcA1hyOzYk4XfHK1qW3Wpflduz86UGDbURWP3XhXQNaSScJGOhVylZbiBWcjFKlD
# E/sl+bDyafUy0jLur6/Vl4H2xCgXbJlEazr04QfizW9N9x2G6sDkdbQd4k3kSEJt
# UOufbrdjDY1MRd/NlnjVGY+zslEDN9QJQuKq00SJagicDJ+vIzg6J7YjnRfDGLAi
# RJb9rXxuQyEoSTdtxQgnPNkb6vCNQz80bjHmoqGCFz4wghc6BgorBgEEAYI3AwMB
# MYIXKjCCFyYGCSqGSIb3DQEHAqCCFxcwghcTAgEDMQ8wDQYJYIZIAWUDBAIBBQAw
# eAYLKoZIhvcNAQkQAQSgaQRnMGUCAQEGCWCGSAGG/WwHATAxMA0GCWCGSAFlAwQC
# AQUABCCJnxONky4RAgM+R4O2F+soqJ9cjrZDLL3JqXN+msPWngIRAPgphjs42egI
# Fn/RXf6+TgkYDzIwMjIxMDI0MTgzMzM4WqCCEwcwggbAMIIEqKADAgECAhAMTWly
# S5T6PCpKPSkHgD1aMA0GCSqGSIb3DQEBCwUAMGMxCzAJBgNVBAYTAlVTMRcwFQYD
# VQQKEw5EaWdpQ2VydCwgSW5jLjE7MDkGA1UEAxMyRGlnaUNlcnQgVHJ1c3RlZCBH
# NCBSU0E0MDk2IFNIQTI1NiBUaW1lU3RhbXBpbmcgQ0EwHhcNMjIwOTIxMDAwMDAw
# WhcNMzMxMTIxMjM1OTU5WjBGMQswCQYDVQQGEwJVUzERMA8GA1UEChMIRGlnaUNl
# cnQxJDAiBgNVBAMTG0RpZ2lDZXJ0IFRpbWVzdGFtcCAyMDIyIC0gMjCCAiIwDQYJ
# KoZIhvcNAQEBBQADggIPADCCAgoCggIBAM/spSY6xqnya7uNwQ2a26HoFIV0Mxom
# rNAcVR4eNm28klUMYfSdCXc9FZYIL2tkpP0GgxbXkZI4HDEClvtysZc6Va8z7GGK
# 6aYo25BjXL2JU+A6LYyHQq4mpOS7eHi5ehbhVsbAumRTuyoW51BIu4hpDIjG8b7g
# L307scpTjUCDHufLckkoHkyAHoVW54Xt8mG8qjoHffarbuVm3eJc9S/tjdRNlYRo
# 44DLannR0hCRRinrPibytIzNTLlmyLuqUDgN5YyUXRlav/V7QG5vFqianJVHhoV5
# PgxeZowaCiS+nKrSnLb3T254xCg/oxwPUAY3ugjZNaa1Htp4WB056PhMkRCWfk3h
# 3cKtpX74LRsf7CtGGKMZ9jn39cFPcS6JAxGiS7uYv/pP5Hs27wZE5FX/NurlfDHn
# 88JSxOYWe1p+pSVz28BqmSEtY+VZ9U0vkB8nt9KrFOU4ZodRCGv7U0M50GT6Vs/g
# 9ArmFG1keLuY/ZTDcyHzL8IuINeBrNPxB9ThvdldS24xlCmL5kGkZZTAWOXlLimQ
# prdhZPrZIGwYUWC6poEPCSVT8b876asHDmoHOWIZydaFfxPZjXnPYsXs4Xu5zGcT
# B5rBeO3GiMiwbjJ5xwtZg43G7vUsfHuOy2SJ8bHEuOdTXl9V0n0ZKVkDTvpd6kVz
# HIR+187i1Dp3AgMBAAGjggGLMIIBhzAOBgNVHQ8BAf8EBAMCB4AwDAYDVR0TAQH/
# BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcDCDAgBgNVHSAEGTAXMAgGBmeBDAEE
# AjALBglghkgBhv1sBwEwHwYDVR0jBBgwFoAUuhbZbU2FL3MpdpovdYxqII+eyG8w
# HQYDVR0OBBYEFGKK3tBh/I8xFO2XC809KpQU31KcMFoGA1UdHwRTMFEwT6BNoEuG
# SWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNFJTQTQw
# OTZTSEEyNTZUaW1lU3RhbXBpbmdDQS5jcmwwgZAGCCsGAQUFBwEBBIGDMIGAMCQG
# CCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wWAYIKwYBBQUHMAKG
# TGh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNFJT
# QTQwOTZTSEEyNTZUaW1lU3RhbXBpbmdDQS5jcnQwDQYJKoZIhvcNAQELBQADggIB
# AFWqKhrzRvN4Vzcw/HXjT9aFI/H8+ZU5myXm93KKmMN31GT8Ffs2wklRLHiIY1UJ
# RjkA/GnUypsp+6M/wMkAmxMdsJiJ3HjyzXyFzVOdr2LiYWajFCpFh0qYQitQ/Bu1
# nggwCfrkLdcJiXn5CeaIzn0buGqim8FTYAnoo7id160fHLjsmEHw9g6A++T/350Q
# p+sAul9Kjxo6UrTqvwlJFTU2WZoPVNKyG39+XgmtdlSKdG3K0gVnK3br/5iyJpU4
# GYhEFOUKWaJr5yI+RCHSPxzAm+18SLLYkgyRTzxmlK9dAlPrnuKe5NMfhgFknADC
# 6Vp0dQ094XmIvxwBl8kZI4DXNlpflhaxYwzGRkA7zl011Fk+Q5oYrsPJy8P7mxNf
# arXH4PMFw1nfJ2Ir3kHJU7n/NBBn9iYymHv+XEKUgZSCnawKi8ZLFUrTmJBFYDOA
# 4CPe+AOk9kVH5c64A0JH6EE2cXet/aLol3ROLtoeHYxayB6a1cLwxiKoT5u92Bya
# UcQvmvZfpyeXupYuhVfAYOd4Vn9q78KVmksRAsiCnMkaBXy6cbVOepls9Oie1FqY
# yJ+/jbsYXEP10Cro4mLueATbvdH7WwqocH7wl4R44wgDXUcsY6glOJcB0j862uXl
# 9uab3H4szP8XTE0AotjWAQ64i+7m4HJViSwnGWH2dwGMMIIGrjCCBJagAwIBAgIQ
# BzY3tyRUfNhHrP0oZipeWzANBgkqhkiG9w0BAQsFADBiMQswCQYDVQQGEwJVUzEV
# MBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29t
# MSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwHhcNMjIwMzIzMDAw
# MDAwWhcNMzcwMzIyMjM1OTU5WjBjMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGln
# aUNlcnQsIEluYy4xOzA5BgNVBAMTMkRpZ2lDZXJ0IFRydXN0ZWQgRzQgUlNBNDA5
# NiBTSEEyNTYgVGltZVN0YW1waW5nIENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
# MIICCgKCAgEAxoY1BkmzwT1ySVFVxyUDxPKRN6mXUaHW0oPRnkyibaCwzIP5WvYR
# oUQVQl+kiPNo+n3znIkLf50fng8zH1ATCyZzlm34V6gCff1DtITaEfFzsbPuK4CE
# iiIY3+vaPcQXf6sZKz5C3GeO6lE98NZW1OcoLevTsbV15x8GZY2UKdPZ7Gnf2ZCH
# RgB720RBidx8ald68Dd5n12sy+iEZLRS8nZH92GDGd1ftFQLIWhuNyG7QKxfst5K
# fc71ORJn7w6lY2zkpsUdzTYNXNXmG6jBZHRAp8ByxbpOH7G1WE15/tePc5OsLDni
# pUjW8LAxE6lXKZYnLvWHpo9OdhVVJnCYJn+gGkcgQ+NDY4B7dW4nJZCYOjgRs/b2
# nuY7W+yB3iIU2YIqx5K/oN7jPqJz+ucfWmyU8lKVEStYdEAoq3NDzt9KoRxrOMUp
# 88qqlnNCaJ+2RrOdOqPVA+C/8KI8ykLcGEh/FDTP0kyr75s9/g64ZCr6dSgkQe1C
# vwWcZklSUPRR8zZJTYsg0ixXNXkrqPNFYLwjjVj33GHek/45wPmyMKVM1+mYSlg+
# 0wOI/rOP015LdhJRk8mMDDtbiiKowSYI+RQQEgN9XyO7ZONj4KbhPvbCdLI/Hgl2
# 7KtdRnXiYKNYCQEoAA6EVO7O6V3IXjASvUaetdN2udIOa5kM0jO0zbECAwEAAaOC
# AV0wggFZMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFLoW2W1NhS9zKXaa
# L3WMaiCPnshvMB8GA1UdIwQYMBaAFOzX44LScV1kTN8uZz/nupiuHA9PMA4GA1Ud
# DwEB/wQEAwIBhjATBgNVHSUEDDAKBggrBgEFBQcDCDB3BggrBgEFBQcBAQRrMGkw
# JAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBBBggrBgEFBQcw
# AoY1aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0VHJ1c3RlZFJv
# b3RHNC5jcnQwQwYDVR0fBDwwOjA4oDagNIYyaHR0cDovL2NybDMuZGlnaWNlcnQu
# Y29tL0RpZ2lDZXJ0VHJ1c3RlZFJvb3RHNC5jcmwwIAYDVR0gBBkwFzAIBgZngQwB
# BAIwCwYJYIZIAYb9bAcBMA0GCSqGSIb3DQEBCwUAA4ICAQB9WY7Ak7ZvmKlEIgF+
# ZtbYIULhsBguEE0TzzBTzr8Y+8dQXeJLKftwig2qKWn8acHPHQfpPmDI2AvlXFvX
# bYf6hCAlNDFnzbYSlm/EUExiHQwIgqgWvalWzxVzjQEiJc6VaT9Hd/tydBTX/6tP
# iix6q4XNQ1/tYLaqT5Fmniye4Iqs5f2MvGQmh2ySvZ180HAKfO+ovHVPulr3qRCy
# Xen/KFSJ8NWKcXZl2szwcqMj+sAngkSumScbqyQeJsG33irr9p6xeZmBo1aGqwpF
# yd/EjaDnmPv7pp1yr8THwcFqcdnGE4AJxLafzYeHJLtPo0m5d2aR8XKc6UsCUqc3
# fpNTrDsdCEkPlM05et3/JWOZJyw9P2un8WbDQc1PtkCbISFA0LcTJM3cHXg65J6t
# 5TRxktcma+Q4c6umAU+9Pzt4rUyt+8SVe+0KXzM5h0F4ejjpnOHdI/0dKNPH+ejx
# mF/7K9h+8kaddSweJywm228Vex4Ziza4k9Tm8heZWcpw8De/mADfIBZPJ/tgZxah
# ZrrdVcA6KYawmKAr7ZVBtzrVFZgxtGIJDwq9gdkT/r+k0fNX2bwE+oLeMt8EifAA
# zV3C+dAjfwAL5HYCJtnwZXZCpimHCUcr5n8apIUP/JiW9lVUKx+A+sDyDivl1vup
# L0QVSucTDh3bNzgaoSv27dZ8/DCCBY0wggR1oAMCAQICEA6bGI750C3n79tQ4ghA
# GFowDQYJKoZIhvcNAQEMBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lD
# ZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGln
# aUNlcnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTIyMDgwMTAwMDAwMFoXDTMxMTEw
# OTIzNTk1OVowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ
# MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgVHJ1
# c3RlZCBSb290IEc0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAv+aQ
# c2jeu+RdSjwwIjBpM+zCpyUuySE98orYWcLhKac9WKt2ms2uexuEDcQwH/MbpDgW
# 61bGl20dq7J58soR0uRf1gU8Ug9SH8aeFaV+vp+pVxZZVXKvaJNwwrK6dZlqczKU
# 0RBEEC7fgvMHhOZ0O21x4i0MG+4g1ckgHWMpLc7sXk7Ik/ghYZs06wXGXuxbGrzr
# yc/NrDRAX7F6Zu53yEioZldXn1RYjgwrt0+nMNlW7sp7XeOtyU9e5TXnMcvak17c
# jo+A2raRmECQecN4x7axxLVqGDgDEI3Y1DekLgV9iPWCPhCRcKtVgkEy19sEcypu
# kQF8IUzUvK4bA3VdeGbZOjFEmjNAvwjXWkmkwuapoGfdpCe8oU85tRFYF/ckXEaP
# ZPfBaYh2mHY9WV1CdoeJl2l6SPDgohIbZpp0yt5LHucOY67m1O+SkjqePdwA5EUl
# ibaaRBkrfsCUtNJhbesz2cXfSwQAzH0clcOP9yGyshG3u3/y1YxwLEFgqrFjGESV
# GnZifvaAsPvoZKYz0YkH4b235kOkGLimdwHhD5QMIR2yVCkliWzlDlJRR3S+Jqy2
# QXXeeqxfjT/JvNNBERJb5RBQ6zHFynIWIgnffEx1P2PsIV/EIFFrb7GrhotPwtZF
# X50g/KEexcCPorF+CiaZ9eRpL5gdLfXZqbId5RsCAwEAAaOCATowggE2MA8GA1Ud
# EwEB/wQFMAMBAf8wHQYDVR0OBBYEFOzX44LScV1kTN8uZz/nupiuHA9PMB8GA1Ud
# IwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3zbcgPMA4GA1UdDwEB/wQEAwIBhjB5Bggr
# BgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNv
# bTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lD
# ZXJ0QXNzdXJlZElEUm9vdENBLmNydDBFBgNVHR8EPjA8MDqgOKA2hjRodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMBEG
# A1UdIAQKMAgwBgYEVR0gADANBgkqhkiG9w0BAQwFAAOCAQEAcKC/Q1xV5zhfoKN0
# Gz22Ftf3v1cHvZqsoYcs7IVeqRq7IviHGmlUIu2kiHdtvRoU9BNKei8ttzjv9P+A
# ufih9/Jy3iS8UgPITtAq3votVs/59PesMHqai7Je1M/RQ0SbQyHrlnKhSLSZy51P
# pwYDE3cnRNTnf+hZqPC/Lwum6fI0POz3A8eHqNJMQBk1RmppVLC4oVaO7KTVPeix
# 3P0c2PR3WlxUjG/voVA9/HYJaISfb8rbII01YBwCA8sgsKxYoA5AY8WYIsGyWfVV
# a88nq2x2zm8jLfR+cWojayL/ErhULSd+2DrZ8LaHlv1b0VysGMNNn3O3AamfV6pe
# KOK5lDGCA3YwggNyAgEBMHcwYzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lD
# ZXJ0LCBJbmMuMTswOQYDVQQDEzJEaWdpQ2VydCBUcnVzdGVkIEc0IFJTQTQwOTYg
# U0hBMjU2IFRpbWVTdGFtcGluZyBDQQIQDE1pckuU+jwqSj0pB4A9WjANBglghkgB
# ZQMEAgEFAKCB0TAaBgkqhkiG9w0BCQMxDQYLKoZIhvcNAQkQAQQwHAYJKoZIhvcN
# AQkFMQ8XDTIyMTAyNDE4MzMzOFowKwYLKoZIhvcNAQkQAgwxHDAaMBgwFgQU84ci
# TYYzgpI1qZS8vY+W6f4cfHMwLwYJKoZIhvcNAQkEMSIEILoHmtH34MMtLSezOEUS
# 8z6MwtqV/PFPq/sNVq5aJnKMMDcGCyqGSIb3DQEJEAIvMSgwJjAkMCIEIMf04b4y
# KIkgq+ImOr4axPxP5ngcLWTQTIB1V6Ajtbb6MA0GCSqGSIb3DQEBAQUABIICAEtb
# WINxaVTjBdclvuFwJT/uHWvlOdcKzc1o+toRkFb1OA7shEdXFvjNU549TilTs8qQ
# bly8CbFcz3JzLVLrNKO7lr4GXd2iyJV5sv/XU4ED866fznOnFWtZJvxKGOdqN0W7
# 01pw7mIJ8+2aRqpow1ppPzju7VagRQ8fKmtj9Sg5N8Ja3+AehpjwM/PYzctan/1m
# ytIK/HCw5k/MeGmPVBs/fqbN0DT4KGrJ7YMySdYZMs0U9V7Ak7PelZLgw8BkNi1Y
# Rb9i+7/t9AaBlVYMy/6+gzdsnarnlSzV8/6Est8w4Ie7sBxx3Tpsokopb+oPF///
# 2cA3jMNToO9YfsqvgpTEkWwjWanC2cd26K8ikw0uu0klmaxNvYpP459/QU3JMyFj
# I4ReTxVXLZrQlzCDUUdLmLSeV1AugCOYOHM2RAv4r+3qxk0jBCfA8RRK+prLNjXE
# af1QEbeRRNr0418MtnBdIzxHnW8yffWfHmtDNJoyPqggkRU3Mb8Myu8QPD3ZiCPj
# F+HsKUntyCV64hr9BNLmkpbw+kUvGtC0/7sZF9Gyp/DKnnbQu8vSR+CaZQqVQxJo
# UeI7m44utNTSSZCJ9JV7bnniwqztrP/r2PTAxkUywoCzif6R863qJ/uQA0QQjq8t
# +aR822g6YVyJsLYQKbpEgshG2QwzGHun5HkvawJ8
# SIG # End signature block
-69
View File
@@ -1,69 +0,0 @@
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r 2> /dev/null
fi
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
unset VIRTUAL_ENV_PROMPT
if [ ! "${1:-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
VIRTUAL_ENV="e:\Documents\Python Scripting\AI Snake\.venv"
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/Scripts:$PATH"
export PATH
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
unset PYTHONHOME
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
PS1="(.venv) ${PS1:-}"
export PS1
VIRTUAL_ENV_PROMPT="(.venv) "
export VIRTUAL_ENV_PROMPT
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r 2> /dev/null
fi
-34
View File
@@ -1,34 +0,0 @@
@echo off
rem This file is UTF-8 encoded, so we need to update the current code page while executing it
for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do (
set _OLD_CODEPAGE=%%a
)
if defined _OLD_CODEPAGE (
"%SystemRoot%\System32\chcp.com" 65001 > nul
)
set VIRTUAL_ENV=e:\Documents\Python Scripting\AI Snake\.venv
if not defined PROMPT set PROMPT=$P$G
if defined _OLD_VIRTUAL_PROMPT set PROMPT=%_OLD_VIRTUAL_PROMPT%
if defined _OLD_VIRTUAL_PYTHONHOME set PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%
set _OLD_VIRTUAL_PROMPT=%PROMPT%
set PROMPT=(.venv) %PROMPT%
if defined PYTHONHOME set _OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%
set PYTHONHOME=
if defined _OLD_VIRTUAL_PATH set PATH=%_OLD_VIRTUAL_PATH%
if not defined _OLD_VIRTUAL_PATH set _OLD_VIRTUAL_PATH=%PATH%
set PATH=%VIRTUAL_ENV%\Scripts;%PATH%
set VIRTUAL_ENV_PROMPT=(.venv)
:END
if defined _OLD_CODEPAGE (
"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
set _OLD_CODEPAGE=
)
Binary file not shown.
Binary file not shown.
-22
View File
@@ -1,22 +0,0 @@
@echo off
if defined _OLD_VIRTUAL_PROMPT (
set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
)
set _OLD_VIRTUAL_PROMPT=
if defined _OLD_VIRTUAL_PYTHONHOME (
set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
set _OLD_VIRTUAL_PYTHONHOME=
)
if defined _OLD_VIRTUAL_PATH (
set "PATH=%_OLD_VIRTUAL_PATH%"
)
set _OLD_VIRTUAL_PATH=
set VIRTUAL_ENV=
set VIRTUAL_ENV_PROMPT=
:END
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-5
View File
@@ -1,5 +0,0 @@
home = C:\Python311
include-system-site-packages = false
version = 3.11.0
executable = C:\Python311\python.exe
command = C:\Python311\python.exe -m venv e:\Documents\Python Scripting\AI Snake\.venv
+92 -39
View File
@@ -3,11 +3,26 @@
This is a living document that tracks the development progress of the AI Snake Game project.
## Current Status
Last Updated: [Food System Implementation]
- Added Food class with spawning mechanics
- Integrated food system with main game loop
- Implemented basic scoring system
- Added game over screen with score display
Last Updated: [Control and Menu Improvements]
- Fixed menu interaction issues:
- Added proper mouse click handling
- Fixed menu item highlighting
- Improved keyboard and mouse navigation
- Improved snake movement system:
- Implemented input buffer for direction changes
- Fixed rapid direction change issues
- Improved responsiveness while maintaining safety
- Previous updates:
- Added settings menu with game options
- Added wrap-around mode toggle
- Added speed increase toggle
- Added main menu interface
- Added game mode selection
- Implemented menu navigation
- Added game mode display
- Added game restart functionality
- Added Food class with spawning mechanics
- Implemented basic scoring system
## Phase 1: Project Setup and Basic Structure ✅
- [x] Create project structure and virtual environment
@@ -16,27 +31,41 @@ Last Updated: [Food System Implementation]
- [x] Create basic project documentation (README.md)
- [x] Create living roadmap document
## Phase 2: Core Game Development 🔄
## Phase 2: Core Game Development ✅
- [x] Implement basic game window using Pygame
- [x] Create Snake class with movement mechanics
- [x] Basic movement and collision
- [x] Input buffering for direction changes
- [x] Fix rapid direction change issues
- [x] Prevent 180-degree turns
- [x] Implement food spawning system
- [x] Create Food class
- [x] Add random food placement
- [x] Add collision detection with food
- [x] Add collision detection (walls and self)
- [x] Add collision detection
- [x] Wall collisions
- [x] Self collisions
- [x] Add wrap-around mode option
- [x] Implement scoring system
- [x] Add score display
- [ ] Add high score tracking
- [x] Add game over conditions
- [x] Implement game over state transition
- [ ] Add restart functionality
- [x] Add restart functionality
## Phase 3: Game Polish and UI
- [ ] Add main menu interface
- [ ] Create menu layout
- [ ] Add game mode selection
- [ ] Add settings options
## Phase 3: Game Polish and UI ✅
- [x] Add main menu interface
- [x] Create menu layout
- [x] Add game mode selection
- [x] Add settings menu
- [x] Fix menu interaction issues
- [x] Mouse click handling
- [x] Menu item highlighting
- [x] Keyboard/mouse navigation
- [x] Implement pause functionality
- [x] Add settings options
- [x] Wrap-around mode toggle
- [x] Speed increase toggle
- [ ] Add visual effects and animations
- [ ] Snake movement animation
- [ ] Food spawn animation
@@ -47,51 +76,75 @@ Last Updated: [Food System Implementation]
- [ ] Add background music
- [ ] Add menu sounds
- [ ] Display score and high score
- [ ] Add game over screen with restart option
- [x] Add game over screen with restart option
## Phase 4: AI Implementation
- [ ] Design AI algorithm (pathfinding)
- [ ] Research and select appropriate algorithm
- [ ] Implement basic pathfinding
- [ ] Implement AI snake movement logic
- [ ] Create AI controller class
- [ ] Implement decision making
- [ ] Add AI difficulty levels
- [ ] Easy mode (basic pathfinding)
- [ ] Medium mode (improved decision making)
## Phase 4: AI Implementation 🔄
- [ ] Set up ML training environment
- [ ] Create gym-like interface for the game
- [ ] Define observation space (snake + food state)
- [ ] Define action space (4 directions)
- [ ] Implement reward system
- [ ] Implement ML infrastructure
- [ ] Add ML dependencies (PyTorch/TensorFlow)
- [ ] Create neural network architecture
- [ ] Set up training pipeline
- [ ] Train AI models for different difficulties
- [ ] Easy mode (basic food seeking)
- [ ] Medium mode (balanced survival/food seeking)
- [ ] Hard mode (optimal pathfinding)
- [ ] Create mode selection (Player vs AI)
- [ ] Optimize AI performance
- [ ] Create AI controller class
- [ ] Model loading and inference
- [ ] Real-time decision making
- [ ] Performance optimization
- [x] Create mode selection (Player vs AI)
- [ ] Add training utilities
- [ ] Save/load model checkpoints
- [ ] Training progress visualization
- [ ] Model performance metrics
## Phase 5: Final Polish
- [ ] Add configuration options
- [ ] Game speed settings
- [x] Add configuration options
- [x] Game speed settings
- [x] Wrap-around option
- [ ] Visual settings
- [ ] Sound settings
- [ ] Implement save/load functionality for high scores
- [ ] Bug fixing and performance optimization
- [x] Fix menu interaction bugs
- [x] Fix movement control issues
- [x] Optimize input handling
- [ ] Code cleanup and documentation
- [ ] Add docstrings
- [x] Add docstrings
- [ ] Create API documentation
- [ ] Update README with final features
- [ ] Final testing and refinements
## Resolved Issues
1. Menu Interaction
- Issue: Menu items not responding to clicks
- Solution: Added proper mouse click event handling in game loop
- Solution: Fixed menu item highlighting and selection state
2. Snake Movement
- Issue: Rapid direction changes causing self-collision
- Issue: Missed inputs during quick turns
- Solution: Implemented input buffer system
- Solution: Process one direction change per grid movement
- Solution: Store up to 2 pending direction changes
## Next Steps
1. Add restart functionality
- Implement game restart on key press
- Reset score and snake position
2. Create main menu interface
- Design menu layout
- Implement menu navigation
3. Add high score system
1. Implement AI snake movement
- Set up ML training environment
- Create neural network architecture
- Train initial model
2. Add high score system
- Implement score persistence
- Add high score display
4. Add visual and sound effects
3. Add visual and sound effects
- Implement basic animations
- Add game sounds
## Known Issues
- None reported yet
- None reported
## Future Considerations
- Multiplayer support
+10
View File
@@ -0,0 +1,10 @@
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = -v --tb=short -n 4 --import-mode=importlib
markers =
slow: marks tests as slow (deselect with '-m "not slow"')
integration: marks tests as integration tests
unit: marks tests as unit tests
+9 -1
View File
@@ -1,4 +1,12 @@
pygame==2.5.2
numpy==1.24.3
numpy==1.26.3
black==23.12.1 # for code formatting
pytest==7.4.3 # for testing
pytest-xdist==3.5.0 # for parallel test execution
--extra-index-url https://download.pytorch.org/whl/cu118
torch==2.1.2+cu118 # CUDA 11.8 support
stable-baselines3[extra]==2.2.1 # for reinforcement learning
tensorboard==2.15.1 # for training visualization
gymnasium==0.29.1 # for RL environment interface
tqdm==4.66.1
rich==13.7.0
+39
View File
@@ -0,0 +1,39 @@
from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="ai-snake-game",
version="0.1.0",
author="Rbanh",
description="A classic snake game with AI capabilities",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://git.spacetrainclubhouse.com/Rbanh/AI-Snake-Game",
packages=find_packages(),
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Development Status :: 3 - Alpha",
"Topic :: Games/Entertainment :: Arcade",
],
python_requires=">=3.8",
install_requires=[
"pygame>=2.5.2",
"numpy>=1.24.3",
],
extras_require={
"dev": [
"pytest>=7.4.3",
"pytest-xdist>=3.5.0",
"black>=23.12.1",
],
},
entry_points={
"console_scripts": [
"snake-game=src.cli:main",
],
},
)
+37
View File
@@ -0,0 +1,37 @@
"""
AI Snake Game - A classic snake game with AI capabilities.
This package contains all the core game components including:
- Game engine and state management
- Snake movement and collision detection
- Food spawning system
- Menu interface
- AI controllers (coming soon)
"""
from src import config
from src import core
from src import ai
from src import ui
from src.game import Game, GameState
from src.ui.menu import GameMode
__version__ = '0.1.0'
__author__ = 'Rbanh'
# Define what's available when using "from src import *"
__all__ = [
'Game',
'GameState',
'Snake',
'Direction',
'Food',
'Menu',
'GameMode',
'MenuItem',
'cli_main',
'config',
'core',
'ai',
'ui'
]
+235
View File
@@ -0,0 +1,235 @@
"""
Training Configuration UI
This module provides a graphical interface for configuring AI training parameters.
"""
import pygame
import json
import os
from typing import Dict, Any, Optional, Tuple, List
class ConfigUI:
def __init__(self, width: int = 800, height: int = 600):
"""Initialize the configuration UI."""
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Training Configuration")
# Fonts
self.title_font = pygame.font.Font(None, 48)
self.header_font = pygame.font.Font(None, 36)
self.text_font = pygame.font.Font(None, 24)
# Colors
self.colors = {
'background': (0, 0, 0),
'text': (200, 200, 200),
'highlight': (0, 255, 0),
'button': (40, 40, 40),
'button_hover': (60, 60, 60),
'input_bg': (30, 30, 30),
'input_active': (50, 50, 50)
}
# Parameters
self.parameters = {
'timesteps': {
'value': 1000000,
'type': 'int',
'min': 1000,
'max': 10000000,
'description': 'Total timesteps to train for'
},
'learning_rate': {
'value': 0.0003,
'type': 'float',
'min': 0.00001,
'max': 0.01,
'description': 'Learning rate for training'
},
'batch_size': {
'value': 64,
'type': 'int',
'min': 32,
'max': 512,
'description': 'Batch size for training'
},
'n_envs': {
'value': 8,
'type': 'int',
'min': 1,
'max': 32,
'description': 'Number of parallel environments'
},
'n_steps': {
'value': 2048,
'type': 'int',
'min': 128,
'max': 8192,
'description': 'Number of steps per update'
}
}
# UI state
self.active_input = None
self.input_text = ""
self.scroll_offset = 0
self.max_scroll = max(0, len(self.parameters) * 60 - (height - 200))
# Load saved config if exists
self.config_file = "training_config.json"
self.load_config()
def load_config(self) -> None:
"""Load configuration from file."""
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r') as f:
saved_config = json.load(f)
for key, value in saved_config.items():
if key in self.parameters:
self.parameters[key]['value'] = value
except:
pass
def save_config(self) -> None:
"""Save configuration to file."""
config = {key: param['value'] for key, param in self.parameters.items()}
with open(self.config_file, 'w') as f:
json.dump(config, f, indent=4)
def draw_text_input(self, rect: pygame.Rect, value: Any, active: bool) -> None:
"""Draw a text input field."""
color = self.colors['input_active'] if active else self.colors['input_bg']
pygame.draw.rect(self.screen, color, rect)
pygame.draw.rect(self.screen, self.colors['text'], rect, 1)
text = str(value)
if active:
text = self.input_text + "|"
text_surface = self.text_font.render(text, True, self.colors['text'])
text_rect = text_surface.get_rect(midleft=(rect.left + 5, rect.centery))
self.screen.blit(text_surface, text_rect)
def draw_button(self, rect: pygame.Rect, text: str, hover: bool = False) -> None:
"""Draw a button."""
color = self.colors['button_hover'] if hover else self.colors['button']
pygame.draw.rect(self.screen, color, rect)
pygame.draw.rect(self.screen, self.colors['text'], rect, 1)
text_surface = self.text_font.render(text, True, self.colors['text'])
text_rect = text_surface.get_rect(center=rect.center)
self.screen.blit(text_surface, text_rect)
def validate_input(self, param: Dict[str, Any], value: str) -> Optional[Any]:
"""Validate and convert input value."""
try:
if param['type'] == 'int':
val = int(value)
else:
val = float(value)
if val < param['min'] or val > param['max']:
return None
return val
except:
return None
def run(self) -> Optional[Dict[str, Any]]:
"""Run the configuration UI. Returns the config dict if saved, None if cancelled."""
running = True
save_clicked = False
mouse_pos = (0, 0)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos
# Check parameter inputs
y = 100 - self.scroll_offset
for name, param in self.parameters.items():
input_rect = pygame.Rect(300, y, 200, 30)
if input_rect.collidepoint(mouse_pos):
self.active_input = name
self.input_text = str(param['value'])
y += 60
# Check buttons
save_rect = pygame.Rect(self.width//2 - 150, self.height - 60, 140, 40)
cancel_rect = pygame.Rect(self.width//2 + 10, self.height - 60, 140, 40)
if save_rect.collidepoint(mouse_pos):
self.save_config()
save_clicked = True
running = False
elif cancel_rect.collidepoint(mouse_pos):
running = False
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 4: # Mouse wheel up
self.scroll_offset = max(0, self.scroll_offset - 30)
elif event.button == 5: # Mouse wheel down
self.scroll_offset = min(self.max_scroll, self.scroll_offset + 30)
elif event.type == pygame.KEYDOWN:
if self.active_input is not None:
if event.key == pygame.K_RETURN:
param = self.parameters[self.active_input]
if val := self.validate_input(param, self.input_text):
param['value'] = val
self.active_input = None
elif event.key == pygame.K_BACKSPACE:
self.input_text = self.input_text[:-1]
else:
if event.unicode.isnumeric() or event.unicode == '.':
self.input_text += event.unicode
# Draw UI
self.screen.fill(self.colors['background'])
# Title
title = "Training Configuration"
title_surface = self.title_font.render(title, True, self.colors['highlight'])
title_rect = title_surface.get_rect(midtop=(self.width//2, 20))
self.screen.blit(title_surface, title_rect)
# Parameters
y = 100 - self.scroll_offset
for name, param in self.parameters.items():
if 0 <= y <= self.height - 100:
# Parameter name and description
name_surface = self.header_font.render(name, True, self.colors['text'])
desc_surface = self.text_font.render(param['description'], True, self.colors['text'])
self.screen.blit(name_surface, (20, y))
self.screen.blit(desc_surface, (20, y + 30))
# Input field
input_rect = pygame.Rect(300, y, 200, 30)
self.draw_text_input(input_rect, param['value'], name == self.active_input)
y += 60
# Buttons
save_rect = pygame.Rect(self.width//2 - 150, self.height - 60, 140, 40)
cancel_rect = pygame.Rect(self.width//2 + 10, self.height - 60, 140, 40)
save_hover = save_rect.collidepoint(mouse_pos)
cancel_hover = cancel_rect.collidepoint(mouse_pos)
self.draw_button(save_rect, "Save", save_hover)
self.draw_button(cancel_rect, "Cancel", cancel_hover)
pygame.display.flip()
pygame.quit()
if save_clicked:
return {key: param['value'] for key, param in self.parameters.items()}
return None
+70
View File
@@ -0,0 +1,70 @@
"""
AI Controller for Snake Game
This module provides the AI controller that uses trained models to play the game.
It handles model loading, state processing, and decision making during gameplay.
"""
import os
import numpy as np
from stable_baselines3 import PPO
from ai.environment import SnakeEnv, Direction
class AIController:
"""AI controller that uses trained models to play the game."""
def __init__(self, difficulty: str = "medium"):
"""
Initialize the AI controller.
Args:
difficulty: "easy", "medium", or "hard"
"""
self.difficulty = difficulty
self.model = None
self.env = SnakeEnv() # For state processing
self._load_model()
def _load_model(self):
"""Load the appropriate model based on difficulty."""
model_path = f"models/{self.difficulty}/best_model.zip"
if not os.path.exists(model_path):
# Fall back to final model if best model doesn't exist
model_path = f"models/{self.difficulty}/final_model.zip"
if not os.path.exists(model_path):
raise FileNotFoundError(
f"No model found for difficulty {self.difficulty}. "
"Please train the model first."
)
self.model = PPO.load(model_path)
def get_action(self, game_state: dict) -> Direction:
"""
Get the next action based on the current game state.
Args:
game_state: Dictionary containing:
- snake: Snake object
- food: Food object
- width: Game width
- height: Game height
Returns:
Direction enum indicating the chosen action
"""
# Update environment with current game state
self.env.snake = game_state["snake"]
self.env.food = game_state["food"]
self.env.width = game_state["width"]
self.env.height = game_state["height"]
# Get state observation
state = self.env._get_state()
# Get action from model
action, _ = self.model.predict(state, deterministic=True)
# Convert action index to Direction
return self.env.action_space[action]
+787
View File
@@ -0,0 +1,787 @@
"""
Snake Game Environment for Reinforcement Learning
This module provides a gym-like interface for training AI agents to play the snake game.
It includes:
- State observation space
- Action space
- Reward system
- Environment dynamics
"""
import numpy as np
import random
import gymnasium as gym
from gymnasium import spaces
from typing import Tuple, List, Dict, Any, Optional
import pygame
from src.core import Snake
from src.core import Direction
from src.core import GameSession
from src.ui import GameArea
from src.config import GameRules
def manhattan_distance(pos1: Tuple[int, int], pos2: Tuple[int, int]) -> int:
"""Calculate Manhattan distance between two points."""
return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1])
def manhattan_distance_wrap(pos1: Tuple[int, int], pos2: Tuple[int, int], size: int) -> int:
"""Calculate Manhattan distance between two points with wrap-around."""
dx = abs(pos1[0] - pos2[0])
dy = abs(pos1[1] - pos2[1])
return min(dx, size - dx) + min(dy, size - dy)
class SnakeEnv(gym.Env):
"""A Gymnasium environment for training snake AI agents."""
metadata = {"render_modes": ["human", "rgb_array"], "render_fps": 30}
def __init__(self, size=30, render_mode=None, difficulty="easy"):
super().__init__()
self.size = size
self.render_mode = render_mode
self.difficulty = difficulty
# Action to Direction mapping
self.action_to_direction = {
0: Direction.UP,
1: Direction.RIGHT,
2: Direction.DOWN,
3: Direction.LEFT
}
# Direction to index mapping for one-hot encoding
self.direction_to_index = {
Direction.UP: 0,
Direction.RIGHT: 1,
Direction.DOWN: 2,
Direction.LEFT: 3
}
# Initialize reward scales with emphasis on precision
self.reward_scales = {
'food': 20.0, # Base food reward (will be scaled exponentially)
'death': -5.0, # Reduced death penalty to encourage exploration
'distance': 0.5, # Increased distance reward
'survival': -0.01, # Small survival penalty
'milestone': 10.0, # Larger milestone rewards
'efficiency': 0.2, # Small efficiency reward
'exploration': 0.5, # Increased exploration reward
'safety': 1.0, # Safety reward for avoiding danger
'timeout': -1.0, # Reduced timeout penalty
'wrap_bonus': 0.2, # Small wrap-around bonus
'near_miss': -0.1, # Very small near miss penalty
'repetitive': -2 # Increased base penalty for repetitive movement
}
# Near miss detection
self.near_miss_threshold = 1 # Only penalize very close misses
# Time limit parameters - more lenient
self.base_time_limit = 200 # Double base time limit
self.length_time_bonus = 100 # Double length bonus
self.max_time_limit = 1000 # Much longer maximum time
# Exploration decay
self.initial_exploration_bonus = 2.0 # Higher initial exploration
self.exploration_decay = 0.9995 # Slower decay
self.min_exploration_bonus = 0.5 # Higher minimum exploration
self.current_exploration_bonus = self.initial_exploration_bonus
self.total_episodes = 0 # Track number of episodes for decay
# Curriculum learning parameters
self.curriculum_stage = 0
self.success_threshold = {
0: 3, # Stage 0: Basic movement (need more consistent success)
1: 5, # Stage 1: Food collection
2: 7, # Stage 2: Longer snake
3: 10 # Stage 3: Full difficulty
}
self.consecutive_successes = 0
self.stage_requirements = {
0: 1, # Stage 0: Get one food
1: 3, # Stage 1: Get three food
2: 5, # Stage 2: Get five food
3: 7 # Stage 3: Get seven food
}
# Dynamic episode length based on curriculum stage
self.base_max_steps = 300 # More steps for exploration
self.max_steps = self.base_max_steps
# Window dimensions for rendering
self.window_width = 1024
self.window_height = 768
# Create game area and rules
self.game_area = GameArea(self.window_width, self.window_height)
self.rules = GameRules()
self.rules.wrap_around = False # No wrap-around for AI training
# Define action and observation spaces
self.action_space = spaces.Discrete(4) # Up, Right, Down, Left
num_channels = 26 # Total number of channels we created in _get_normalized_observation
self.observation_space = spaces.Box(
low=0,
high=1,
shape=(num_channels, size, size), # (channels, height, width)
dtype=np.float32
)
# Game session
self.session = None
self.steps = 0
self.steps_since_food = 0
self.current_time = 0
self.last_score = 0
self.last_distance = float('inf')
self.last_food_steps = 0
self.steps_since_direction_change = 0 # Track steps since last direction change
self.last_direction = None # Track previous direction
self.recent_positions = []
self.steps_in_same_direction = 0 # Track steps without direction change
self.last_min_food_distance = float('inf') # Initialize minimum distance tracking
# For rendering
self.window = None
self.clock = None
self.score_milestone_rewards = {5: 10.0, 10: 20.0, 15: 30.0} # Bonus rewards at score milestones
self.last_milestone = 0 # Track last milestone reached
self.base_survival_penalty = -1.0 # Much larger constant penalty per step
# Movement control parameters
self.max_direction_steps = 10 # Reduced from 20 to 10
self.direction_step_increase = 2 # Reduced from 5 to 2
self.min_safe_turns = 2 # Reduced from 3 to 2
self.repetitive_threshold = 10 # Base threshold before repetitive penalty kicks in
self.repetitive_scale = 1.2 # Base scale for penalty growth
self.repetitive_wrap_scale = 2.0 # Much faster growth rate in wrap mode
self.max_repetitive_penalty = -5.0 # Increased maximum repetitive movement penalty
# Initialize base rewards with adjusted values
rewards = {
'food': 0.0,
'death': 0.0,
'distance': 0.0,
'survival': self.base_survival_penalty * 0.5,
'direction': 0.0,
'efficiency': 0.0,
'progress': 0.0,
'alignment': 0.0,
'repetitive': 0.0
}
def _get_normalized_observation(self) -> np.ndarray:
"""
Create a multi-channel 2D observation from the game state.
Spatial channels encode the grid layout (snake & food),
while extra scalar features are broadcast over additional channels.
"""
state = self.session.get_state()
snake_body = state["snake_body"]
food_position = state["food_position"]
head = snake_body[0]
body = snake_body
# --- Spatial Channels ---
# Channel 0: Snake positions (1 for snake, 0 otherwise)
snake_channel = np.zeros((self.size, self.size), dtype=np.float32)
for pos in snake_body:
snake_channel[pos[1], pos[0]] = 1.0
assert pos[0] < self.size and pos[1] < self.size, \
f"Snake position {pos} exceeds grid size {self.size}"
# Channel 1: Food position
food_channel = np.zeros((self.size, self.size), dtype=np.float32)
food_channel[food_position[1], food_position[0]] = 1.0
# --- Auxiliary Scalar Features ---
# Compute distances and apply wrap-around adjustments
dx = food_position[0] - head[0]
dy = food_position[1] - head[1]
if self.rules.wrap_around:
if dx > self.size/2:
wrap_dx = dx - self.size
elif dx < -self.size/2:
wrap_dx = dx + self.size
else:
wrap_dx = dx
if dy > self.size/2:
wrap_dy = dy - self.size
elif dy < -self.size/2:
wrap_dy = dy + self.size
else:
wrap_dy = dy
else:
wrap_dx = dx
wrap_dy = dy
# Normalize
dx_norm = dx / self.size
dy_norm = dy / self.size
wrap_dx_norm = wrap_dx / self.size
wrap_dy_norm = wrap_dy / self.size
# Danger indicators (vector of 4 values)
dangers = self._get_danger_observations_all_directions(head, body)
# Other auxiliary scalar features
snake_length_norm = len(body) / (self.size**2)
# One-hot encode current direction
direction_one_hot = [0.0] * 4
direction_one_hot[self.direction_to_index[state["snake_direction"]]] = 1.0
# One-hot encode relative food direction
food_dir = [0.0] * 4
if abs(dx_norm) > abs(dy_norm):
if dx_norm > 0:
food_dir[self.direction_to_index[Direction.RIGHT]] = 1.0
else:
food_dir[self.direction_to_index[Direction.LEFT]] = 1.0
else:
if dy_norm > 0:
food_dir[self.direction_to_index[Direction.DOWN]] = 1.0
else:
food_dir[self.direction_to_index[Direction.UP]] = 1.0
current_time_limit = min(
self.max_time_limit,
self.base_time_limit + (len(body) - 1) * self.length_time_bonus
)
time_pressure = np.clip(self.steps_since_food / current_time_limit, 0, 1)
wrap_mode = float(self.rules.wrap_around)
progress = min(1.0, len(body) / 10)
recent_food = min(1.0, self.steps_since_food / 50)
curriculum_stage_norm = float(self.curriculum_stage) / 3
advanced_length = float(len(body) > 5)
manhattan_norm = min(1.0, manhattan_distance(head, food_position) / (self.size * 2))
# --- Create "broadcasted" channels for each scalar ---
def broadcast_channel(value):
return np.full((self.size, self.size), value, dtype=np.float32)
dx_channel = broadcast_channel(dx_norm)
dy_channel = broadcast_channel(dy_norm)
wrap_dx_channel = broadcast_channel(wrap_dx_norm)
wrap_dy_channel = broadcast_channel(wrap_dy_norm)
snake_length_chan = broadcast_channel(snake_length_norm)
time_pressure_chan = broadcast_channel(time_pressure)
wrap_mode_chan = broadcast_channel(wrap_mode)
progress_chan = broadcast_channel(progress)
recent_food_chan = broadcast_channel(recent_food)
curriculum_chan = broadcast_channel(curriculum_stage_norm)
advanced_length_chan = broadcast_channel(advanced_length)
manhattan_chan = broadcast_channel(manhattan_norm)
# For one-hot features, create one channel per value
direction_channels = [broadcast_channel(v) for v in direction_one_hot]
food_dir_channels = [broadcast_channel(v) for v in food_dir]
# For dangers, one channel per direction (4 channels)
danger_channels = [broadcast_channel(d) for d in dangers]
# --- Stack all channels ---
# You can adjust the channel order as desired.
channels = [
snake_channel, # Channel 0
food_channel, # Channel 1
dx_channel, # Channel 2
dy_channel, # Channel 3
wrap_dx_channel, # Channel 4
wrap_dy_channel, # Channel 5
]
channels.extend(danger_channels) # Channels 6-9
channels.append(snake_length_chan) # Channel 10
channels.extend(direction_channels) # Channels 11-14
channels.extend(food_dir_channels) # Channels 15-18
channels.append(time_pressure_chan) # Channel 19
channels.append(wrap_mode_chan) # Channel 20
channels.append(progress_chan) # Channel 21
channels.append(recent_food_chan) # Channel 22
channels.append(curriculum_chan) # Channel 23
channels.append(advanced_length_chan) # Channel 24
channels.append(manhattan_chan) # Channel 25
# Final observation: shape (num_channels, size, size)
observation = np.stack(channels, axis=0)
return np.clip(observation, 0, 1)
def _get_danger_observations_all_directions(self, head: Tuple[int, int], body: List[Tuple[int, int]]) -> List[float]:
"""Get danger observations in all four directions."""
dangers = [0.0] * 4 # [UP, RIGHT, DOWN, LEFT]
# Check each direction
directions = [Direction.UP, Direction.RIGHT, Direction.DOWN, Direction.LEFT]
for i, direction in enumerate(directions):
dx, dy = direction.to_vector()
next_pos = (head[0] + dx, head[1] + dy)
# Check wall collision
if not self.rules.wrap_around:
if (next_pos[0] < 0 or next_pos[0] >= self.size or
next_pos[1] < 0 or next_pos[1] >= self.size):
dangers[i] = 1.0
continue
else:
next_pos = (next_pos[0] % self.size, next_pos[1] % self.size)
# Check self collision
if next_pos in body[1:]:
dangers[i] = 1.0
return dangers
def reset(self, seed=None, options=None):
"""Reset with curriculum-based difficulty and exploration decay."""
# Call parent reset without unpacking
super().reset(seed=seed)
if seed is not None:
random.seed(seed)
np.random.seed(seed)
# Update exploration bonus
self.total_episodes += 1
self.current_exploration_bonus = max(
self.min_exploration_bonus,
self.initial_exploration_bonus * (self.exploration_decay ** self.total_episodes)
)
# Initialize game session with curriculum-appropriate settings
self.session = GameSession(
self.size,
self.size,
self.rules
)
# Reset counters
self.steps = 0
self.steps_since_food = 0
self.current_time = 0
self.last_score = 0
self.last_distance = float('inf')
self.last_direction = self.session.get_state()["snake_direction"] # Track initial direction
self.recent_positions = []
self.steps_in_same_direction = 0 # Track steps without direction change
self.last_min_food_distance = float('inf') # Initialize minimum distance tracking
# Get initial observation
observation = self._get_normalized_observation()
info = {
"curriculum_stage": self.curriculum_stage,
"exploration_bonus": self.current_exploration_bonus
}
return observation, info
def _calculate_area_penalty(self, head_pos):
"""Calculate penalty for staying in a small area."""
# Add current position to history
self.recent_positions.append(head_pos)
if len(self.recent_positions) > self.max_recent_positions:
self.recent_positions.pop(0)
if len(self.recent_positions) < 10: # Need minimum history to calculate
return 0.0
# Calculate bounding box of recent positions
x_coords = [p[0] for p in self.recent_positions]
y_coords = [p[1] for p in self.recent_positions]
area_width = max(x_coords) - min(x_coords) + 1
area_height = max(y_coords) - min(y_coords) + 1
area = area_width * area_height
# Calculate unique positions visited
unique_positions = len(set(self.recent_positions))
# Penalize small areas and repeated positions
area_penalty = 0.0
if area < 9: # 3x3 grid or smaller
area_penalty = -0.2 * (9 - area) / 8 # Max penalty -0.2 for 1x1 area
# Additional penalty for revisiting same positions frequently
repetition_penalty = -0.3 * (1 - unique_positions / len(self.recent_positions))
return area_penalty + repetition_penalty
def step(self, action):
"""Improved reward structure with length-aware exploration."""
self.steps += 1
self.steps_since_food += 1
# Calculate current time limit based on snake length
snake_length = len(self.session.get_state()["snake_body"])
current_time_limit = min(
self.max_time_limit,
self.base_time_limit + (snake_length - 1) * self.length_time_bonus
)
# Get state before action
prev_state = self.session.get_state()
prev_head = prev_state["snake_head"]
prev_food_dist = manhattan_distance(prev_head, prev_state["food_position"])
if self.rules.wrap_around:
prev_food_dist = min(prev_food_dist,
manhattan_distance_wrap(prev_head, prev_state["food_position"], self.size))
# Convert action to Direction and apply
direction = self.action_to_direction[int(action)]
# Update game state
state, base_reward, done = self.session.step(direction, self.current_time)
# Initialize reward components
rewards = {
'food': 0.0,
'death': 0.0,
'distance': 0.0,
'survival': 0.0,
'milestone': 0.0,
'efficiency': 0.0,
'exploration': 0.0,
'safety': 0.0,
'timeout': 0.0,
'direction': 0.0,
'repetitive': 0.0
}
# Get current state info
curr_head = state["snake_body"][0]
curr_food = state["food_position"]
curr_food_dist = manhattan_distance(curr_head, curr_food)
if self.rules.wrap_around:
curr_food_dist = min(curr_food_dist,
manhattan_distance_wrap(curr_head, curr_food, self.size))
# Update current time
self.current_time += self.session.move_cooldown
# Food reward with exponential scaling based on snake length
food_eaten = state["score"] > prev_state["score"]
if food_eaten:
# Reset timer when food is eaten
self.steps_since_food = 0
# Calculate exponential food reward
base_food_reward = self.reward_scales['food']
length_multiplier = 1.2 ** (len(state["snake_body"]) - 1) # 20% increase per length
rewards['food'] = base_food_reward * length_multiplier
# Add milestone rewards for achieving certain scores
if state["score"] in [5, 10, 15, 20]:
rewards['milestone'] = self.reward_scales['milestone'] * (state["score"] / 5)
else:
# Only apply survival penalty if we haven't eaten food in a while
if self.steps_since_food > current_time_limit / 2:
penalty_factor = (self.steps_since_food - current_time_limit/2) / (current_time_limit/2)
rewards['survival'] = self.reward_scales['survival'] * penalty_factor
# Check if direction changed and update counters
direction_changed = direction != self.last_direction
if direction_changed:
self.steps_in_same_direction = 0
else:
self.steps_in_same_direction += 1
# Apply growing penalty for repetitive movement
if self.steps_in_same_direction > (self.repetitive_threshold - 5 if self.rules.wrap_around else self.repetitive_threshold):
excess_steps = self.steps_in_same_direction - (self.repetitive_threshold - 5 if self.rules.wrap_around else self.repetitive_threshold)
# Use much faster growth rate in wrap-around mode
growth_rate = self.repetitive_wrap_scale if self.rules.wrap_around else self.repetitive_scale
repetitive_penalty = self.reward_scales['repetitive'] * (growth_rate ** excess_steps)
# Apply additional multiplier in wrap-around mode that grows with steps
if self.rules.wrap_around:
wrap_multiplier = 1.0 + (excess_steps * 0.5) # Multiplier grows with each step
repetitive_penalty *= wrap_multiplier
rewards['repetitive'] = repetitive_penalty # No maximum cap - let it grow unbounded in wrap-around mode
else:
# Cap the penalty when not in wrap-around mode
rewards['repetitive'] = max(repetitive_penalty, self.max_repetitive_penalty)
self.last_direction = direction
# Check for timeout or stuck in loop - only if we haven't just eaten food
if (self.steps_since_food >= current_time_limit and not food_eaten):
done = True
rewards['timeout'] = self.reward_scales['timeout']
# Scale timeout penalty based on distance to food
if curr_food_dist < 5: # Harsher penalty for timing out near food
rewards['timeout'] *= 1.5
# Additional penalty for getting stuck in a loop
if self.steps_in_same_direction >= 30: # Also update this threshold
rewards['timeout'] *= 1.2
# Death penalty - calculate AFTER food rewards
if done and not self.steps_since_food >= current_time_limit:
base_death_penalty = self.reward_scales['death']
# Check if death was due to self-collision
if curr_head in state["snake_body"][1:]:
# Base multiplier for self-collision
self_collision_multiplier = 2.0
# Additional penalty scaling with score
# At score 5: 2.5x penalty
# At score 10: 3.0x penalty
# At score 15: 3.5x penalty
score_multiplier = 1.0 + (state["score"] / 10)
# Apply both multipliers
rewards['death'] = base_death_penalty * self_collision_multiplier * score_multiplier
# Additional penalty if we died near food
if curr_food_dist < 5:
rewards['death'] *= 1.5 # Even harsher if we collide with ourselves near food
else:
# For wall collisions, keep original scaling but make it less punishing at higher scores
rewards['death'] = base_death_penalty * (1.0 - min(0.5, state["score"] / 20))
# Add an immediate negative reward for losing potential score
potential_loss_penalty = -0.5 * state["score"] # Larger penalty for dying with higher scores
rewards['death'] += potential_loss_penalty
# Track minimum distance to food and check for near misses
if curr_food_dist < self.last_min_food_distance:
self.last_min_food_distance = curr_food_dist
elif curr_food_dist > self.last_min_food_distance:
# We're moving away from our closest approach
if self.last_min_food_distance <= self.near_miss_threshold:
# We got very close but missed
rewards['distance'] += self.reward_scales['near_miss']
self.last_min_food_distance = float('inf') # Reset tracking
# Progressive distance reward - more reward for getting closer when near food
distance_change = prev_food_dist - curr_food_dist
if curr_food_dist < 5: # When close to food
distance_multiplier = 2.0 # Double the reward/penalty
else:
distance_multiplier = 1.0
rewards['distance'] = distance_change * self.reward_scales['distance'] * distance_multiplier
# Calculate direction penalty
if curr_food_dist <= 5: # Only apply when close to food
# Calculate optimal direction to food
dx = curr_food[0] - curr_head[0]
dy = curr_food[1] - curr_head[1]
if self.rules.wrap_around:
# Adjust for wrap-around
if dx > self.size/2: dx -= self.size
elif dx < -self.size/2: dx += self.size
if dy > self.size/2: dy -= self.size
elif dy < -self.size/2: dy += self.size
# Determine optimal direction(s)
optimal_directions = []
if abs(dx) > abs(dy):
if dx > 0: optimal_directions.append(Direction.RIGHT)
elif dx < 0: optimal_directions.append(Direction.LEFT)
if abs(dy) >= abs(dx):
if dy > 0: optimal_directions.append(Direction.DOWN)
elif dy < 0: optimal_directions.append(Direction.UP)
# Base penalty scales with proximity (closer = higher penalty)
base_penalty = (6 - curr_food_dist) * 0.1 # Scales from 0.1 to 0.5
if direction not in optimal_directions:
# Check if we're moving directly away from food
opposite_dirs = {
Direction.UP: Direction.DOWN,
Direction.DOWN: Direction.UP,
Direction.LEFT: Direction.RIGHT,
Direction.RIGHT: Direction.LEFT
}
optimal_opposites = [opposite_dirs[d] for d in optimal_directions]
if direction in optimal_opposites:
# Double penalty for moving directly away from food
rewards['direction'] = -2 * base_penalty
else:
# Regular penalty for suboptimal direction
rewards['direction'] = -base_penalty
elif curr_food_dist <= 2: # Small reward for correct direction when very close
rewards['direction'] = 0.1
# Efficiency reward - encourage purposeful movement
if not done and self.steps_since_food < 50: # Only apply when actively hunting
rewards['efficiency'] = self.reward_scales['efficiency'] * (1.0 - self.steps_since_food / 50)
# Calculate final reward - simple sum of components
reward = sum(rewards.values())
# Get observation
observation = self._get_normalized_observation()
# No more episode-based truncation
truncated = False
# Include reward components and exploration info in info dict for monitoring
info = {
"score": state["score"],
"reward_components": rewards,
"exploration_bonus": self.current_exploration_bonus,
"direction_changed": direction_changed,
"steps_in_same_direction": self.steps_in_same_direction,
"snake_length": snake_length,
"steps": self.steps # Include total steps for monitoring
}
return observation, reward, done, truncated, info
def render(self):
"""Render the environment."""
if self.window is None and self.render_mode == "human":
pygame.init()
self.window = pygame.display.set_mode((self.window_width, self.window_height))
pygame.display.set_caption("Snake Environment")
self.clock = pygame.time.Clock()
if self.window is not None:
self.window.fill((0, 0, 0))
# Draw game area
self.game_area.draw(self.window)
# Draw game session
self.session.render(self.window, self.game_area)
# Draw score
font = pygame.font.Font(None, 36)
score_text = f"Score: {self.session.score}"
score_surface = font.render(score_text, True, (0, 255, 0))
score_rect = score_surface.get_rect(midtop=(self.window_width // 2, 20))
self.window.blit(score_surface, score_rect)
pygame.display.flip()
self.clock.tick(self.metadata["render_fps"])
if self.render_mode == "rgb_array":
return np.transpose(
np.array(pygame.surfarray.pixels3d(self.window)),
axes=(1, 0, 2)
)
def close(self):
"""Close the environment."""
if self.window is not None:
pygame.quit()
self.window = None
def get_state(self) -> Dict:
"""Get the current game state."""
state = self.session.get_state()
state['steps_since_food'] = self.steps_since_food
# Calculate and include current time limit
snake_length = len(state["snake_body"])
current_time_limit = min(
self.max_time_limit,
self.base_time_limit + (snake_length - 1) * self.length_time_bonus
)
state['current_time_limit'] = current_time_limit
return state
def _get_adjacent_positions(self, position: Tuple[int, int]) -> List[Tuple[int, int]]:
"""
Get all adjacent positions to the given position.
Args:
position: Current position (x, y)
Returns:
List of adjacent positions [(x, y), ...]
Raises:
ValueError: If position is None or not a tuple of 2 integers
ValueError: If position coordinates are not integers
"""
if not position or not isinstance(position, tuple) or len(position) != 2:
raise ValueError("Position must be a tuple of 2 coordinates")
try:
x, y = int(position[0]), int(position[1])
except (TypeError, ValueError):
raise ValueError("Position coordinates must be integers")
# Get positions in all 4 directions (up, right, down, left)
adjacent = [
(x, y - 1), # up
(x + 1, y), # right
(x, y + 1), # down
(x - 1, y) # left
]
# Validate size attribute exists and is positive integer
if not hasattr(self, 'size') or not isinstance(self.size, int) or self.size <= 0:
raise ValueError("Environment size must be a positive integer")
# If wrap-around is enabled, adjust out-of-bounds positions
if hasattr(self, 'rules') and hasattr(self.rules, 'wrap_around') and self.rules.wrap_around:
adjacent = [
(pos[0] % self.size, pos[1] % self.size)
for pos in adjacent
]
return adjacent
# Otherwise, only return positions that are within bounds
return [
(pos[0], pos[1]) for pos in adjacent
if 0 <= pos[0] < self.size and 0 <= pos[1] < self.size
]
def _update_curriculum(self, score: int, done: bool) -> None:
"""Update curriculum stage based on agent's performance."""
if done:
if score >= self.stage_requirements[self.curriculum_stage]:
self.consecutive_successes += 1
else:
self.consecutive_successes = 0
# Check for stage advancement
if (self.curriculum_stage < 3 and
self.consecutive_successes >= self.success_threshold[self.curriculum_stage]):
self.curriculum_stage += 1
self.consecutive_successes = 0
# Increase episode length with curriculum stage
self.max_steps = self.base_max_steps * (1 + self.curriculum_stage * 0.5)
def _get_curriculum_rules(self) -> GameRules:
"""Get game rules appropriate for current curriculum stage."""
rules = GameRules()
# Adjust rules based on curriculum stage
if self.curriculum_stage == 0:
rules.wrap_around = True # Make it easier to avoid walls
rules.speed_increase = False
rules.initial_move_cooldown = 200 # Much slower movement
elif self.curriculum_stage == 1:
rules.wrap_around = True
rules.speed_increase = False # Still no speed increase
rules.initial_move_cooldown = 150
elif self.curriculum_stage == 2:
rules.wrap_around = True # Keep wrap-around until final stage
rules.speed_increase = True
rules.initial_move_cooldown = 120
else: # Stage 3
rules.wrap_around = False
rules.speed_increase = True
rules.initial_move_cooldown = 100
return rules
# Register the environment with Gymnasium
from gymnasium.envs.registration import register
register(
id='Snake-v0',
entry_point='src.ai.environment:SnakeEnv',
kwargs={
'size': 30,
'render_mode': None,
'difficulty': 'easy'
}
)
+93
View File
@@ -0,0 +1,93 @@
import gym
import numpy as np
import torch
import torch.nn as nn
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
class CustomRecurrentCNN(BaseFeaturesExtractor):
"""
A simple CNN with an LSTM layer added on top. This enables the network to keep an internal
memory of past observations so that it can adapt to changing rules/environment dynamics.
"""
def __init__(self, observation_space, features_dim=512):
# Initialize with a features_dim that matches the LSTM's output.
super(CustomRecurrentCNN, self).__init__(observation_space, features_dim)
# Calculate the expected CNN output size first
n_input_channels = observation_space.shape[0] # Number of input channels
self.cnn = nn.Sequential(
# Layer 1: (n_channels, 30, 30) -> (32, 15, 15)
nn.Conv2d(n_input_channels, 32, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
# Layer 2: (32, 15, 15) -> (64, 8, 8)
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
# Layer 3: (64, 8, 8) -> (64, 4, 4)
nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),
nn.ReLU(),
nn.Flatten()
)
# Calculate CNN output dimension using a dummy forward pass
with torch.no_grad():
dummy_input = torch.zeros(1, *observation_space.shape)
cnn_output = self.cnn(dummy_input)
self._cnn_output_dim = cnn_output.shape[1] # Should be 64 * 4 * 4 = 1024
# Add linear layer to reduce CNN output to desired feature dimension
self.fc = nn.Linear(self._cnn_output_dim, 256)
# LSTM layer
self.lstm = nn.LSTM(256, features_dim, batch_first=True)
def forward(self, observations):
# Pass through CNN: (batch, channels, height, width) -> (batch, cnn_features)
cnn_out = self.cnn(observations)
# Pass through linear layer: (batch, cnn_features) -> (batch, 256)
fc_out = self.fc(cnn_out)
# Add time dimension for LSTM: (batch, 256) -> (batch, 1, 256)
lstm_input = fc_out.unsqueeze(1)
# LSTM: (batch, 1, 256) -> (batch, 1, features_dim)
lstm_out, _ = self.lstm(lstm_input)
# Remove time dimension: (batch, 1, features_dim) -> (batch, features_dim)
return lstm_out.squeeze(1)
class CustomCNN(BaseFeaturesExtractor):
"""
Custom feature extractor for the snake environment.
Uses fully connected layers since our input is a 1D vector of normalized features.
"""
def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 512):
super().__init__(observation_space, features_dim)
self.input_dim = int(np.prod(observation_space.shape))
self.cnn = nn.Sequential(
nn.Linear(self.input_dim, 512),
nn.ReLU(),
nn.BatchNorm1d(512),
nn.Linear(512, 512),
nn.ReLU(),
nn.BatchNorm1d(512),
nn.Linear(512, features_dim),
nn.ReLU(),
)
def forward(self, observations: torch.Tensor) -> torch.Tensor:
# Handle both single and batch observations
if len(observations.shape) == 1:
observations = observations.unsqueeze(0)
# Ensure the input dimension matches what we expect
flat_obs = observations.reshape(observations.shape[0], self.input_dim)
return self.cnn(flat_obs)
+423
View File
@@ -0,0 +1,423 @@
"""
Training script for Snake AI using Stable Baselines3.
This script sets up and trains RL agents using the SnakeEnv environment.
It supports multiple difficulty levels and provides real-time visualization
of the training process.
"""
import os
import time
import numpy as np
import torch
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import DummyVecEnv, SubprocVecEnv
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.utils import set_random_seed
from stable_baselines3.common.monitor import Monitor
import gymnasium as gym
import torch.nn as nn
import argparse
from queue import Queue
from threading import Thread
from typing import Dict, Any, Optional
import json
from queue import Empty
from src.ai.environment import SnakeEnv
from src.ai.visualize import run_dashboard
from src.ai.model_networks import CustomRecurrentCNN, CustomCNN
class VisualizationCallback(BaseCallback):
"""Callback for updating the training visualization."""
def __init__(self, viz_queue: Queue, total_timesteps: int, eval_freq: int = 1000, n_steps: int = 512, n_envs: int = 32, initial_timesteps: int = 0):
super().__init__()
self.viz_queue = viz_queue
self.total_timesteps = total_timesteps
self.eval_freq = eval_freq
self.n_steps = n_steps
self.n_envs = n_envs
self.initial_timesteps = initial_timesteps # Store initial timesteps
# Training metrics
self.episode_rewards = []
self.episode_lengths = []
# Evaluation metrics
self.eval_scores = []
self.high_score = 0
self.recent_high_score = 0
# Current episode tracking
self.current_reward = 0
self.current_length = 0
# Evaluation games (one with wrap, one without)
self.eval_envs = [
Monitor(SnakeEnv(render_mode="rgb_array")) for _ in range(2)
]
self.eval_envs[0].unwrapped.rules.wrap_around = False
self.eval_envs[1].unwrapped.rules.wrap_around = True
self.eval_obs = [None, None]
self.eval_done = [True, True]
self.eval_scores_current = [0, 0]
# Real-time demo environment
self.demo_env = Monitor(SnakeEnv(render_mode="rgb_array"))
self.demo_env.unwrapped.rules.wrap_around = True
self.demo_obs = None
self.demo_done = True
self.last_demo_time = 0
self.demo_speed = 50
def _on_step(self) -> bool:
"""Update visualization on each step."""
try:
current_time = time.time() * 1000 # Convert to milliseconds
# Update episode tracking
self.current_length += 1
reward = self.locals.get("rewards", [0])[0]
self.current_reward += reward
# Get action probabilities and value estimate for demo game
if self.demo_obs is not None:
# Ensure proper tensor shape (batch_size, obs_dim)
demo_obs_tensor = torch.as_tensor(self.demo_obs).float()
if len(demo_obs_tensor.shape) == 1:
demo_obs_tensor = demo_obs_tensor.unsqueeze(0)
# Move tensor to same device as model's policy
device = self.model.policy.device
demo_obs_tensor = demo_obs_tensor.to(device)
with torch.no_grad():
# Get action distribution and value estimate
dist = self.model.policy.get_distribution(demo_obs_tensor)
action_probs = dist.distribution.probs
value_estimate = self.model.policy.predict_values(demo_obs_tensor)
# Move results back to CPU and get first item (since we added batch dimension)
action_probs = action_probs[0].cpu().numpy()
value_estimate = value_estimate[0].cpu().numpy()
else:
action_probs = np.zeros(4)
value_estimate = np.array([0.0])
# Check if episode ended
dones = self.locals.get("dones", [False])
if any(dones):
self.episode_rewards.append(self.current_reward)
self.episode_lengths.append(self.current_length)
self.current_reward = 0
self.current_length = 0
# Run evaluation games (keep these deterministic as they're meant to show best performance)
for i, (env, obs, done) in enumerate(zip(self.eval_envs, self.eval_obs, self.eval_done)):
if done:
if obs is not None: # If this wasn't the first reset
self.eval_scores.append(self.eval_scores_current[i])
# Update high scores based on evaluation performance
self.high_score = max(self.high_score, self.eval_scores_current[i])
self.recent_high_score = max(self.recent_high_score, self.eval_scores_current[i])
self.eval_obs[i] = env.reset()[0]
self.eval_done[i] = False
self.eval_scores_current[i] = 0
eval_action, _ = self.model.predict(self.eval_obs[i], deterministic=True)
eval_action = eval_action.item() if hasattr(eval_action, 'item') else eval_action
self.eval_obs[i], _, done, truncated, info = env.step(eval_action)
self.eval_done[i] = done or truncated
# Update current evaluation score
self.eval_scores_current[i] = info.get("score", 0)
# Run real-time demo game
if current_time - self.last_demo_time >= self.demo_speed:
if self.demo_done:
self.demo_obs = self.demo_env.reset()[0]
self.demo_done = False
demo_action, _ = self.model.predict(self.demo_obs, deterministic=True)
demo_action = demo_action.item() if hasattr(demo_action, 'item') else demo_action
self.demo_obs, _, done, truncated, info = self.demo_env.step(demo_action)
self.demo_done = done or truncated
self.last_demo_time = current_time
# Get current states from actual training environments
# Sample one no-wrap and one wrap environment from the training environments
no_wrap_idx = 0 # First half are no-wrap
wrap_idx = self.n_envs // 2 # Second half are wrap
training_state_1 = self.training_env.get_attr("session")[no_wrap_idx].get_state()
training_state_1["wrap_around"] = False
training_state_2 = self.training_env.get_attr("session")[wrap_idx].get_state()
training_state_2["wrap_around"] = True
eval_state_1 = self.eval_envs[0].unwrapped.session.get_state()
eval_state_1["wrap_around"] = self.eval_envs[0].unwrapped.rules.wrap_around
eval_state_2 = self.eval_envs[1].unwrapped.session.get_state()
eval_state_2["wrap_around"] = self.eval_envs[1].unwrapped.rules.wrap_around
demo_state = self.demo_env.unwrapped.session.get_state()
demo_state["wrap_around"] = self.demo_env.unwrapped.rules.wrap_around
# Update viz_data
viz_data = {
'training_state': [training_state_1, training_state_2],
'eval_states': [eval_state_1, eval_state_2],
'demo_state': demo_state,
'weights_info': {
'action_probs': action_probs.tolist() if 'action_probs' in locals() else [0.25] * 4,
'value_estimate': float(value_estimate[0]) if 'value_estimate' in locals() else 0.0,
'action_labels': ['Up', 'Right', 'Down', 'Left']
},
'training_info': {
'total_timesteps': self.num_timesteps,
'initial_timesteps': self.initial_timesteps, # Add initial timesteps
'target_timesteps': self.total_timesteps,
'episode_reward': float(self.current_reward),
'mean_reward': float(np.mean(self.episode_rewards[-100:])) if self.episode_rewards else 0.0,
'episode_length': int(self.current_length),
'mean_length': float(np.mean(self.episode_lengths[-100:])) if self.episode_lengths else 0.0,
'mean_eval_score': float(np.mean(self.eval_scores[-100:])) if self.eval_scores else 0.0,
'rewards_history': self.episode_rewards[-1000:],
'lengths_history': self.episode_lengths[-1000:],
'eval_scores_history': self.eval_scores[-1000:],
'high_score': self.high_score,
'recent_high_score': self.recent_high_score
}
}
# Send update to visualization
self.viz_queue.put(('update', viz_data))
# Reset recent high score periodically
if self.num_timesteps % (self.n_steps * self.n_envs) == 0:
print(f"\nEvaluation High Score: {self.high_score}")
print(f"Recent Evaluation High Score: {self.recent_high_score}")
self.recent_high_score = 0
return True
except Exception as e:
print(f"Error in visualization callback: {e}")
import traceback
traceback.print_exc()
return True
def make_env(seed: int = 0, wrap_walls: bool = False) -> gym.Env:
"""Create a training environment.
Args:
seed: Random seed
wrap_walls: Whether snake can wrap around walls
"""
def _init() -> gym.Env:
env = SnakeEnv(render_mode=None)
env = Monitor(env)
# Set wrap-around mode
env.unwrapped.rules.wrap_around = wrap_walls
env.reset(seed=seed)
return env
set_random_seed(seed)
return _init
def train_model(
total_timesteps: int,
viz_queue: Queue,
model_path: Optional[str] = None,
cuda: bool = True,
learning_rate: float = 3e-4, # Standard PPO learning rate
batch_size: int = 256, # More reasonable batch size
n_envs: int = 16, # Balanced number of environments
n_steps: int = 2048 # Standard PPO steps
) -> None:
"""
Train the snake AI model.
Args:
total_timesteps: Number of timesteps to train for
viz_queue: Queue for sending visualization updates
model_path: Path to save/load the model
cuda: Whether to use CUDA for training
learning_rate: Learning rate for the optimizer
batch_size: Batch size for training
n_envs: Number of parallel environments
n_steps: Number of steps per environment
"""
try:
# Set up environments - half with wrap, half without
envs = []
for i in range(n_envs):
wrap_walls = i >= n_envs // 2 # Half the envs with wrap-around
envs.append(make_env(i, wrap_walls))
env = SubprocVecEnv(envs)
# PPO hyperparameters - adjusted for more stable learning
ppo_params = dict(
learning_rate=1e-4, # Slightly higher learning rate
n_steps=1024, # Shorter horizon for faster updates
batch_size=128, # Smaller batch size for more frequent updates
n_epochs=4, # Balanced number of epochs
gamma=0.98, # Slightly lower discount for more immediate rewards
gae_lambda=0.9, # Lower GAE lambda for more immediate advantage estimates
clip_range=0.1, # Smaller clip range for more conservative updates
clip_range_vf=0.1, # Also clip value function
normalize_advantage=True,
ent_coef=0.2, # Moderate entropy for exploration
vf_coef=0.8, # Balanced value function coefficient
max_grad_norm=0.3, # More conservative gradient clipping
target_kl=None,
verbose=1,
device="cuda" if cuda and torch.cuda.is_available() else "cpu"
)
# Create or load model with updated architecture
policy_kwargs = dict(
features_extractor_class=CustomRecurrentCNN, # Use the new recurrent extractor
features_extractor_kwargs=dict(features_dim=512), # You can adjust features_dim as needed
net_arch=dict(
pi=[512, 256, 128], # Policy network layers
vf=[512, 256, 128] # Value network layers
),
activation_fn=nn.ReLU,
normalize_images=False
)
# Track initial timesteps for progress tracking
initial_timesteps = 0
if model_path and os.path.exists(model_path):
print(f"Loading model from {model_path}")
try:
model = PPO.load(
model_path,
env=env,
custom_objects={"policy_kwargs": policy_kwargs},
**ppo_params
)
initial_timesteps = model.num_timesteps
print(f"Loaded model with {initial_timesteps:,} timesteps of training")
except Exception as e:
print(f"Failed to load model with error: {e}")
print("Creating new model instead")
model = PPO("CnnPolicy", env, policy_kwargs=policy_kwargs, **ppo_params)
else:
print("Creating new model")
model = PPO("CnnPolicy", env, policy_kwargs=policy_kwargs, **ppo_params)
# Set up visualization callback with initial timesteps
viz_callback = VisualizationCallback(
viz_queue=viz_queue,
total_timesteps=total_timesteps,
eval_freq=1000,
n_steps=n_steps,
n_envs=n_envs,
initial_timesteps=initial_timesteps # Pass initial timesteps to callback
)
# Training loop with stop check
should_stop = False
timesteps_per_batch = n_steps * n_envs
num_batches = total_timesteps // timesteps_per_batch
for i in range(num_batches):
if should_stop:
break
# Train for one batch
model.learn(
total_timesteps=timesteps_per_batch,
callback=viz_callback,
progress_bar=True,
reset_num_timesteps=False
)
# Check for stop signal from visualization
try:
while True: # Process all pending messages
msg_type, _ = viz_queue.get_nowait()
if msg_type == 'stop_training':
should_stop = True
break
except Empty:
pass
# Save model if training completed or interrupted
if model_path:
print(f"Saving model to {model_path}")
model.save(model_path)
except Exception as e:
print(f"Error in training process: {e}")
import traceback
traceback.print_exc()
finally:
# Clean up
env.close()
# Signal visualization to stop if we haven't already
viz_queue.put(('stop', None))
def main():
"""Main training script."""
parser = argparse.ArgumentParser(description="Train Snake AI")
parser.add_argument("--config", action="store_true",
help="Show configuration UI before training")
parser.add_argument("--model", type=str, default="models/snake_ai.zip",
help="Path to save/load model")
parser.add_argument("--no-cuda", action="store_true",
help="Disable CUDA training")
args = parser.parse_args()
# Get training configuration
if args.config:
from src.ai.config_ui import ConfigUI
config_ui = ConfigUI()
config = config_ui.run()
if config is None: # User cancelled
return
else:
# Load saved config or use defaults
config_file = "training_config.json"
if os.path.exists(config_file):
with open(config_file, 'r') as f:
config = json.load(f)
else:
config = {
'timesteps': 2000000,
'learning_rate': 0.0001,
'batch_size': 512,
'n_envs': 32,
'n_steps': 512
}
# Create visualization queue
viz_queue = Queue()
# Start visualization in separate thread
viz_thread = Thread(target=run_dashboard, args=(viz_queue,))
viz_thread.start()
# Start training with configuration
train_model(
total_timesteps=config['timesteps'],
viz_queue=viz_queue,
model_path=args.model,
cuda=not args.no_cuda,
learning_rate=config['learning_rate'],
batch_size=config['batch_size'],
n_envs=config['n_envs'],
n_steps=config['n_steps']
)
# Wait for visualization to finish
viz_thread.join()
if __name__ == "__main__":
main()
+540
View File
@@ -0,0 +1,540 @@
"""
Training Visualization Dashboard
This module provides a real-time visualization of the training process,
showing both the training metrics and evaluation games.
"""
import pygame
import numpy as np
from typing import Dict, Any, Optional, List, Tuple
import threading
from queue import Queue, Empty
import time
class TrainingDashboard:
def __init__(self, width: int = 1920, height: int = 1080):
"""Initialize the training dashboard."""
self.width = width
self.height = height
# Fonts
self.title_font = None
self.header_font = None
self.text_font = None
# Colors
self.colors = {
'background': (0, 0, 0),
'text': (200, 200, 200),
'highlight': (0, 255, 0),
'grid': (40, 40, 40),
'border': (0, 255, 0),
'snake': (0, 255, 0),
'food': (255, 0, 0),
'graph_bg': (20, 20, 20),
'graph_line': (0, 255, 0),
'graph_grid': (40, 40, 40)
}
# Layout
self.layout = {
'margin': 20,
'game_size': 400,
'graph_height': 200,
'metrics_width': 300
}
# Training metrics history
self.metrics_history = {
'rewards': [],
'scores': [],
'lengths': []
}
self.max_history = 1000
# Current state
self.current_state = None
self.eval_state = None
self.demo_state = None
self.training_info = None
self.model_info = None
# Performance tracking
self.frame_times = []
self.max_frame_times = 60
# Initialize the clock
self.clock = None
self.target_fps = 60
def run(self, update_queue: Queue) -> None:
"""Run the dashboard, processing updates from the queue."""
pygame.init()
try:
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("Snake AI Training Dashboard")
# Initialize fonts after pygame is initialized
self.title_font = pygame.font.Font(None, 48)
self.header_font = pygame.font.Font(None, 36)
self.text_font = pygame.font.Font(None, 24)
# Initialize clock
self.clock = pygame.time.Clock()
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
# Process updates from queue
try:
while True: # Process all available updates
update_type, data = update_queue.get_nowait()
if update_type == 'update':
self.update(data)
elif update_type == 'stop':
running = False
break
except Empty:
pass
# Render dashboard
self.render()
self.clock.tick(self.target_fps)
finally:
pygame.quit()
def update(self, data: Dict[str, Any]) -> None:
"""Update the dashboard with new data."""
self.current_state = data # Store entire data dict
if 'training_info' in data:
self.training_info = data['training_info']
# Update metrics history
for key in ['rewards', 'scores', 'lengths']:
if key in self.training_info:
self.metrics_history[key].append(self.training_info[key])
if len(self.metrics_history[key]) > self.max_history:
self.metrics_history[key].pop(0)
def draw_game_view(self, state: Dict[str, Any], position: Tuple[int, int], size: int, title: str) -> None:
"""Draw a game view at the specified position."""
if not state:
return
x, y = position
# Draw game area background
game_rect = pygame.Rect(x, y, size, size)
pygame.draw.rect(self.screen, self.colors['grid'], game_rect)
pygame.draw.rect(self.screen, self.colors['border'], game_rect, 2)
# Get time limit info directly from state
steps_since_food = state.get('steps_since_food', 0)
current_time_limit = state.get('current_time_limit', 100) # Default to base limit if not provided
time_left = max(0, current_time_limit - steps_since_food)
# Calculate cell size based on grid dimensions
cell_size = size // 30 # Assuming 30x30 grid
# Draw snake
if "snake_body" in state:
for segment in state["snake_body"]:
segment_rect = pygame.Rect(
x + segment[0] * cell_size,
y + segment[1] * cell_size,
cell_size, cell_size
)
pygame.draw.rect(self.screen, self.colors['snake'], segment_rect)
# Draw food
if "food_position" in state:
food_rect = pygame.Rect(
x + state["food_position"][0] * cell_size,
y + state["food_position"][1] * cell_size,
cell_size, cell_size
)
pygame.draw.rect(self.screen, self.colors['food'], food_rect)
# Draw score and timer above game area
score = state.get('score', 0)
score_text = f"Score: {score}"
timer_text = f"Time: {time_left}/{current_time_limit}" # Show both current and max time
combined_text = f"{score_text} | {timer_text}"
score_surface = self.text_font.render(combined_text, True, self.colors['text'])
score_rect = score_surface.get_rect(midtop=(x + size//2, y - 25))
self.screen.blit(score_surface, score_rect)
# Draw title below game area, including wrap mode for training view
if title == "Training Episode" and 'wrap_around' in state:
wrap_mode = "(Wrap)" if state['wrap_around'] else "(No Wrap)"
title = f"{title} {wrap_mode}"
title_text = title
title_surface = self.header_font.render(title_text, True, self.colors['text'])
title_rect = title_surface.get_rect(midtop=(x + size//2, y + size + 10))
self.screen.blit(title_surface, title_rect)
def draw_metrics(self, x: int, y: int, width: int) -> None:
"""Draw training metrics."""
if not self.training_info:
return
font = pygame.font.Font(None, 24)
y_offset = 0
# Draw high scores
high_score = self.training_info.get("high_score", 0)
recent_high = self.training_info.get("recent_high_score", 0)
metrics = [
("All-time High Score", high_score),
("Recent High Score", recent_high),
("", ""), # Empty line for spacing
("Training Metrics", ""),
("Total Steps", self.training_info.get('total_timesteps', 0)),
("Episode Reward", f"{self.training_info.get('episode_reward', 0):.2f}"),
("Mean Reward", f"{self.training_info.get('mean_reward', 0):.2f}"),
("Episode Length", self.training_info.get('episode_length', 0)),
("Mean Length", f"{self.training_info.get('mean_length', 0):.2f}"),
("FPS", f"{len(self.frame_times) / sum(self.frame_times):.1f}" if self.frame_times else "0")
]
for i, (label, value) in enumerate(metrics):
text = f"{label}: {value}" if label else ""
surface = self.text_font.render(text, True, self.colors['text'])
self.screen.blit(surface, (x, y + i * 25))
def draw_graph(self, data: List[float], rect: pygame.Rect, title: str,
color: Tuple[int, int, int], min_val: float, max_val: float,
smoothing_window: int = 10) -> None:
"""Draw a line graph of the given data.
Args:
data: List of data points.
rect: Rectangle area for drawing the graph.
title: Title for the graph.
color: Color for the graph line.
min_val: Minimum value for scaling the y-axis.
max_val: Maximum value for scaling the y-axis.
smoothing_window: Optional smoothing window size for drawing
long term trends. Increase this value for a smoother, longer-term trend.
Default is 10.
"""
if not data:
return
# Create a separate surface for the graph
graph_surface = pygame.Surface((rect.width, rect.height))
graph_surface.fill(self.colors['graph_bg'])
# Draw grid lines on the graph surface
num_lines = 5
for i in range(num_lines):
y_line = i * rect.height / (num_lines - 1)
pygame.draw.line(graph_surface, self.colors['graph_grid'],
(0, y_line), (rect.width, y_line))
# Add padding to the min/max values for better visualization
value_range = max_val - min_val
if value_range == 0:
value_range = 1.0
padding = value_range * 0.1
min_val_adjusted = min_val - padding
max_val_adjusted = max_val + padding
# Smooth the data using the provided smoothing_window parameter
window_size = smoothing_window if len(data) >= smoothing_window else len(data)
if window_size > 1:
smoothed_data = np.convolve(data, np.ones(window_size) / window_size, mode='valid')
else:
smoothed_data = data
points = []
for i, value in enumerate(smoothed_data):
x_point = i * rect.width / len(smoothed_data)
y_point = rect.height - ((value - min_val_adjusted) * rect.height /
(max_val_adjusted - min_val_adjusted))
points.append((x_point, y_point))
if len(points) > 1:
pygame.draw.lines(graph_surface, color, False, points, 2)
# Draw border on the graph surface
pygame.draw.rect(graph_surface, self.colors['border'],
pygame.Rect(0, 0, rect.width, rect.height), 1)
# Blit the graph surface onto the main screen
self.screen.blit(graph_surface, rect)
# Draw title and current value
current_value = data[-1] if data else 0
title_text = f"{title} (Current: {current_value:.2f})"
title_surface = self.text_font.render(title_text, True, self.colors['text'])
title_rect = title_surface.get_rect(midtop=(rect.centerx, rect.top - 20))
self.screen.blit(title_surface, title_rect)
# Draw value labels to the right of the graph
label_spacing = rect.height / (num_lines - 1)
label_x = rect.right + 10
for i in range(num_lines):
value = max_val_adjusted - (i * (max_val_adjusted - min_val_adjusted) / (num_lines - 1))
label_text = f"{value:.1f}"
label_surface = self.text_font.render(label_text, True, self.colors['text'])
label_rect = label_surface.get_rect(
left=label_x,
centery=rect.top + i * label_spacing
)
self.screen.blit(label_surface, label_rect)
def draw_weights_visualization(self, x: int, y: int, width: int, height: int, weights_info: Dict) -> None:
"""Draw the neural network weights visualization."""
if not weights_info:
return
# Get data
action_probs = weights_info.get('action_probs', [0, 0, 0, 0])
value_estimate = weights_info.get('value_estimate', 0.0)
action_labels = weights_info.get('action_labels', ['Up', 'Right', 'Down', 'Left'])
# Draw background
rect = pygame.Rect(x, y, width, height)
pygame.draw.rect(self.screen, self.colors['graph_bg'], rect)
pygame.draw.rect(self.screen, self.colors['border'], rect, 1)
# Draw title
title = "Action Probabilities"
title_surface = self.header_font.render(title, True, self.colors['text'])
title_rect = title_surface.get_rect(midtop=(x + width//2, y + 5))
self.screen.blit(title_surface, title_rect)
# Draw action probability bars
bar_height = 20
bar_spacing = 30
bar_start_y = y + 50
max_bar_width = width - 120 # Leave space for labels
for i, (prob, label) in enumerate(zip(action_probs, action_labels)):
# Draw label
label_surface = self.text_font.render(label, True, self.colors['text'])
self.screen.blit(label_surface, (x + 10, bar_start_y + i * bar_spacing))
# Draw bar background
bar_bg_rect = pygame.Rect(x + 70, bar_start_y + i * bar_spacing, max_bar_width, bar_height)
pygame.draw.rect(self.screen, self.colors['grid'], bar_bg_rect)
# Draw probability bar
bar_width = int(prob * max_bar_width)
bar_rect = pygame.Rect(x + 70, bar_start_y + i * bar_spacing, bar_width, bar_height)
pygame.draw.rect(self.screen, self.colors['highlight'], bar_rect)
# Draw probability value
prob_text = f"{prob:.2f}"
prob_surface = self.text_font.render(prob_text, True, self.colors['text'])
self.screen.blit(prob_surface, (x + 80 + max_bar_width, bar_start_y + i * bar_spacing))
# Draw value estimate
value_text = f"Value Estimate: {value_estimate:.2f}"
value_surface = self.text_font.render(value_text, True, self.colors['text'])
value_rect = value_surface.get_rect(midbottom=(x + width//2, y + height - 10))
self.screen.blit(value_surface, value_rect)
def draw_progress_bar(self, x: int, y: int, width: int, height: int, progress: float, text: str) -> None:
"""Draw a progress bar with text.
Args:
x, y: Position of the progress bar
width, height: Dimensions of the progress bar
progress: Progress value between 0 and 1
text: Text to display above the progress bar
"""
# Draw background
bg_rect = pygame.Rect(x, y, width, height)
pygame.draw.rect(self.screen, self.colors['graph_bg'], bg_rect)
pygame.draw.rect(self.screen, self.colors['border'], bg_rect, 1)
# Draw progress
if progress > 0:
progress_width = int(width * progress)
progress_rect = pygame.Rect(x, y, progress_width, height)
pygame.draw.rect(self.screen, self.colors['highlight'], progress_rect)
# Draw text
text_surface = self.text_font.render(text, True, self.colors['text'])
text_rect = text_surface.get_rect(bottomleft=(x, y - 5))
self.screen.blit(text_surface, text_rect)
def render(self) -> None:
"""Render the dashboard."""
if not self.current_state:
return
self.screen.fill(self.colors['background'])
# Draw game views
if 'training_state' in self.current_state:
# Draw both training games
self.draw_game_view(
self.current_state['training_state'][0], # No wrap training
(50, 50),
250,
"Training (No Wrap)"
)
self.draw_game_view(
self.current_state['training_state'][1], # Wrap training
(350, 50),
250,
"Training (Wrap)"
)
if 'eval_states' in self.current_state:
self.draw_game_view(
self.current_state['eval_states'][0],
(650, 50),
250,
"Evaluation (No Wrap)"
)
self.draw_game_view(
self.current_state['eval_states'][1],
(950, 50),
250,
"Evaluation (Wrap)"
)
if 'demo_state' in self.current_state:
self.draw_game_view(
self.current_state['demo_state'],
(1250, 50),
250,
"Demo Game"
)
# Draw metrics
if self.training_info:
metrics_data = [
(self.training_info['rewards_history'], "Episode Rewards"),
(self.training_info['lengths_history'], "Episode Lengths"),
(self.training_info['eval_scores_history'], "Evaluation Scores")
]
for i, (data, label) in enumerate(metrics_data):
if data: # Only draw if we have data
rect = pygame.Rect(50, 400 + i * 200, 500, 150)
self.draw_graph(
data,
rect,
label,
self.colors['graph_line'],
min(data) if data else 0,
max(data) if data else 1
)
# Draw current metrics text
metrics_text = [
f"Total Steps: {self.training_info.get('total_timesteps', 0):,}",
f"Mean Reward: {self.training_info.get('mean_reward', 0):.2f}",
f"Mean Length: {self.training_info.get('mean_length', 0):.1f}",
f"Mean Eval Score: {self.training_info.get('mean_eval_score', 0):.2f}",
f"High Score: {self.training_info.get('high_score', 0)}",
f"Recent High Score: {self.training_info.get('recent_high_score', 0)}"
]
# Add vertical spacer between metrics sections
metrics_text.insert(3, "") # Insert empty string as spacer after first 3 metrics
font = pygame.font.Font(None, 36)
for i, text in enumerate(metrics_text):
surface = font.render(text, True, self.colors['text'])
self.screen.blit(surface, (600, 400 + i * 30))
# Draw action probabilities if available
if 'weights_info' in self.current_state:
self.draw_weights_visualization(
1100, 400,
300, 300,
self.current_state['weights_info']
)
# Draw trend indicator graph
if self.training_info:
# Calculate trend indicators
window = 100 # Use last 100 episodes for trends
rewards = self.training_info['rewards_history'][-window:]
lengths = self.training_info['lengths_history'][-window:]
eval_scores = self.training_info['eval_scores_history'][-window:]
if rewards and lengths and eval_scores:
# Normalize each metric to 0-1 range for fair combination
norm_rewards = [(r - min(rewards)) / (max(rewards) - min(rewards) + 1e-8) for r in rewards]
norm_lengths = [(l - min(lengths)) / (max(lengths) - min(lengths) + 1e-8) for l in lengths]
norm_scores = [(s - min(eval_scores)) / (max(eval_scores) - min(eval_scores) + 1e-8) for s in eval_scores]
# Combine metrics with weights (rewards: 0.4, lengths: 0.3, eval_scores: 0.3)
trend_data = [0.4 * r + 0.3 * l + 0.3 * s
for r, l, s in zip(norm_rewards, norm_lengths, norm_scores)]
# Add trend direction indicator
trending = 0 # -1, 0, 1
if len(trend_data) >= 2:
recent_trend = trend_data[-1] - trend_data[0]
trending = 1 if recent_trend > 0.1 else -1 if recent_trend < -0.1 else 0
trend_text = "↑ Improving" if trending == 1 else "↓ Declining" if trending == -1 else "→ Stable"
trend_color = (0, 255, 0) if trending == 1 else (255, 0, 0) if trending == -1 else (200, 200, 0)
trend_surface = self.text_font.render(trend_text, True, trend_color)
trend_rect = trend_surface.get_rect(midtop=(1250, 860))
self.screen.blit(trend_surface, trend_rect)
graph_color = (0, 255, 0) if trending == 1 else (255, 0, 0) if trending == -1 else (200, 200, 0)
# Draw trend graph 50 pixels below the action probabilities graph
trend_rect = pygame.Rect(1100, 750, 300, 150)
self.draw_graph(
trend_data,
trend_rect,
"Learning Trend",
graph_color, # color based on trend
0, # Min value (normalized)
1, # Max value (normalized)
smoothing_window=10 # Use a larger smoothing window for longer-term trends
)
# Draw training progress bar at the bottom of the screen
if self.training_info:
# Get current session steps (from start of this training run)
current_session_steps = self.training_info.get('total_timesteps', 0) - self.training_info.get('initial_timesteps', 0)
target_timesteps = self.training_info.get('target_timesteps', 1000000)
progress = min(1.0, current_session_steps / target_timesteps)
# Show both current session progress and total model training
total_model_steps = self.training_info.get('total_timesteps', 0)
progress_text = (
f"Current Session: {current_session_steps:,}/{target_timesteps:,} steps ({progress*100:.1f}%) | "
f"Total Model Training: {total_model_steps:,} steps"
)
self.draw_progress_bar(50, self.height - 40, self.width - 100, 20, progress, progress_text)
pygame.display.flip()
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.running = False
def run_dashboard(update_queue: Queue) -> None:
"""Run the training dashboard in a separate thread."""
dashboard = TrainingDashboard()
try:
dashboard.run(update_queue)
finally:
# Send stop signal back to training process
update_queue.put(('stop_training', None))
pygame.quit()
+65
View File
@@ -0,0 +1,65 @@
"""
AI Snake Game CLI
This module provides the command-line interface for running the AI Snake Game.
It handles command-line arguments for different game modes and configurations.
"""
import argparse
from src.game import Game, GameState
from src.ui.menu import GameMode
def main():
"""
Main entry point for the AI Snake Game.
Parses command line arguments and initializes the game with the specified settings.
Available modes:
- Normal mode: Standard game settings
- Test mode: Smaller window and faster speed
- Debug mode: Shows grid and additional debug information
"""
parser = argparse.ArgumentParser(description='Run AI Snake Game')
parser.add_argument('--test', action='store_true',
help='Run game in test mode (smaller window, faster speed)')
parser.add_argument('--debug', action='store_true',
help='Run game in debug mode (shows grid and additional info)')
parser.add_argument('--ai-only', action='store_true',
help='Start directly in AI mode (skips menu)')
args = parser.parse_args()
# Create game instance
game = Game()
# Apply test mode settings
if args.test:
game.width = 400
game.height = 300
game.game_session.grid_size = 20
game.clock.tick(30) # Set FPS to 30
# Apply debug mode settings
if args.debug:
game.settings.debug_mode = True
if game.game_session:
game.game_session.show_grid = True
# Apply AI mode settings
if args.ai_only:
game.game_mode = GameMode.AI_MEDIUM
game.state = GameState.PLAYING
# Run the game
try:
game.run()
except KeyboardInterrupt:
print("\nGame terminated by user")
except Exception as e:
print(f"Error: {e}")
finally:
# Clean up will be handled by Game class destructor
pass
if __name__ == "__main__":
main()
+36
View File
@@ -0,0 +1,36 @@
"""
Game Configuration Package
This package contains game configuration and constants.
"""
from .constants import *
from .settings import GameRules, GameSettings
__all__ = [
'GameRules',
'GameSettings',
# Include all constants
'WINDOW_WIDTH',
'WINDOW_HEIGHT',
'DEFAULT_GRID_WIDTH',
'DEFAULT_GRID_HEIGHT',
'DEFAULT_GRID_SIZE',
'DEFAULT_PADDING',
'DEFAULT_SCORE_HEIGHT',
'BLACK',
'WHITE',
'GREEN',
'DARK_GREEN',
'GRAY',
'DARK_GRAY',
'GRID_COLOR',
'TITLE_FONT_SIZE',
'SUBTITLE_FONT_SIZE',
'SCORE_FONT_SIZE',
'DEBUG_FONT_SIZE',
'FPS',
'DEFAULT_MOVE_COOLDOWN',
'MIN_MOVE_COOLDOWN',
'MENU_ITEM_SPACING'
]
+25
View File
@@ -0,0 +1,25 @@
"""
Game Colors
This module contains all the color values used throughout the game.
"""
# Modern color palette
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
DARK_GREEN = (0, 100, 0)
NEON_GREEN = (57, 255, 20) # Brighter, more neon green
LIME_GREEN = (50, 205, 50) # Softer green for variety
FOREST_GREEN = (0, 100, 0) # Dark green for contrast
DARKER_GREEN = (0, 40, 0) # Very dark green for borders
GRAY = (128, 128, 128)
DARK_GRAY = (25, 25, 25) # Darker background for better contrast
GRID_COLOR = (40, 40, 40)
SUBTLE_GRID_COLOR = (35, 35, 35)
RED = (255, 0, 0)
NEON_RED = (255, 20, 57) # Brighter, more neon red for food
GLOW_GREEN = (150, 255, 150) # Light green for glow effects
SNAKE_GRADIENT_START = (57, 255, 20) # Head color
SNAKE_GRADIENT_END = (0, 150, 0) # Tail color
+31
View File
@@ -0,0 +1,31 @@
"""
Game Constants
This module contains all the constant values used throughout the game.
"""
# Window settings
WINDOW_WIDTH = 1024
WINDOW_HEIGHT = 768
# Grid settings
DEFAULT_GRID_WIDTH = 30
DEFAULT_GRID_HEIGHT = 30
DEFAULT_GRID_SIZE = 20
# Game area settings
DEFAULT_PADDING = 40
DEFAULT_SCORE_HEIGHT = 60
# Font sizes
TITLE_FONT_SIZE = 72
SUBTITLE_FONT_SIZE = 36
SCORE_FONT_SIZE = 36
DEBUG_FONT_SIZE = 24
# Game timing
FPS = 60
DEFAULT_MOVE_COOLDOWN = 100
MIN_MOVE_COOLDOWN = 50
# Menu settings
MENU_ITEM_SPACING = 50
+52
View File
@@ -0,0 +1,52 @@
"""
Game Settings
This module contains the game settings and rules that can be configured.
"""
class GameRules:
"""Game rules that can be configured through the settings menu."""
def __init__(self):
self.wrap_around = True # Whether snake wraps around screen edges
self.speed_increase = True # Whether snake speeds up as it grows
self.min_move_cooldown = 50 # Minimum movement delay in milliseconds
self.initial_move_cooldown = 100 # Initial movement delay
self.starting_length = 3 # Starting length of the snake
def update_rule(self, rule_name, value):
"""
Update a game rule with a new value.
Args:
rule_name (str): Name of the rule to update
value: New value for the rule
Returns:
bool: True if update was successful, False otherwise
"""
if hasattr(self, rule_name):
# Define validation rules for specific attributes
validators = {
'starting_length': lambda x: 1 <= x <= 10,
'wrap_around': lambda x: isinstance(x, bool),
'speed_increase': lambda x: isinstance(x, bool),
'min_move_cooldown': lambda x: x > 0,
'initial_move_cooldown': lambda x: x > 0
}
# Validate the value if there's a validator for this rule
if rule_name in validators and not validators[rule_name](value):
return False
setattr(self, rule_name, value)
return True
return False
class GameSettings:
"""Global game settings."""
def __init__(self):
self.debug_mode = False # Whether to show debug information
self.show_grid = self.debug_mode # Whether to show the grid lines
self.rules = GameRules() # Game rules instance
+16
View File
@@ -0,0 +1,16 @@
"""
Game Core Package
This package contains the core game mechanics and entities.
"""
from .snake import Snake, Direction
from .food import Food
from .game_session import GameSession
__all__ = [
'Snake',
'Direction',
'Food',
'GameSession'
]
+82
View File
@@ -0,0 +1,82 @@
"""
Food Module
This module provides the Food class that represents the food item in the game.
"""
import pygame
import random
from typing import Tuple, List
from src.ui import GameArea
from src.config.colors import *
class Food:
def __init__(self, color: Tuple[int, int, int] = NEON_RED):
"""
Initialize food with a color.
Args:
color: RGB color tuple for the food
"""
self.color = color
self.position = (0, 0) # Will be set by spawn_at_position()
def spawn_at_position(self, available_positions: List[Tuple[int, int]]) -> None:
"""
Spawn food at a random position from the available positions.
Args:
available_positions: List of valid grid positions where food can spawn
"""
if not available_positions:
# No valid positions (snake fills screen) - game should be won
return
# Choose random position from valid positions
self.position = random.choice(available_positions)
def draw(self, screen: pygame.Surface, game_area: GameArea) -> None:
"""
Draw the food on the screen with a glowing effect
Args:
screen: Pygame surface to draw on
game_area: GameArea instance for coordinate conversion
"""
screen_x, screen_y = game_area.get_screen_pos(self.position[0], self.position[1])
# Draw outer glow
glow_size = game_area.grid_size + 4
glow_surface = pygame.Surface((glow_size, glow_size), pygame.SRCALPHA)
# Create radial gradient for glow
for i in range(3):
alpha = 100 - (i * 30) # Fade out alpha
size = glow_size - (i * 2)
pos = (glow_size - size) // 2
pygame.draw.circle(glow_surface, (*NEON_RED[:3], alpha), (glow_size//2, glow_size//2), size//2)
# Draw glow
screen.blit(glow_surface, (screen_x - 2, screen_y - 2))
# Draw main food body
food_rect = pygame.Rect(
screen_x + 2,
screen_y + 2,
game_area.grid_size - 4,
game_area.grid_size - 4
)
pygame.draw.rect(screen, NEON_RED, food_rect, border_radius=4)
# Draw highlight
highlight_rect = pygame.Rect(
screen_x + 4,
screen_y + 4,
game_area.grid_size - 8,
game_area.grid_size - 8
)
pygame.draw.rect(screen, (*NEON_RED, 200), highlight_rect, border_radius=3)
def check_collision(self, position: Tuple[int, int]) -> bool:
"""Check if the given position collides with the food"""
return self.position == position
+239
View File
@@ -0,0 +1,239 @@
"""
Game Session Manager
This module provides a reusable game session class that encapsulates the core gameplay mechanics.
It can be used by both the main game and the training environment to ensure consistent behavior.
"""
import pygame
from typing import Tuple, Dict, Optional
from src.core import Snake, Direction, Food
from src.ui import GameArea
from src.config import (
WINDOW_WIDTH,
WINDOW_HEIGHT,
FPS
)
from src.config.colors import *
from src.config.settings import GameRules
class GameSession:
"""Manages a single game session with consistent rules and boundaries."""
def __init__(self, grid_width: int, grid_height: int, rules : GameRules, window_width: int = WINDOW_WIDTH, window_height: int = WINDOW_HEIGHT):
"""
Initialize a new game session.
Args:
grid_width: Number of grid cells horizontally
grid_height: Number of grid cells vertically
rules: GameRules instance containing game settings
window_width: Width of the game window
window_height: Height of the game window
"""
self.grid_width = grid_width
self.grid_height = grid_height
self.rules = rules
self.window_width = window_width
self.window_height = window_height
# Game objects
self.snake = None
self.food = None
# Game state
self.score = 0
self.is_game_over = False
self.move_cooldown = rules.initial_move_cooldown
self.last_move_time = 0
self.reset()
def reset(self) -> Dict:
"""
Reset the game session to its initial state, including the game area.
Returns:
Dict containing the initial game state
"""
# Initialize game area with window dimensions
self.game_area = GameArea(
window_width=self.window_width,
window_height=self.window_height,
grid_width=self.grid_width,
grid_height=self.grid_height
)
# Initialize snake in the middle of the grid
start_x = self.grid_width // 2
start_y = self.grid_height // 2
self.snake = Snake(
start_pos=(start_x, start_y),
grid_width=self.grid_width,
grid_height=self.grid_height
)
# Initialize food
self.food = Food()
self._spawn_food()
# Reset game state
self.score = 0
self.is_game_over = False
self.move_cooldown = self.rules.initial_move_cooldown
self.last_move_time = 0
return self.get_state()
def _spawn_food(self) -> None:
"""Spawn food in a random empty grid cell."""
# Get all occupied positions
occupied = set(self.snake.body)
# Get all possible positions
all_positions = [(x, y) for x in range(self.grid_width)
for y in range(self.grid_height)]
# Filter out occupied positions
available = [pos for pos in all_positions if pos not in occupied]
if available:
self.food.spawn_at_position(available)
def step(self, action: Optional[Direction] = None, current_time: int = 0) -> Tuple[Dict, float, bool]:
"""
Advance the game state by one step.
Args:
action: Optional direction to change to
current_time: Current game time in milliseconds
Returns:
Tuple of (game_state, reward, done)
"""
if self.is_game_over:
return self.get_state(), 0, True
# Apply action if provided
if action is not None:
self.snake.change_direction(action)
# Update snake movement animation
self.snake.update_movement(1.0 / FPS) #
# Check if enough time has passed for next move
if current_time - self.last_move_time < self.move_cooldown:
return self.get_state(), 0, False
self.last_move_time = current_time
# Process any pending direction changes first
if self.snake.input_buffer:
# Try first direction
next_direction = self.snake.input_buffer[0]
if self.snake.is_direction_valid(next_direction):
self.snake.direction = next_direction
self.snake.input_buffer.pop(0)
# If invalid and we have another input, try that one first
elif len(self.snake.input_buffer) > 1:
alt_direction = self.snake.input_buffer[1]
if self.snake.is_direction_valid(alt_direction):
self.snake.direction = alt_direction
self.snake.input_buffer.pop(1) # Remove the successful second input
# Remove the first input regardless as it's had its chance
self.snake.input_buffer.pop(0)
else:
# Single invalid input, just remove it
self.snake.input_buffer.pop(0)
# Now get movement vector with updated direction
dx, dy = self.snake.direction.to_vector()
new_head = (self.snake.body[0][0] + dx, self.snake.body[0][1] + dy)
# Check for immediate wall collision (before moving)
if not self.rules.wrap_around:
if (new_head[0] < 0 or new_head[0] >= self.grid_width or
new_head[1] < 0 or new_head[1] >= self.grid_height):
self.is_game_over = True
return self.get_state(), -1, True
# check for collision with snake body
if new_head in self.snake.body[1:]:
self.is_game_over = True
return self.get_state(), -1, True
# Move snake
head_x, head_y = self.snake.move()
# Handle wrap-around if enabled
if self.rules.wrap_around:
head_x = head_x % self.grid_width
head_y = head_y % self.grid_height
self.snake.body[0] = (head_x, head_y)
self.snake.target_positions[0] = (head_x, head_y) # Update target position for smooth movement
# Check self collision
if (head_x, head_y) in self.snake.body[1:]:
self.is_game_over = True
return self.get_state(), -1, True
# Check food collision
if (head_x, head_y) == self.food.position:
self.score += 1
self.snake.grow()
self._spawn_food()
# Increase speed if enabled
if self.rules.speed_increase:
self.move_cooldown = max(
self.rules.min_move_cooldown,
self.move_cooldown - 2
)
return self.get_state(), 1, False
return self.get_state(), 0, False
def get_state(self) -> Dict:
"""
Get the current game state.
Returns:
Dict containing the game state
"""
return {
"grid_width": self.grid_width,
"grid_height": self.grid_height,
"snake_head": self.snake.body[0],
"snake_body": self.snake.body,
"snake_direction": self.snake.direction,
"food_position": self.food.position,
"score": self.score,
"game_over": self.is_game_over,
"move_cooldown": self.move_cooldown
}
def render(self, screen: pygame.Surface) -> None:
"""
Render the game state to the screen.
Args:
screen: Pygame surface to render to
"""
# Draw game area first
self.game_area.draw(screen)
# Draw game objects
self.snake.draw(screen, self.game_area)
self.food.draw(screen, self.game_area)
# Draw grid (optional, for debugging)
if hasattr(self, 'show_grid') and self.show_grid:
for x in range(self.grid_width + 1):
start_pos = (self.game_area.x + x * self.game_area.grid_size, self.game_area.y)
end_pos = (self.game_area.x + x * self.game_area.grid_size, self.game_area.y + self.game_area.height)
pygame.draw.line(screen, GRID_COLOR, start_pos, end_pos, 1)
for y in range(self.grid_height + 1):
start_pos = (self.game_area.x, self.game_area.y + y * self.game_area.grid_size)
end_pos = (self.game_area.x + self.game_area.width, self.game_area.y + y * self.game_area.grid_size)
pygame.draw.line(screen, GRID_COLOR, start_pos, end_pos, 1)
+357
View File
@@ -0,0 +1,357 @@
"""
Snake Module
This module provides the Snake class and Direction enum for snake movement and rendering.
"""
import pygame
from enum import Enum, auto
from typing import Tuple, List
import math
from src.config.colors import *
import pygame.gfxdraw
class Direction(Enum):
UP = auto()
DOWN = auto()
LEFT = auto()
RIGHT = auto()
def to_vector(self) -> Tuple[int, int]:
# Convert direction to a movement vector
if self == Direction.UP:
return (0, -1)
elif self == Direction.DOWN:
return (0, 1)
elif self == Direction.LEFT:
return (-1, 0)
else: # Direction.RIGHT
return (1, 0)
class Snake:
def __init__(self, start_pos: Tuple[int, int], grid_width: int, grid_height: int, length: int = 3):
"""
Initialize snake at the given grid position.
Args:
start_pos: Starting position in grid coordinates (x, y)
grid_width: Width of the game grid
grid_height: Height of the game grid
length: Initial length of the snake
"""
self.direction = Direction.RIGHT
self.body = [start_pos] # Head is at index 0
self.growing = False
self.grid_width = grid_width
self.grid_height = grid_height
# FIX: Start from 1 to avoid duplicate head segment.
for i in range(1, length):
self.body.append((start_pos[0] - i, start_pos[1]))
# Initialize visual positions for each body segment
self.visual_positions = [(float(pos[0]), float(pos[1])) for pos in self.body]
self.move_progress = 1.0 # Progress of current move (0.0 to 1.0)
self.move_speed = 0.2 # Movement speed
self.target_positions = list(self.body) # Target grid positions
# Input buffer for direction changes
self.input_buffer = [] # Store up to 2 pending direction changes
self.max_buffer_size = 2
# Create base segment surface with gradient
self.segment_size = 32 # Base size for segment surface
self.base_surface = pygame.Surface((self.segment_size, self.segment_size), pygame.SRCALPHA)
# Create a radial gradient for the base segment
center = self.segment_size // 2
for radius in range(center, -1, -1):
# Calculate color intensity based on distance from center
intensity = 1.0 - (radius / center) ** 0.8 # Adjust power for gradient shape
color = (
int(SNAKE_GRADIENT_START[0] * intensity),
int(SNAKE_GRADIENT_START[1] * intensity),
int(SNAKE_GRADIENT_START[2] * intensity),
255
)
pygame.draw.circle(self.base_surface, color, (center, center), radius)
def move(self) -> Tuple[int, int]:
"""
Move the snake one grid cell in current direction.
Returns:
New head position (x, y)
"""
# Get new head position
head = self.body[0]
new_head = self._get_new_head_position(head)
# Update grid positions
self.body.insert(0, new_head)
if not self.growing:
self.body.pop()
else:
self.growing = False
# Update visual positions
self.target_positions = list(self.body) # Copy current grid positions as targets
if len(self.visual_positions) < len(self.target_positions):
self.visual_positions.append(self.visual_positions[-1])
# Reset move progress for smooth animation
self.move_progress = 0.0
return new_head
def update_movement(self, dt: float):
"""Update visual position interpolation with consistent timing."""
if self.move_progress >= 1.0:
return
# Use cubic easing for smoother acceleration/deceleration
self.move_progress = min(1.0, self.move_progress + self.move_speed)
t = self.move_progress
overall_progress = t * t * (3 - 2 * t)
# Update each segment with fixed delay windows
segment_count = len(self.visual_positions)
for i in range(segment_count):
if i >= len(self.target_positions):
continue
current = self.visual_positions[i]
target = self.target_positions[i]
dx = target[0] - current[0]
dy = target[1] - current[1]
# Check if this segment needs to wrap
wrap_x = abs(dx) > 2
wrap_y = abs(dy) > 2
if wrap_x or wrap_y:
self.visual_positions[i] = target
else:
# Use fixed delay windows instead of compounding delays
delay_window = 0.2 # Total delay spread across all segments
segment_delay = (i / segment_count) * delay_window
# Calculate progress for this segment
segment_progress = max(0.0, (overall_progress - segment_delay) / (1.0 - segment_delay))
segment_progress = min(1.0, segment_progress)
# Apply smoothed movement
new_x = current[0] + dx * segment_progress
new_y = current[1] + dy * segment_progress
self.visual_positions[i] = (new_x, new_y)
def _get_new_head_position(self, head: Tuple[int, int]) -> Tuple[int, int]:
"""Calculate new head position based on current direction"""
x, y = head
dx, dy = self.direction.to_vector()
return (x + dx, y + dy)
def grow(self):
"""Mark the snake to grow on next move"""
self.growing = True
def check_collision(self, width: int, height: int, wrap_around: bool = False) -> bool:
"""
Check if snake has collided with walls or itself.
Args:
width: Game area width
height: Game area height
wrap_around: If True, snake wraps around screen edges instead of colliding
"""
head = self.body[0]
if not wrap_around:
# Check wall collision
if (head[0] < 0 or head[0] >= width or
head[1] < 0 or head[1] >= height):
return True
# Check self collision (skip head)
if head in self.body[1:]:
return True
return False
def wrap_position(self, width: int, height: int):
"""Wrap snake's head position around screen edges"""
head_x, head_y = self.body[0]
wrapped_head = (
head_x % width,
head_y % height
)
self.body[0] = wrapped_head
def is_direction_valid(self, new_direction: Direction) -> bool:
"""
Try to change direction, ensuring no 180-degree turns.
Args:
new_direction: The direction to change to
Returns:
True if direction was changed, False otherwise
"""
opposite_directions = {
Direction.UP: Direction.DOWN,
Direction.DOWN: Direction.UP,
Direction.LEFT: Direction.RIGHT,
Direction.RIGHT: Direction.LEFT
}
if opposite_directions[new_direction] == self.direction or new_direction == self.direction:
return False
self.direction = new_direction
return True
def change_direction(self, new_direction: Direction):
"""
Buffer a direction change to be applied on next move.
Args:
new_direction: The direction to change to
"""
if self.input_buffer and self.input_buffer[-1] == new_direction:
return
if len(self.input_buffer) < self.max_buffer_size:
self.input_buffer.append(new_direction)
def draw(self, screen: pygame.Surface, game_area):
"""Draw snake with clean, connected design and cute tongue."""
if len(self.visual_positions) < 2:
return
base_size = game_area.grid_size
segment_size = base_size - 4
# Draw snake body segments
for i in range(len(self.visual_positions) - 1):
pos1 = self.visual_positions[i]
pos2 = self.visual_positions[i + 1]
screen_positions = self._get_wrapped_segment_positions(pos1, pos2, game_area)
if not screen_positions:
continue
for sp1, sp2 in screen_positions:
# Calculate segment properties
progress = max(0.4, 1.0 - (i / len(self.visual_positions)))
color = (
int(SNAKE_GRADIENT_START[0] * progress),
int(SNAKE_GRADIENT_START[1] * progress),
int(SNAKE_GRADIENT_START[2] * progress)
)
# Draw connecting segments with extra thickness
center1 = (sp1[0] + base_size//2, sp1[1] + base_size//2)
center2 = (sp2[0] + base_size//2, sp2[1] + base_size//2)
# Draw a thicker base line first
pygame.draw.line(screen, color, center1, center2, segment_size + 4)
# Draw larger circles at joints to ensure corner coverage
pygame.draw.circle(screen, color, center1, (segment_size + 2)//2)
pygame.draw.circle(screen, color, center2, (segment_size + 2)//2)
# If this is a corner (check by looking at next segment)
if i < len(self.visual_positions) - 2:
pos3 = self.visual_positions[i + 2]
if pos2[0] != pos1[0] and pos3[1] != pos2[1] or \
pos2[1] != pos1[1] and pos3[0] != pos2[0]:
# Draw extra circle at the corner to ensure coverage
pygame.draw.circle(screen, color, center2, (segment_size + 6)//2)
# Draw head
head_pos = self.visual_positions[0]
screen_pos = game_area.get_screen_pos(head_pos[0], head_pos[1])
center = (screen_pos[0] + base_size//2, screen_pos[1] + base_size//2)
# Draw head circle
pygame.draw.circle(screen, SNAKE_GRADIENT_START, center, segment_size//2)
# Calculate direction for eyes and tongue
next_pos = self.visual_positions[1] if len(self.visual_positions) > 1 else head_pos
dx = head_pos[0] - next_pos[0] # Reversed the direction calculation
dy = head_pos[1] - next_pos[1] # Reversed the direction calculation
angle = math.atan2(dy, dx)
# Draw eyes
eye_offset = segment_size//4
eye_size = 2
eye_angle = angle + math.pi/2
for side in [-1, 1]:
eye_x = center[0] + math.cos(eye_angle) * eye_offset * side
eye_y = center[1] + math.sin(eye_angle) * eye_offset
pygame.draw.circle(screen, (0, 0, 0), (int(eye_x), int(eye_y)), eye_size)
# Draw flickering tongue with more pronounced animation
time = pygame.time.get_ticks()
tongue_flick = math.sin(time * 0.01) * 0.8 + 0.2 # Slower, more pronounced flicking
# Tongue base position (at front of head)
tongue_base_x = center[0] + math.cos(angle) * (segment_size//2)
tongue_base_y = center[1] + math.sin(angle) * (segment_size//2)
# Tongue length varies with flicking animation
tongue_length = (3 + tongue_flick * 6) # Length varies between 3 and 9 pixels
fork_length = 4 # Slightly longer fork
fork_angle = math.pi/3 # Wider fork angle
# Calculate tongue tip
tongue_tip_x = tongue_base_x + math.cos(angle) * tongue_length
tongue_tip_y = tongue_base_y + math.sin(angle) * tongue_length
# Calculate fork tips
left_fork_x = tongue_tip_x + math.cos(angle + fork_angle) * fork_length
left_fork_y = tongue_tip_y + math.sin(angle + fork_angle) * fork_length
right_fork_x = tongue_tip_x + math.cos(angle - fork_angle) * fork_length
right_fork_y = tongue_tip_y + math.sin(angle - fork_angle) * fork_length
# Draw tongue with brighter red
tongue_color = (255, 0, 0) # Bright red
# Draw main tongue line
pygame.draw.line(screen, tongue_color,
(tongue_base_x, tongue_base_y),
(tongue_tip_x, tongue_tip_y), 2)
# Draw forked tips
pygame.draw.line(screen, tongue_color,
(tongue_tip_x, tongue_tip_y),
(left_fork_x, left_fork_y), 2)
pygame.draw.line(screen, tongue_color,
(tongue_tip_x, tongue_tip_y),
(right_fork_x, right_fork_y), 2)
def _get_wrapped_segment_positions(self, pos1, pos2, game_area):
"""
Get screen positions for segment rendering, handling wrap-around.
Only returns positions for segments that are close enough to interpolate.
"""
grid_w = self.grid_width
grid_h = self.grid_height
# Calculate primary direction
dx = pos2[0] - pos1[0]
dy = pos2[1] - pos1[1]
# If segments are too far apart (wrapping), don't draw connecting segment
if abs(dx) > 2 or abs(dy) > 2:
return []
# Convert to screen coordinates
screen_pos1 = game_area.get_screen_pos(pos1[0], pos1[1])
screen_pos2 = game_area.get_screen_pos(pos2[0], pos2[1])
return [(screen_pos1, screen_pos2)]
-52
View File
@@ -1,52 +0,0 @@
import pygame
import random
from typing import Tuple, List
class Food:
def __init__(self, block_size: int, color: Tuple[int, int, int] = (255, 0, 0)):
self.block_size = block_size
self.color = color
self.position = (0, 0) # Will be set by spawn()
def spawn(self, width: int, height: int, occupied_positions: List[Tuple[int, int]]) -> None:
"""
Spawn food at a random position that isn't occupied by the snake.
Args:
width: Game area width
height: Game area height
occupied_positions: List of positions (typically snake body positions) where food shouldn't spawn
"""
# Calculate valid grid positions
valid_x = range(0, width, self.block_size)
valid_y = range(0, height, self.block_size)
# Create list of all possible positions
all_positions = [
(x, y) for x in valid_x for y in valid_y
if (x, y) not in occupied_positions
]
if not all_positions:
# No valid positions (snake fills screen) - game should be won
return
# Choose random position
self.position = random.choice(all_positions)
def draw(self, screen: pygame.Surface) -> None:
"""Draw the food on the screen"""
pygame.draw.rect(
screen,
self.color,
pygame.Rect(
self.position[0],
self.position[1],
self.block_size,
self.block_size
)
)
def check_collision(self, position: Tuple[int, int]) -> bool:
"""Check if the given position collides with the food"""
return self.position == position
+167 -58
View File
@@ -1,113 +1,222 @@
"""
Main Game Module
This module provides the main game class that handles the game loop,
state management, and user interface.
"""
import pygame
import sys
from enum import Enum, auto
from snake import Snake, Direction
from food import Food
from src.config import (
WINDOW_WIDTH,
WINDOW_HEIGHT,
FPS,
SCORE_FONT_SIZE
)
from src.config import GameSettings
from src.config.colors import BLACK, GREEN, NEON_GREEN
from src.core import Direction, GameSession
from src.ui import Menu, GameMode, SettingsMenu, PauseMenu, GameArea
class GameState(Enum):
"""Game states."""
MENU = auto()
SETTINGS = auto()
PLAYING = auto()
GAME_OVER = auto()
PAUSED = auto()
class Game:
"""Main game class that manages the game loop and state."""
def __init__(self):
# Initialize display
self.width = 800
self.height = 600
"""Initialize the game."""
pygame.init()
pygame.font.init()
# Window setup
self.width = WINDOW_WIDTH
self.height = WINDOW_HEIGHT
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("AI Snake Game")
pygame.display.set_caption("Snake Game")
# Initialize clock
# Initialize game components
self.clock = pygame.time.Clock()
self.fps = 60
# Game objects
self.block_size = 20
self.snake = Snake((self.width // 2, self.height // 2), self.block_size)
self.food = Food(self.block_size)
# Spawn initial food
self.food.spawn(self.width, self.height, self.snake.body)
self.font = pygame.font.Font(None, SCORE_FONT_SIZE)
self.settings = GameSettings()
self.menu = Menu()
self.settings_menu = SettingsMenu(rules=self.settings.rules)
self.pause_menu = PauseMenu()
# Game state
self.state = GameState.PLAYING # Changed to start in playing state for now
self.state = GameState.MENU
self.game_session = None
self.game_mode = None
self.running = True
self.score = 0
self.reset_game()
def reset_game(self):
"""Initialize or reset the game session."""
if self.game_session:
del self.game_session
self.game_session = GameSession(
grid_width=30,
grid_height=30,
rules=self.settings.rules,
window_width=self.width,
window_height=self.height
)
def handle_events(self):
"""Handle game events."""
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# Handle mouse clicks in menus
if self.state == GameState.MENU:
selected_mode = self.menu.handle_input(event)
if selected_mode is not None:
if selected_mode == GameMode.SETTINGS:
self.state = GameState.SETTINGS
elif selected_mode == GameMode.PLAYER:
self.game_mode = GameMode.PLAYER
self.state = GameState.PLAYING
self.reset_game()
elif selected_mode in (GameMode.AI_EASY, GameMode.AI_MEDIUM, GameMode.AI_HARD):
self.game_mode = selected_mode
self.state = GameState.PLAYING
self.reset_game()
else: # Quit selected
self.running = False
elif self.state == GameState.SETTINGS:
result = self.settings_menu.handle_input(event)
if result == 'back':
self.state = GameState.MENU
elif self.state == GameState.PAUSED:
result = self.pause_menu.handle_input(event)
if result == 'resume':
self.state = GameState.PLAYING
elif result == 'menu':
self.state = GameState.MENU
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
if self.state == GameState.PLAYING:
self.state = GameState.PAUSED
elif self.state == GameState.PAUSED:
self.state = GameState.PLAYING
elif self.state == GameState.MENU:
self.running = False
elif self.state == GameState.SETTINGS:
self.state = GameState.MENU
elif event.key == pygame.K_F3: # Toggle debug mode
self.settings.debug_mode = not self.settings.debug_mode
if self.game_session:
self.game_session.show_grid = self.settings.debug_mode
elif self.state == GameState.PLAYING:
# Handle snake direction
if event.key == pygame.K_UP:
self.snake.change_direction(Direction.UP)
self.game_session.step(Direction.UP, current_time)
elif event.key == pygame.K_DOWN:
self.snake.change_direction(Direction.DOWN)
self.game_session.step(Direction.DOWN, current_time)
elif event.key == pygame.K_LEFT:
self.snake.change_direction(Direction.LEFT)
self.game_session.step(Direction.LEFT, current_time)
elif event.key == pygame.K_RIGHT:
self.snake.change_direction(Direction.RIGHT)
self.game_session.step(Direction.RIGHT, current_time)
elif self.state == GameState.GAME_OVER:
# Any key to return to menu in game over state
self.state = GameState.MENU
def update(self):
if self.state == GameState.PLAYING:
# Move snake
if self.snake.move(pygame.time.get_ticks()):
# Check wall collision
if self.snake.check_collision(self.width, self.height):
self.state = GameState.GAME_OVER
return
"""Update game state."""
current_time = pygame.time.get_ticks()
# Check food collision
if self.food.check_collision(self.snake.body[0]):
self.snake.grow()
self.score += 1
self.food.spawn(self.width, self.height, self.snake.body)
if self.state == GameState.MENU:
self.menu.update()
elif self.state == GameState.SETTINGS:
self.settings_menu.update()
elif self.state == GameState.PAUSED:
self.pause_menu.update()
elif self.state == GameState.PLAYING:
# Update game session
_, _, done = self.game_session.step(current_time=current_time)
if done:
self.state = GameState.GAME_OVER
def draw_debug_info(self):
"""Draw debug information."""
if not self.game_session:
return
state = self.game_session.get_state()
font = pygame.font.Font(None, 24)
debug_info = [
f"FPS: {int(self.clock.get_fps())}",
f"Snake Length: {len(state['snake_body'])}",
f"Snake Head: {state['snake_body'][0]}",
f"Food Pos: {state['food_position']}",
f"Game State: {self.state.name}",
f"Game Mode: {self.game_mode.name if self.game_mode else 'None'}",
f"Move Cooldown: {state['move_cooldown']}ms"
]
for i, text in enumerate(debug_info):
surface = font.render(text, True, GREEN)
self.screen.blit(surface, (10, self.height - 200 + i * 25))
def draw_overlay(self, text):
"""Draw a semi-transparent overlay with text."""
overlay = pygame.Surface((self.width, self.height))
overlay.fill(BLACK)
overlay.set_alpha(128)
self.screen.blit(overlay, (0, 0))
text_surface = self.font.render(text, True, NEON_GREEN)
text_rect = text_surface.get_rect(center=(self.width // 2, self.height // 2))
self.screen.blit(text_surface, text_rect)
def render(self):
"""Render the current game state."""
# Clear screen
self.screen.fill((0, 0, 0)) # Black background
self.screen.fill(BLACK)
if self.state == GameState.PLAYING or self.state == GameState.PAUSED:
# Draw game objects
self.snake.draw(self.screen)
self.food.draw(self.screen)
if self.state == GameState.MENU:
self.menu.draw(self.screen)
elif self.state == GameState.SETTINGS:
self.settings_menu.draw(self.screen)
elif self.state in [GameState.PLAYING, GameState.PAUSED, GameState.GAME_OVER]:
# Draw game session
self.game_session.render(self.screen)
# Draw score
font = pygame.font.Font(None, 36)
score_text = font.render(f'Score: {self.score}', True, (255, 255, 255))
self.screen.blit(score_text, (10, 10))
# Draw score panel
score_text = f"Score: {self.game_session.score}"
score_surface = self.font.render(score_text, True, GREEN)
score_rect = score_surface.get_rect(midtop=(self.width // 2, 20))
self.screen.blit(score_surface, score_rect)
# Draw pause indicator
# Draw overlays
if self.state == GameState.PAUSED:
pause_text = font.render('PAUSED', True, (255, 255, 255))
text_rect = pause_text.get_rect(center=(self.width//2, self.height//2))
self.screen.blit(pause_text, text_rect)
self.pause_menu.draw(self.screen)
elif self.state == GameState.GAME_OVER:
self.draw_overlay("GAME OVER")
elif self.state == GameState.GAME_OVER:
font = pygame.font.Font(None, 74)
text = font.render('Game Over!', True, (255, 0, 0))
score_text = font.render(f'Score: {self.score}', True, (255, 255, 255))
text_rect = text.get_rect(center=(self.width//2, self.height//2 - 50))
score_rect = score_text.get_rect(center=(self.width//2, self.height//2 + 50))
self.screen.blit(text, text_rect)
self.screen.blit(score_text, score_rect)
# Draw debug info if enabled
if self.settings.debug_mode:
self.draw_debug_info()
# Update display
pygame.display.flip()
def run(self):
"""Run the main game loop."""
self.running = True
while self.running:
self.handle_events()
self.update()
self.render()
self.clock.tick(self.fps)
self.clock.tick(FPS)
+9 -1
View File
@@ -1,8 +1,16 @@
"""
Main entry point for the AI Snake Game.
This module provides the standard entry point for running the game
without any command line arguments.
"""
import pygame
import sys
from game import Game
from src.game import Game
def main():
"""Run the game with default settings."""
# Initialize Pygame
pygame.init()
+142
View File
@@ -0,0 +1,142 @@
import pygame
from enum import Enum, auto
from typing import List, Tuple, Callable
class GameMode(Enum):
PLAYER = auto()
AI_EASY = auto()
AI_MEDIUM = auto()
AI_HARD = auto()
SETTINGS = auto()
QUIT = auto()
class MenuItem:
def __init__(self, text, position, action, size=36, color=(255, 255, 255)):
self.text = text
self.position = position
self.action = action
self.size = size
self.default_color = color
self.color = color
self.hover = False
self._setup_font()
def _setup_font(self):
"""Update the font surface with current color"""
self.font = pygame.font.Font(None, self.size)
color = (255, 255, 0) if self.hover else self.default_color # Yellow when hovered
self.surface = self.font.render(self.text, True, color)
self.rect = self.surface.get_rect(center=self.position)
def update_hover(self, mouse_pos):
"""Update hover state based on mouse position"""
old_hover = self.hover
self.hover = self.rect.collidepoint(mouse_pos)
if old_hover != self.hover:
self._setup_font()
def draw(self, screen):
"""Draw the menu item on the screen"""
screen.blit(self.surface, self.rect)
class Menu:
def __init__(self, width, height):
self.width = width
self.height = height
self.setup_menu_items()
self.title_font = pygame.font.Font(None, 72)
self.subtitle_font = pygame.font.Font(None, 36)
# Create title surfaces
self.title_surface = self.title_font.render("AI Snake Game", True, (0, 255, 0))
self.title_rect = self.title_surface.get_rect(center=(width//2, height//4))
self.subtitle_surface = self.subtitle_font.render("Choose Game Mode", True, (200, 200, 200))
self.subtitle_rect = self.subtitle_surface.get_rect(center=(width//2, height//4 + 50))
# Initialize first item as selected
self.selected_index = 0
self.menu_items[0].hover = True
self.menu_items[0]._setup_font()
def setup_menu_items(self):
# Calculate positions for menu items
start_y = self.height // 2
spacing = 50
center_x = self.width // 2
self.menu_items = [
MenuItem("Player Mode", (center_x, start_y), GameMode.PLAYER),
MenuItem("AI Easy", (center_x, start_y + spacing), GameMode.AI_EASY),
MenuItem("AI Medium", (center_x, start_y + spacing * 2), GameMode.AI_MEDIUM),
MenuItem("AI Hard", (center_x, start_y + spacing * 3), GameMode.AI_HARD),
MenuItem("Settings", (center_x, start_y + spacing * 4), GameMode.SETTINGS),
MenuItem("Quit", (center_x, start_y + spacing * 5), GameMode.QUIT, color=(255, 100, 100))
]
def handle_input(self, event):
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# Handle mouse clicks
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
self.selected_index = i
item.hover = True
item._setup_font()
return item.action
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
# Return the selected item's action
return self.menu_items[self.selected_index].action
elif event.key in (pygame.K_UP, pygame.K_DOWN):
# Update selected index
if event.key == pygame.K_UP:
self.selected_index = (self.selected_index - 1) % len(self.menu_items)
else:
self.selected_index = (self.selected_index + 1) % len(self.menu_items)
# Update hover states
for i, item in enumerate(self.menu_items):
item.hover = (i == self.selected_index)
item._setup_font()
return None
def update(self):
# Handle mouse hover
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
# Update selected index when mouse hovers
self.selected_index = i
item.hover = True
item._setup_font()
else:
# Keep keyboard selection visible
item.hover = (i == self.selected_index)
item._setup_font()
def draw(self, screen):
# Draw background
screen.fill((0, 0, 0))
# Draw title and subtitle
screen.blit(self.title_surface, self.title_rect)
screen.blit(self.subtitle_surface, self.subtitle_rect)
# Draw menu items
for item in self.menu_items:
item.draw(screen)
# Draw version and controls
version_text = "v0.1.0"
controls_text = "Arrow keys or mouse to navigate, Enter to select"
font = pygame.font.Font(None, 24)
version_surface = font.render(version_text, True, (100, 100, 100))
controls_surface = font.render(controls_text, True, (100, 100, 100))
screen.blit(version_surface, (10, self.height - 30))
screen.blit(controls_surface, (self.width - controls_surface.get_width() - 10, self.height - 30))
-92
View File
@@ -1,92 +0,0 @@
import pygame
from enum import Enum, auto
from typing import List, Tuple
class Direction(Enum):
UP = auto()
DOWN = auto()
LEFT = auto()
RIGHT = auto()
class Snake:
def __init__(self, start_pos: Tuple[int, int], block_size: int):
self.block_size = block_size
self.direction = Direction.RIGHT
self.body = [start_pos] # Head is at index 0
self.growing = False
# Movement cooldown
self.move_cooldown = 100 # milliseconds
self.last_move_time = 0
def move(self, current_time: int) -> bool:
"""Move the snake if enough time has passed. Returns True if moved."""
if current_time - self.last_move_time < self.move_cooldown:
return False
# Update position
head = self.body[0]
new_head = self._get_new_head_position(head)
# Insert new head
self.body.insert(0, new_head)
# Remove tail if not growing
if not self.growing:
self.body.pop()
else:
self.growing = False
self.last_move_time = current_time
return True
def _get_new_head_position(self, head: Tuple[int, int]) -> Tuple[int, int]:
x, y = head
if self.direction == Direction.UP:
return (x, y - self.block_size)
elif self.direction == Direction.DOWN:
return (x, y + self.block_size)
elif self.direction == Direction.LEFT:
return (x - self.block_size, y)
else: # Direction.RIGHT
return (x + self.block_size, y)
def grow(self):
"""Mark the snake to grow on next move"""
self.growing = True
def check_collision(self, width: int, height: int) -> bool:
"""Check if snake has collided with walls or itself"""
head = self.body[0]
# Check wall collision
if (head[0] < 0 or head[0] >= width or
head[1] < 0 or head[1] >= height):
return True
# Check self collision (skip head)
if head in self.body[1:]:
return True
return False
def change_direction(self, new_direction: Direction):
"""Change direction if it's not opposite to current direction"""
opposites = {
Direction.UP: Direction.DOWN,
Direction.DOWN: Direction.UP,
Direction.LEFT: Direction.RIGHT,
Direction.RIGHT: Direction.LEFT
}
if opposites[new_direction] != self.direction:
self.direction = new_direction
def draw(self, screen: pygame.Surface):
"""Draw the snake on the screen"""
for segment in self.body:
pygame.draw.rect(
screen,
(0, 255, 0), # Green color
pygame.Rect(segment[0], segment[1], self.block_size, self.block_size)
)
+20
View File
@@ -0,0 +1,20 @@
"""
Game UI Package
This package contains all user interface components.
"""
from .menu import Menu, GameMode
from .menu_item import MenuItem
from .settings_menu import SettingsMenu
from .pause_menu import PauseMenu
from .game_area import GameArea
__all__ = [
'Menu',
'GameMode',
'MenuItem',
'SettingsMenu',
'PauseMenu',
'GameArea'
]
+138
View File
@@ -0,0 +1,138 @@
"""
Game Area Module
This module provides the GameArea class that handles the rendering of the game area
and coordinate conversions between screen and grid coordinates.
"""
import pygame
from src.config import (
DEFAULT_PADDING,
DEFAULT_SCORE_HEIGHT,
)
from src.config.colors import *
from typing import Tuple
class GameArea:
"""Manages the game area rendering and coordinate conversions."""
def __init__(self, window_width, window_height, grid_size=20, grid_width=30, grid_height=30,
padding=DEFAULT_PADDING, score_height=DEFAULT_SCORE_HEIGHT):
# Grid properties
self.grid_size = grid_size
self.grid_width = grid_width
self.grid_height = grid_height
# Area properties
self.padding = padding
self.score_height = score_height
self.border_thickness = 4 # Increased border thickness
# Calculate game area dimensions
self.width = self.grid_width * self.grid_size
self.height = self.grid_height * self.grid_size
# Center the game area in the window
self.x = (window_width - self.width) // 2
self.y = self.score_height + self.padding
# Create rectangle for game bounds
self.rect = pygame.Rect(self.x, self.y, self.width, self.height)
# Create inner rectangle for gameplay area with thicker border
self.inner_rect = pygame.Rect(
self.x + self.border_thickness,
self.y + self.border_thickness,
self.width - (self.border_thickness * 2),
self.height - (self.border_thickness * 2)
)
self.screen_offset = (self.x, self.y)
def get_grid_pos(self, screen_x, screen_y):
"""Convert screen coordinates to grid position."""
grid_x = (screen_x - self.x) // self.grid_size
grid_y = (screen_y - self.y) // self.grid_size
return grid_x, grid_y
def get_screen_pos(self, grid_x, grid_y):
"""Convert grid position to screen coordinates."""
screen_x = self.x + (grid_x * self.grid_size)
screen_y = self.y + (grid_y * self.grid_size)
return screen_x, screen_y
def is_within_bounds(self, grid_x, grid_y):
"""Check if grid position is within game bounds."""
return 0 <= grid_x < self.grid_width and 0 <= grid_y < self.grid_height
def draw(self, screen):
"""Draw the game area boundary and background with modern effects."""
# Draw outer border with gradient effect
for i in range(self.border_thickness):
border_rect = pygame.Rect(
self.x + i,
self.y + i,
self.width - (i * 2),
self.height - (i * 2)
)
# Gradient from darker to lighter
color_factor = i / self.border_thickness
r = int(DARKER_GREEN[0] * (1 - color_factor) + FOREST_GREEN[0] * color_factor)
g = int(DARKER_GREEN[1] * (1 - color_factor) + FOREST_GREEN[1] * color_factor)
b = int(DARKER_GREEN[2] * (1 - color_factor) + FOREST_GREEN[2] * color_factor)
pygame.draw.rect(screen, (r, g, b), border_rect)
# Draw inner background
pygame.draw.rect(screen, DARK_GRAY, self.inner_rect)
# Draw subtle grid pattern
if hasattr(self, 'show_grid') and self.show_grid:
# Debug grid lines
for x in range(self.grid_width + 1):
start_pos = (self.x + x * self.grid_size, self.y)
end_pos = (self.x + x * self.grid_size, self.y + self.height)
pygame.draw.line(screen, GRID_COLOR, start_pos, end_pos, 1)
for y in range(self.grid_height + 1):
start_pos = (self.x, self.y + y * self.grid_size)
end_pos = (self.x + self.width, self.y + y * self.grid_size)
pygame.draw.line(screen, GRID_COLOR, start_pos, end_pos, 1)
else:
# Subtle grid dots with fade effect
for x in range(self.grid_width + 1):
for y in range(self.grid_height + 1):
pos_x = self.x + x * self.grid_size
pos_y = self.y + y * self.grid_size
# Calculate distance from center for fade effect
center_x = self.x + (self.width / 2)
center_y = self.y + (self.height / 2)
dist_x = abs(pos_x - center_x) / (self.width / 2)
dist_y = abs(pos_y - center_y) / (self.height / 2)
dist = min(1.0, (dist_x + dist_y) / 2)
# Fade dot color based on distance from center
dot_color = tuple(int(c * (1 - dist * 0.5)) for c in SUBTLE_GRID_COLOR)
pygame.draw.circle(screen, dot_color, (pos_x, pos_y), 1)
# Draw inner border glow
glow_colors = [
(int(NEON_GREEN[0] * 0.4), int(NEON_GREEN[1] * 0.4), int(NEON_GREEN[2] * 0.4)),
(int(NEON_GREEN[0] * 0.6), int(NEON_GREEN[1] * 0.6), int(NEON_GREEN[2] * 0.6)),
NEON_GREEN
]
for i, color in enumerate(glow_colors):
glow_rect = pygame.Rect(
self.inner_rect.x - i,
self.inner_rect.y - i,
self.inner_rect.width + (i * 2),
self.inner_rect.height + (i * 2)
)
pygame.draw.rect(screen, color, glow_rect, 1)
def grid_to_screen(self, grid_pos: Tuple[int, int]) -> Tuple[int, int]:
"""Convert grid coordinates to screen coordinates"""
x = self.rect.left + grid_pos[0] * self.grid_size + self.grid_size // 2
y = self.rect.top + grid_pos[1] * self.grid_size + self.grid_size // 2
return (x, y)
+127
View File
@@ -0,0 +1,127 @@
"""
Main Menu Module
This module provides the main menu interface for the game.
"""
import pygame
from enum import Enum, auto
from src.config import (
WINDOW_WIDTH,
WINDOW_HEIGHT,
TITLE_FONT_SIZE,
SUBTITLE_FONT_SIZE,
MENU_ITEM_SPACING
)
from src.config.colors import BLACK, GRAY
from src.ui.menu_item import MenuItem
class GameMode(Enum):
"""Available game modes."""
PLAYER = auto()
AI_EASY = auto()
AI_MEDIUM = auto()
AI_HARD = auto()
SETTINGS = auto()
class Menu:
"""Main menu interface."""
def __init__(self, width=WINDOW_WIDTH, height=WINDOW_HEIGHT):
"""Initialize the main menu."""
self.width = width
self.height = height
self.setup_menu_items()
# Create fonts
self.title_font = pygame.font.Font(None, TITLE_FONT_SIZE)
self.subtitle_font = pygame.font.Font(None, SUBTITLE_FONT_SIZE)
# Create title surfaces
self.title_surface = self.title_font.render("Snake Game", True, (0, 255, 0))
self.title_rect = self.title_surface.get_rect(center=(width//2, height//4))
# Initialize first item as selected
self.selected_index = 0
self.menu_items[0].hover = True
self.menu_items[0]._setup_font()
def setup_menu_items(self):
"""Setup the menu items."""
start_y = self.height // 2
spacing = MENU_ITEM_SPACING
center_x = self.width // 2
self.menu_items = [
MenuItem("Player Game", (center_x, start_y), GameMode.PLAYER),
MenuItem("AI Game (Easy)", (center_x, start_y + spacing), GameMode.AI_EASY),
MenuItem("AI Game (Medium)", (center_x, start_y + spacing * 2), GameMode.AI_MEDIUM),
MenuItem("AI Game (Hard)", (center_x, start_y + spacing * 3), GameMode.AI_HARD),
MenuItem("Settings", (center_x, start_y + spacing * 4), GameMode.SETTINGS),
MenuItem("Quit", (center_x, start_y + spacing * 5), 'quit')
]
def update(self):
"""Update menu state."""
# Handle mouse hover
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
# Update selected index when mouse hovers
self.selected_index = i
item.hover = True
item._setup_font()
else:
# Keep keyboard selection visible
item.hover = (i == self.selected_index)
item._setup_font()
def handle_input(self, event):
"""
Handle input events.
Returns:
GameMode or None: The selected game mode or None if no selection made
"""
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# Handle mouse clicks
mouse_pos = pygame.mouse.get_pos()
for item in self.menu_items:
if item.rect.collidepoint(mouse_pos):
return item.action
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
return self.menu_items[self.selected_index].action
elif event.key in (pygame.K_UP, pygame.K_DOWN):
# Update selected index
if event.key == pygame.K_UP:
self.selected_index = (self.selected_index - 1) % len(self.menu_items)
else:
self.selected_index = (self.selected_index + 1) % len(self.menu_items)
# Update hover states
for i, item in enumerate(self.menu_items):
item.hover = (i == self.selected_index)
item._setup_font()
return None
def draw(self, screen):
"""Draw the menu to the screen."""
# Draw background
screen.fill(BLACK)
# Draw title
screen.blit(self.title_surface, self.title_rect)
# Draw menu items
for item in self.menu_items:
item.draw(screen)
# Draw controls
controls_text = "Arrow keys or mouse to navigate, Enter to select"
controls_surface = self.subtitle_font.render(controls_text, True, GRAY)
screen.blit(controls_surface,
(self.width - controls_surface.get_width() - 10,
self.height - 30))
+84
View File
@@ -0,0 +1,84 @@
"""
Menu Item Module
This module provides the MenuItem class that represents a clickable menu item.
"""
import pygame
from src.config.colors import *
class MenuItem:
"""A clickable menu item with hover effects."""
def __init__(self, text, position, action, font_size_normal=36, font_size_hover=48):
"""
Initialize a menu item.
Args:
text: The text to display
position: (x, y) tuple for center position
action: String identifier for the action to take when clicked
font_size_normal: Font size when not hovered (default 36)
font_size_hover: Font size when hovered (default 48)
"""
self.text = text
self.position = position
self.action = action
self.hover = False
self.font_size_normal = font_size_normal
self.font_size_hover = font_size_hover
self._setup_font()
def _setup_font(self):
"""Setup the font based on hover state."""
size = self.font_size_hover if self.hover else self.font_size_normal
self.font = pygame.font.Font(None, size)
self.surface = self.font.render(self.text, True, GREEN if self.hover else WHITE)
self.rect = self.surface.get_rect(center=self.position)
def draw(self, screen):
"""Draw the menu item to the screen."""
screen.blit(self.surface, self.rect)
class NumberMenuItem(MenuItem):
"""A menu item that displays a number that can be adjusted with arrow keys."""
def __init__(self, text, position, action, min_value, max_value,
step=1, font_size_normal=36, font_size_hover=48):
"""
Initialize a number menu item.
Args:
text: The text to display
position: (x, y) tuple for center position
action: String identifier for the action to take when clicked
min_value: Minimum allowed value
max_value: Maximum allowed value
step: Amount to increment/decrement by (default 1)
font_size_normal: Font size when not hovered (default 36)
font_size_hover: Font size when hovered (default 48)
"""
super().__init__(text, position, action, font_size_normal, font_size_hover)
self.min_value = min_value
self.max_value = max_value
self.step = step
self.current_value = int(text.split(": ")[1]) # Extract number from text
def increment(self):
"""Increment the current value by step amount."""
if self.current_value + self.step <= self.max_value:
self.current_value += self.step
self._update_text()
def decrement(self):
"""Decrement the current value by step amount."""
if self.current_value - self.step >= self.min_value:
self.current_value -= self.step
self._update_text()
def _update_text(self):
"""Update the displayed text with new value."""
base_text = self.text.split(": ")[0]
self.text = f"{base_text}: {self.current_value}"
self._setup_font()
+129
View File
@@ -0,0 +1,129 @@
"""
Pause Menu Module
This module provides the pause menu interface that appears during gameplay.
"""
import pygame
from src.config import (
WINDOW_WIDTH,
WINDOW_HEIGHT,
TITLE_FONT_SIZE,
SUBTITLE_FONT_SIZE,
MENU_ITEM_SPACING
)
from src.config.colors import *
from src.ui.menu_item import MenuItem
class PauseMenu:
"""Pause menu interface."""
def __init__(self, width=WINDOW_WIDTH, height=WINDOW_HEIGHT):
"""
Initialize the pause menu.
Args:
width: Window width
height: Window height
"""
self.width = width
self.height = height
self.setup_menu_items()
self.title_font = pygame.font.Font(None, TITLE_FONT_SIZE)
self.subtitle_font = pygame.font.Font(None, SUBTITLE_FONT_SIZE)
# Create title surfaces
self.title_surface = self.title_font.render("Paused", True, (0, 255, 0))
self.title_rect = self.title_surface.get_rect(center=(width//2, height//3))
# Initialize first item as selected
self.selected_index = 0
self.menu_items[0].hover = True
self.menu_items[0]._setup_font()
def setup_menu_items(self):
"""Setup the menu items."""
start_y = self.height // 2
spacing = MENU_ITEM_SPACING
center_x = self.width // 2
self.menu_items = [
MenuItem("Resume",
(center_x, start_y),
'resume'),
MenuItem("Return to Menu",
(center_x, start_y + spacing),
'menu')
]
def update(self):
"""Update menu state."""
# Handle mouse hover
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
# Update selected index when mouse hovers
self.selected_index = i
item.hover = True
item._setup_font()
else:
# Keep keyboard selection visible
item.hover = (i == self.selected_index)
item._setup_font()
def handle_input(self, event):
"""
Handle input events.
Returns:
str or None: The action to take or None if no action
"""
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# Handle mouse clicks
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
self.selected_index = i
return item.action
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return 'resume'
elif event.key == pygame.K_RETURN:
return self.menu_items[self.selected_index].action
elif event.key in (pygame.K_UP, pygame.K_DOWN):
# Update selected index
if event.key == pygame.K_UP:
self.selected_index = (self.selected_index - 1) % len(self.menu_items)
else:
self.selected_index = (self.selected_index + 1) % len(self.menu_items)
# Update hover states
for i, item in enumerate(self.menu_items):
item.hover = (i == self.selected_index)
item._setup_font()
return None
def draw(self, screen):
"""Draw the menu to the screen."""
# Draw semi-transparent background
overlay = pygame.Surface((screen.get_width(), screen.get_height()))
overlay.fill(BLACK)
overlay.set_alpha(128)
screen.blit(overlay, (0, 0))
# Draw title
screen.blit(self.title_surface, self.title_rect)
# Draw menu items
for item in self.menu_items:
item.draw(screen)
# Draw controls
controls_text = "Arrow keys or mouse to navigate, Enter to select, Esc to resume"
controls_surface = self.subtitle_font.render(controls_text, True, GRAY)
screen.blit(controls_surface,
(self.width - controls_surface.get_width() - 10,
self.height - 30))
+159
View File
@@ -0,0 +1,159 @@
"""
Settings Menu Module
This module provides the settings menu interface for configuring game rules.
"""
import pygame
from src.config import (
WINDOW_WIDTH,
WINDOW_HEIGHT,
TITLE_FONT_SIZE,
SUBTITLE_FONT_SIZE,
MENU_ITEM_SPACING,
)
from src.config.colors import *
from src.ui.menu_item import MenuItem, NumberMenuItem
class SettingsMenu:
"""Settings menu interface."""
def __init__(self, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, rules=None):
"""
Initialize the settings menu.
Args:
width: Window width
height: Window height
rules: GameRules instance to modify
"""
self.width = width
self.height = height
self.rules = rules
self.setup_menu_items()
self.title_font = pygame.font.Font(None, TITLE_FONT_SIZE)
self.subtitle_font = pygame.font.Font(None, SUBTITLE_FONT_SIZE)
# Create title surfaces
self.title_surface = self.title_font.render("Settings", True, (0, 255, 0))
self.title_rect = self.title_surface.get_rect(center=(width//2, height//4))
# Initialize first item as selected
self.selected_index = 0
self.menu_items[0].hover = True
self.menu_items[0]._setup_font()
def setup_menu_items(self):
"""Setup the menu items."""
start_y = self.height // 2
spacing = MENU_ITEM_SPACING
center_x = self.width // 2
self.menu_items = [
MenuItem(f"Wrap Around: {'On' if self.rules.wrap_around else 'Off'}",
(center_x, start_y),
'toggle_wrap'),
MenuItem(f"Speed Increase: {'On' if self.rules.speed_increase else 'Off'}",
(center_x, start_y + spacing),
'toggle_speed'),
NumberMenuItem(f"Starting Length: {self.rules.starting_length}",
(center_x, start_y + spacing * 2),
'set_starting_length',
1, 10),
MenuItem("Back to Menu",
(center_x, start_y + spacing * 3),
'back')
]
def update(self):
"""Update menu state."""
# Handle mouse hover
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
# Update selected index when mouse hovers
self.selected_index = i
item.hover = True
item._setup_font()
else:
# Keep keyboard selection visible
item.hover = (i == self.selected_index)
item._setup_font()
def handle_input(self, event):
"""
Handle input events.
Returns:
str or None: The action to take or None if no action
"""
if event.type == pygame.MOUSEBUTTONDOWN:
# Handle mouse clicks
mouse_pos = pygame.mouse.get_pos()
for i, item in enumerate(self.menu_items):
if item.rect.collidepoint(mouse_pos):
self.selected_index = i
if event.button == 1:
if item.action == 'toggle_wrap':
self.rules.update_rule('wrap_around', not self.rules.wrap_around)
elif item.action == 'toggle_speed':
self.rules.speed_increase = not self.rules.speed_increase
item.text = f"Speed Increase: {'On' if self.rules.speed_increase else 'Off'}"
item._setup_font()
elif item.action == 'set_starting_length':
item.increment()
self.rules.update_rule('starting_length', item.current_value)
elif item.action == 'back':
return 'back'
elif event.button == 3:
if item.action == 'set_starting_length':
item.decrement()
self.rules.update_rule('starting_length', item.current_value)
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return 'back'
elif event.key == pygame.K_RETURN:
item = self.menu_items[self.selected_index]
if item.action == 'toggle_wrap':
self.rules.update_rule('wrap_around', not self.rules.wrap_around)
elif item.action == 'toggle_speed':
self.rules.update_rule('speed_increase', not self.rules.speed_increase)
elif item.action == 'set_starting_length':
item.increment()
self.rules.update_rule('starting_length', item.current_value)
elif item.action == 'back':
return 'back'
elif event.key in (pygame.K_UP, pygame.K_DOWN):
# Update selected index
if event.key == pygame.K_UP:
self.selected_index = (self.selected_index - 1) % len(self.menu_items)
else:
self.selected_index = (self.selected_index + 1) % len(self.menu_items)
# Update hover states
for i, item in enumerate(self.menu_items):
item.hover = (i == self.selected_index)
item._setup_font()
return None
def draw(self, screen):
"""Draw the menu to the screen."""
# Draw background
screen.fill(BLACK)
# Draw title
screen.blit(self.title_surface, self.title_rect)
# Draw menu items
for item in self.menu_items:
item.draw(screen)
# Draw controls
controls_text = "Arrow keys or mouse to navigate, Enter to select, Esc to go back"
controls_surface = self.subtitle_font.render(controls_text, True, GRAY)
screen.blit(controls_surface,
(self.width - controls_surface.get_width() - 10,
self.height - 30))
+19
View File
@@ -0,0 +1,19 @@
"""
Test suite for the AI Snake Game.
This package contains all test modules including:
- Unit tests for game components
- Integration tests for game mechanics
- Performance tests for AI algorithms
"""
# Import test utilities and fixtures
from conftest import game_config, mock_screen
__version__ = '0.1.0'
# Define test utilities available for import
__all__ = [
'game_config',
'mock_screen',
]
+33
View File
@@ -0,0 +1,33 @@
import pytest
import pygame
import sys
import os
# Add src directory to Python path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
def pytest_configure(config):
"""Initialize pygame once before any tests run"""
# Set SDL to use software rendering and disable audio to reduce resource usage
os.environ['SDL_VIDEODRIVER'] = 'dummy'
os.environ['SDL_AUDIODRIVER'] = 'dummy'
pygame.init()
def pytest_unconfigure(config):
"""Clean up pygame after all tests are done"""
pygame.quit()
@pytest.fixture
def game_config():
"""Basic game configuration"""
return {
'width': 400, # Smaller dimensions for testing
'height': 300,
'block_size': 20,
'fps': 60
}
@pytest.fixture
def mock_screen(game_config):
"""Create a mock pygame screen"""
return pygame.Surface((game_config['width'], game_config['height']))
+60
View File
@@ -0,0 +1,60 @@
import pytest
from src.core import Food
def test_food_initialization():
"""Test food initialization"""
food = Food(20)
assert food.block_size == 20
assert food.color == (255, 0, 0) # Default red color
assert food.position == (0, 0) # Default position
def test_food_spawn():
"""Test food spawning mechanics"""
food = Food(20)
width, height = 800, 600
snake_body = [(100, 100), (120, 100)] # Mock snake body
# Test spawning
food.spawn(width, height, snake_body)
# Check if food is within bounds
assert 0 <= food.position[0] < width
assert 0 <= food.position[1] < height
# Check if position aligns with grid
assert food.position[0] % food.block_size == 0
assert food.position[1] % food.block_size == 0
# Check if food doesn't spawn on snake
assert food.position not in snake_body
def test_food_collision():
"""Test food collision detection"""
food = Food(20)
food.position = (100, 100)
# Test collision
assert food.check_collision((100, 100)) == True
# Test no collision
assert food.check_collision((120, 120)) == False
def test_food_spawn_full_grid():
"""Test food spawning when grid is mostly occupied"""
food = Food(20)
width, height = 60, 60 # Small grid
# Create a snake that occupies all positions except (40, 40)
all_positions = [(x, y) for x in range(0, 60, 20) for y in range(0, 60, 20)]
free_spot = (40, 40)
snake_body = [pos for pos in all_positions if pos != free_spot]
# Verify our test setup is correct
assert len(snake_body) == len(all_positions) - 1
assert free_spot not in snake_body
# Spawn food
food.spawn(width, height, snake_body)
# Food must spawn in the only free spot
assert food.position == free_spot
+73
View File
@@ -0,0 +1,73 @@
from src.core import Snake, Direction
def test_snake_initialization():
"""Test snake initialization with default values"""
snake = Snake((100, 100), 20)
assert snake.block_size == 20
assert snake.direction == Direction.RIGHT
assert len(snake.body) == 1
assert snake.body[0] == (100, 100)
assert not snake.growing
def test_snake_movement():
"""Test snake movement in different directions"""
snake = Snake((100, 100), 20)
# Test right movement (default direction)
snake.move(100) # time parameter
assert snake.body[0] == (120, 100)
# Test down movement
snake.change_direction(Direction.DOWN)
snake.move(200)
assert snake.body[0] == (120, 120)
# Test left movement
snake.change_direction(Direction.LEFT)
snake.move(300)
assert snake.body[0] == (100, 120)
# Test up movement
snake.change_direction(Direction.UP)
snake.move(400)
assert snake.body[0] == (100, 100)
def test_snake_growth():
"""Test snake growth when eating food"""
snake = Snake((100, 100), 20)
original_length = len(snake.body)
snake.grow()
snake.move(100)
assert len(snake.body) == original_length + 1
def test_snake_collision():
"""Test snake collision detection"""
snake = Snake((100, 100), 20)
# Test wall collision
assert snake.check_collision(200, 200) == False # No collision
snake.body[0] = (-20, 100) # Move outside left wall
assert snake.check_collision(200, 200) == True
# Test self collision
snake = Snake((100, 100), 20)
snake.body = [(100, 100), (120, 100), (120, 120), (100, 120), (100, 100)]
assert snake.check_collision(200, 200) == True
def test_invalid_direction_change():
"""Test that snake cannot reverse direction"""
snake = Snake((100, 100), 20)
# Try to change to opposite direction (LEFT while going RIGHT)
snake.change_direction(Direction.LEFT)
assert snake.direction == Direction.RIGHT
# Valid direction change
snake.change_direction(Direction.DOWN)
assert snake.direction == Direction.DOWN
# Try to change to opposite direction (UP while going DOWN)
snake.change_direction(Direction.UP)
assert snake.direction == Direction.DOWN
+15
View File
@@ -0,0 +1,15 @@
{
"timesteps": 3000000,
"learning_rate": 3e-4,
"batch_size": 256,
"n_envs": 16,
"n_steps": 2048,
"gamma": 0.99,
"ent_coef": 0.1,
"n_epochs": 10,
"gae_lambda": 0.95,
"clip_range": 0.2,
"vf_coef": 0.5,
"max_grad_norm": 0.5,
"normalize_advantage": true
}