added completly new version for haslach 2025

This commit is contained in:
fotobox
2025-03-17 03:47:13 +01:00
parent 152832515c
commit 769ab91da8
2333 changed files with 409208 additions and 341 deletions

View File

@@ -0,0 +1,37 @@
# python -m pygame.docs
import os
import webbrowser
from urllib.parse import quote, urlunparse
def _iterpath(path):
path, last = os.path.split(path)
if last:
yield from _iterpath(path)
yield last
# for test suite to confirm pygame built with local docs
def has_local_docs():
pkg_dir = os.path.dirname(os.path.abspath(__file__))
main_page = os.path.join(pkg_dir, "generated", "index.html")
return os.path.exists(main_page)
def open_docs():
pkg_dir = os.path.dirname(os.path.abspath(__file__))
main_page = os.path.join(pkg_dir, "generated", "index.html")
if os.path.exists(main_page):
url_path = quote("/".join(_iterpath(main_page)))
drive, rest = os.path.splitdrive(__file__)
if drive:
url_path = f"{drive}/{url_path}"
url = urlunparse(("file", "", url_path, "", "", ""))
else:
url = "https://www.pygame.org/docs/"
webbrowser.open(url)
if __name__ == "__main__":
open_docs()

View File

@@ -0,0 +1,504 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 176 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 125 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 392 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,25 @@
pygame C API
============
.. toctree::
:maxdepth: 1
:glob:
c_api/slots.rst
c_api/base.rst
c_api/bufferproxy.rst
c_api/color.rst
c_api/display.rst
c_api/event.rst
c_api/freetype.rst
c_api/mixer.rst
c_api/rect.rst
c_api/rwobject.rst
c_api/surface.rst
c_api/surflock.rst
c_api/version.rst
src_c/include/ contains header files for applications
that use the pygame C API, while src_c/ contains
headers used by pygame internally.

View File

@@ -0,0 +1,17 @@
File Path Function Arguments
============================
A pygame function or method which takes a file path argument will accept
either a Unicode or a byte (8-bit or ASCII character) string.
Unicode strings are translated to Python's default filesystem encoding,
as returned by sys.getfilesystemencoding(). A Unicode code point
above U+FFFF (``\uFFFF``) can be coded directly with a 32-bit escape sequences
(``\Uxxxxxxxx``), even for Python interpreters built with an UCS-2
(16-bit character) Unicode type. Byte strings are passed
to the operating system unchanged.
Null characters (``\x00``) are not permitted in the path, raising an exception.
An exception is also raised if an Unicode file path cannot be encoded.
How UTF-16 surrogate codes are handled is Python-interpreter-dependent.
Use UTF-32 code points and 32-bit escape sequences instead.
The exception types are function-dependent.

View File

@@ -0,0 +1,213 @@
Pygame Front Page
=================
.. toctree::
:maxdepth: 2
:glob:
:hidden:
ref/*
tut/*
tut/en/**/*
tut/ko/**/*
c_api
filepaths
logos
Quick start
-----------
Welcome to pygame! Once you've got pygame installed (:code:`pip install pygame` or
:code:`pip3 install pygame` for most people), the next question is how to get a game
loop running. Pygame, unlike some other libraries, gives you full control of program
execution. That freedom means it is easy to mess up in your initial steps.
Here is a good example of a basic setup (opens the window, updates the screen, and handles events)--
.. literalinclude:: ref/code_examples/base_script.py
Here is a slightly more fleshed out example, which shows you how to move something
(a circle in this case) around on screen--
.. literalinclude:: ref/code_examples/base_script_example.py
For more in depth reference, check out the :ref:`tutorials-reference-label`
section below, check out a video tutorial (`I'm a fan of this one
<https://www.youtube.com/watch?v=AY9MnQ4x3zk>`_), or reference the API
documentation by module.
Documents
---------
`Readme`_
Basic information about pygame: what it is, who is involved, and where to find it.
`Install`_
Steps needed to compile pygame on several platforms.
Also help on finding and installing prebuilt binaries for your system.
:doc:`filepaths`
How pygame handles file system paths.
:doc:`Pygame Logos <logos>`
The logos of Pygame in different resolutions.
`LGPL License`_
This is the license pygame is distributed under.
It provides for pygame to be distributed with open source and commercial software.
Generally, if pygame is not changed, it can be used with any type of program.
.. _tutorials-reference-label:
Tutorials
---------
:doc:`Introduction to Pygame <tut/PygameIntro>`
An introduction to the basics of pygame.
This is written for users of Python and appeared in volume two of the Py magazine.
:doc:`Import and Initialize <tut/ImportInit>`
The beginning steps on importing and initializing pygame.
The pygame package is made of several modules.
Some modules are not included on all platforms.
:doc:`How do I move an Image? <tut/MoveIt>`
A basic tutorial that covers the concepts behind 2D computer animation.
Information about drawing and clearing objects to make them appear animated.
:doc:`Chimp Tutorial, Line by Line <tut/ChimpLineByLine>`
The pygame examples include a simple program with an interactive fist and a chimpanzee.
This was inspired by the annoying flash banner of the early 2000s.
This tutorial examines every line of code used in the example.
:doc:`Sprite Module Introduction <tut/SpriteIntro>`
Pygame includes a higher level sprite module to help organize games.
The sprite module includes several classes that help manage details found in almost all games types.
The Sprite classes are a bit more advanced than the regular pygame modules,
and need more understanding to be properly used.
:doc:`Surfarray Introduction <tut/SurfarrayIntro>`
Pygame used the NumPy python module to allow efficient per pixel effects on images.
Using the surface arrays is an advanced feature that allows custom effects and filters.
This also examines some of the simple effects from the pygame example, arraydemo.py.
:doc:`Camera Module Introduction <tut/CameraIntro>`
Pygame, as of 1.9, has a camera module that allows you to capture images,
watch live streams, and do some basic computer vision.
This tutorial covers those use cases.
:doc:`Newbie Guide <tut/newbieguide>`
A list of thirteen helpful tips for people to get comfortable using pygame.
:doc:`Making Games Tutorial <tut/MakeGames>`
A large tutorial that covers the bigger topics needed to create an entire game.
:doc:`Display Modes <tut/DisplayModes>`
Getting a display surface for the screen.
:doc:`한국어 튜토리얼 (Korean Tutorial) <tut/ko/빨간블록 검은블록/개요>`
빨간블록 검은블록
Reference
---------
:ref:`genindex`
A list of all functions, classes, and methods in the pygame package.
:doc:`ref/bufferproxy`
An array protocol view of surface pixels
:doc:`ref/color`
Color representation.
:doc:`ref/cursors`
Loading and compiling cursor images.
:doc:`ref/display`
Configure the display surface.
:doc:`ref/draw`
Drawing simple shapes like lines and ellipses to surfaces.
:doc:`ref/event`
Manage the incoming events from various input devices and the windowing platform.
:doc:`ref/examples`
Various programs demonstrating the use of individual pygame modules.
:doc:`ref/font`
Loading and rendering TrueType fonts.
:doc:`ref/freetype`
Enhanced pygame module for loading and rendering font faces.
:doc:`ref/gfxdraw`
Anti-aliasing draw functions.
:doc:`ref/image`
Loading, saving, and transferring of surfaces.
:doc:`ref/joystick`
Manage the joystick devices.
:doc:`ref/key`
Manage the keyboard device.
:doc:`ref/locals`
Pygame constants.
:doc:`ref/mixer`
Load and play sounds
:doc:`ref/mouse`
Manage the mouse device and display.
:doc:`ref/music`
Play streaming music tracks.
:doc:`ref/pygame`
Top level functions to manage pygame.
:doc:`ref/pixelarray`
Manipulate image pixel data.
:doc:`ref/rect`
Flexible container for a rectangle.
:doc:`ref/scrap`
Native clipboard access.
:doc:`ref/sndarray`
Manipulate sound sample data.
:doc:`ref/sprite`
Higher level objects to represent game images.
:doc:`ref/surface`
Objects for images and the screen.
:doc:`ref/surfarray`
Manipulate image pixel data.
:doc:`ref/tests`
Test pygame.
:doc:`ref/time`
Manage timing and framerate.
:doc:`ref/transform`
Resize and move images.
:doc:`pygame C API <c_api>`
The C api shared amongst pygame extension modules.
:ref:`search`
Search pygame documents by keyword.
.. _Readme: ../wiki/about
.. _Install: ../wiki/GettingStarted#Pygame%20Installation
.. _LGPL License: LGPL.txt

View File

@@ -0,0 +1,47 @@
*************************************************
Pygame Logos Page
*************************************************
Pygame Logos
============
These logos are available for use in your own game projects.
Please put them up wherever you see fit. The logo was created
by TheCorruptor on July 29, 2001 and upscaled by Mega_JC on
August 29, 2021.
.. container:: fullwidth
.. image:: _static/pygame_logo.png
| `pygame_logo.svg <_static/pygame_logo.svg>`_
| `pygame_logo.png <_static/pygame_logo.png>`_ - 1561 x 438
.. image:: _static/pygame_lofi.png
| `pygame_lofi.svg <_static/pygame_lofi.svg>`_
| `pygame_lofi.png <_static/pygame_lofi.png>`_ - 1561 x 438
.. image:: _static/pygame_powered.png
| `pygame_powered.svg <_static/pygame_powered.svg>`_
| `pygame_powered.png <_static/pygame_powered.png>`_ - 1617 x 640
.. image:: _static/pygame_tiny.png
| `pygame_tiny.png <_static/pygame_tiny.png>`_ - 214 x 60
.. image:: _static/pygame_powered_lowres.png
| `pygame_powered_lowres.png <_static/pygame_powered_lowres.png>`_ - 101 x 40
There is a higher resolution layered photoshop image
available `here <https://www.pygame.org/ftp/pygame_logo.psd>`_. *(1.3 MB)*
Legacy logos
------------
.. container:: fullwidth
`legacy_logos.zip <_static/legacy_logos.zip>`_ - 50.1 KB

View File

@@ -0,0 +1,113 @@
.. include:: common.txt
.. default-domain:: py
:class:`pygame.BufferProxy`
===========================
.. currentmodule:: pygame
.. class:: BufferProxy
| :sl:`pygame object to export a surface buffer through an array protocol`
| :sg:`BufferProxy(<parent>) -> BufferProxy`
:class:`BufferProxy` is a pygame support type, designed as the return value
of the :meth:`Surface.get_buffer` and :meth:`Surface.get_view` methods.
For all Python versions a :class:`BufferProxy` object exports a C struct
and Python level array interface on behalf of its parent object's buffer.
A new buffer interface is also exported.
In pygame, :class:`BufferProxy` is key to implementing the
:mod:`pygame.surfarray` module.
:class:`BufferProxy` instances can be created directly from Python code,
either for a parent that exports an interface, or from a Python ``dict``
describing an object's buffer layout. The dict entries are based on the
Python level array interface mapping. The following keys are recognized:
``"shape"`` : tuple
The length of each array dimension as a tuple of integers. The
length of the tuple is the number of dimensions in the array.
``"typestr"`` : string
The array element type as a length 3 string. The first character
gives byteorder, '<' for little-endian, '>' for big-endian, and
'\|' for not applicable. The second character is the element type,
'i' for signed integer, 'u' for unsigned integer, 'f' for floating
point, and 'V' for an chunk of bytes. The third character gives the
bytesize of the element, from '1' to '9' bytes. So, for example,
"<u4" is an unsigned 4 byte little-endian integer, such as a
32 bit pixel on a PC, while "\|V3" would represent a 24 bit pixel,
which has no integer equivalent.
``"data"`` : tuple
The physical buffer start address and a read-only flag as a length
2 tuple. The address is an integer value, while the read-only flag
is a bool—``False`` for writable, ``True`` for read-only.
``"strides"`` : tuple : (optional)
Array stride information as a tuple of integers. It is required
only of non C-contiguous arrays. The tuple length must match
that of ``"shape"``.
``"parent"`` : object : (optional)
The exporting object. It can be used to keep the parent object
alive while its buffer is visible.
``"before"`` : callable : (optional)
Callback invoked when the :class:`BufferProxy` instance
exports the buffer. The callback is given one argument, the
``"parent"`` object if given, otherwise ``None``.
The callback is useful for setting a lock on the parent.
``"after"`` : callable : (optional)
Callback invoked when an exported buffer is released.
The callback is passed on argument, the ``"parent"`` object if given,
otherwise None. The callback is useful for releasing a lock on the
parent.
The BufferProxy class supports subclassing, instance variables, and weak
references.
.. versionadded:: 1.8.0
.. versionextended:: 1.9.2
.. attribute:: parent
| :sl:`Return wrapped exporting object.`
| :sg:`parent -> Surface`
| :sg:`parent -> <parent>`
The :class:`Surface` which returned the :class:`BufferProxy` object or
the object passed to a :class:`BufferProxy` call.
.. attribute:: length
| :sl:`The size, in bytes, of the exported buffer.`
| :sg:`length -> int`
The number of valid bytes of data exported. For discontinuous data,
that is data which is not a single block of memory, the bytes within
the gaps are excluded from the count. This property is equivalent to
the ``Py_buffer`` C struct ``len`` field.
.. attribute:: raw
| :sl:`A copy of the exported buffer as a single block of bytes.`
| :sg:`raw -> bytes`
The buffer data as a ``str``/``bytes`` object.
Any gaps in the exported data are removed.
.. method:: write
| :sl:`Write raw bytes to object buffer.`
| :sg:`write(buffer, offset=0)`
Overwrite bytes in the parent object's data. The data must be C or F
contiguous, otherwise a ValueError is raised. Argument `buffer` is a
``str``/``bytes`` object. An optional offset gives a
start position, in bytes, within the buffer where overwriting begins.
If the offset is negative or greater that or equal to the buffer proxy's
:attr:`length` value, an ``IndexException`` is raised.
If ``len(buffer) > proxy.length + offset``, a ``ValueError`` is raised.

View File

@@ -0,0 +1,247 @@
.. include:: common.txt
:mod:`pygame.camera`
====================
.. module:: pygame.camera
:synopsis: pygame module for camera use
| :sl:`pygame module for camera use`
Pygame currently supports Linux (V4L2) and Windows (MSMF) cameras natively,
with wider platform support available via an integrated OpenCV backend.
.. versionadded:: 2.0.2 Windows native camera support
.. versionadded:: 2.0.3 New OpenCV backends
EXPERIMENTAL!: This API may change or disappear in later pygame releases. If
you use this, your code will very likely break with the next pygame release.
The Bayer to ``RGB`` function is based on:
::
Sonix SN9C101 based webcam basic I/F routines
Copyright (C) 2004 Takafumi Mizuno <taka-qce@ls-a.jp>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
New in pygame 1.9.0.
.. function:: init
| :sl:`Module init`
| :sg:`init(backend = None) -> None`
This function starts up the camera module, choosing the best webcam backend
it can find for your system. This is not guaranteed to succeed, and may even
attempt to import third party modules, like `OpenCV`. If you want to
override its backend choice, you can call pass the name of the backend you
want into this function. More about backends in
:func:`get_backends()`.
.. versionchanged:: 2.0.3 Option to explicitly select backend
.. ## pygame.camera.init ##
.. function:: get_backends
| :sl:`Get the backends supported on this system`
| :sg:`get_backends() -> [str]`
This function returns every backend it thinks has a possibility of working
on your system, in order of priority.
pygame.camera Backends:
::
Backend OS Description
---------------------------------------------------------------------------------
_camera (MSMF) Windows Builtin, works on Windows 8+ Python3
_camera (V4L2) Linux Builtin
OpenCV Any Uses `opencv-python` module, can't enumerate cameras
OpenCV-Mac Mac Same as OpenCV, but has camera enumeration
VideoCapture Windows Uses abandoned `VideoCapture` module, can't enumerate
cameras, may be removed in the future
There are two main differences among backends.
The _camera backends are built in to pygame itself, and require no third
party imports. All the other backends do. For the OpenCV and VideoCapture
backends, those modules need to be installed on your system.
The other big difference is "camera enumeration." Some backends don't have
a way to list out camera names, or even the number of cameras on the
system. In these cases, :func:`list_cameras()` will return
something like ``[0]``. If you know you have multiple cameras on the
system, these backend ports will pass through a "camera index number"
through if you use that as the ``device`` parameter.
.. versionadded:: 2.0.3
.. ## pygame.camera.get_backends ##
.. function:: colorspace
| :sl:`Surface colorspace conversion`
| :sg:`colorspace(Surface, format, DestSurface = None) -> Surface`
Allows for conversion from "RGB" to a destination colorspace of "HSV" or
"YUV". The source and destination surfaces must be the same size and pixel
depth. This is useful for computer vision on devices with limited processing
power. Capture as small of an image as possible, ``transform.scale()`` it
even smaller, and then convert the colorspace to ``YUV`` or ``HSV`` before
doing any processing on it.
.. ## pygame.camera.colorspace ##
.. function:: list_cameras
| :sl:`returns a list of available cameras`
| :sg:`list_cameras() -> [cameras]`
Checks the computer for available cameras and returns a list of strings of
camera names, ready to be fed into :class:`pygame.camera.Camera`.
If the camera backend doesn't support webcam enumeration, this will return
something like ``[0]``. See :func:`get_backends()` for much more
information.
.. ## pygame.camera.list_cameras ##
.. class:: Camera
| :sl:`load a camera`
| :sg:`Camera(device, (width, height), format) -> Camera`
Loads a camera. On Linux, the device is typically something like
"/dev/video0". Default width and height are 640 by 480.
Format is the desired colorspace of the output.
This is useful for computer vision purposes. The default is
``RGB``. The following are supported:
* ``RGB`` - Red, Green, Blue
* ``YUV`` - Luma, Blue Chrominance, Red Chrominance
* ``HSV`` - Hue, Saturation, Value
.. method:: start
| :sl:`opens, initializes, and starts capturing`
| :sg:`start() -> None`
Opens the camera device, attempts to initialize it, and begins recording
images to a buffer. The camera must be started before any of the below
functions can be used.
.. ## Camera.start ##
.. method:: stop
| :sl:`stops, uninitializes, and closes the camera`
| :sg:`stop() -> None`
Stops recording, uninitializes the camera, and closes it. Once a camera
is stopped, the below functions cannot be used until it is started again.
.. ## Camera.stop ##
.. method:: get_controls
| :sl:`gets current values of user controls`
| :sg:`get_controls() -> (hflip = bool, vflip = bool, brightness)`
If the camera supports it, get_controls will return the current settings
for horizontal and vertical image flip as bools and brightness as an int.
If unsupported, it will return the default values of (0, 0, 0). Note that
the return values here may be different than those returned by
set_controls, though these are more likely to be correct.
.. ## Camera.get_controls ##
.. method:: set_controls
| :sl:`changes camera settings if supported by the camera`
| :sg:`set_controls(hflip = bool, vflip = bool, brightness) -> (hflip = bool, vflip = bool, brightness)`
Allows you to change camera settings if the camera supports it. The
return values will be the input values if the camera claims it succeeded
or the values previously in use if not. Each argument is optional, and
the desired one can be chosen by supplying the keyword, like hflip. Note
that the actual settings being used by the camera may not be the same as
those returned by set_controls. On Windows, :code:`hflip` and :code:`vflip` are
implemented by pygame, not by the Camera, so they should always work, but
:code:`brightness` is unsupported.
.. ## Camera.set_controls ##
.. method:: get_size
| :sl:`returns the dimensions of the images being recorded`
| :sg:`get_size() -> (width, height)`
Returns the current dimensions of the images being captured by the
camera. This will return the actual size, which may be different than the
one specified during initialization if the camera did not support that
size.
.. ## Camera.get_size ##
.. method:: query_image
| :sl:`checks if a frame is ready`
| :sg:`query_image() -> bool`
If an image is ready to get, it returns true. Otherwise it returns false.
Note that some webcams will always return False and will only queue a
frame when called with a blocking function like :func:`get_image()`.
On Windows (MSMF), and the OpenCV backends, :func:`query_image()`
should be reliable, though. This is useful to separate the framerate of
the game from that of the camera without having to use threading.
.. ## Camera.query_image ##
.. method:: get_image
| :sl:`captures an image as a Surface`
| :sg:`get_image(Surface = None) -> Surface`
Pulls an image off of the buffer as an ``RGB`` Surface. It can optionally
reuse an existing Surface to save time. The bit-depth of the surface is
24 bits on Linux, 32 bits on Windows, or the same as the optionally
supplied Surface.
.. ## Camera.get_image ##
.. method:: get_raw
| :sl:`returns an unmodified image as bytes`
| :sg:`get_raw() -> bytes`
Gets an image from a camera as a string in the native pixelformat of the
camera. Useful for integration with other libraries. This returns a
bytes object
.. ## Camera.get_raw ##
.. ## pygame.camera.Camera ##
.. ## pygame.camera ##

View File

@@ -0,0 +1,310 @@
.. include:: common.txt
:mod:`pygame.cdrom`
===================
.. module:: pygame.cdrom
:synopsis: pygame module for audio cdrom control
| :sl:`pygame module for audio cdrom control`
.. warning::
This module is non functional in pygame 2.0 and above, unless you have manually compiled pygame with SDL1.
This module will not be supported in the future.
One alternative for python cdrom functionality is `pycdio <https://pypi.org/project/pycdio/>`_.
The cdrom module manages the ``CD`` and ``DVD`` drives on a computer. It can
also control the playback of audio CDs. This module needs to be initialized
before it can do anything. Each ``CD`` object you create represents a cdrom
drive and must also be initialized individually before it can do most things.
.. function:: init
| :sl:`initialize the cdrom module`
| :sg:`init() -> None`
Initialize the cdrom module. This will scan the system for all ``CD``
devices. The module must be initialized before any other functions will
work. This automatically happens when you call ``pygame.init()``.
It is safe to call this function more than once.
.. ## pygame.cdrom.init ##
.. function:: quit
| :sl:`uninitialize the cdrom module`
| :sg:`quit() -> None`
Uninitialize the cdrom module. After you call this any existing ``CD``
objects will no longer work.
It is safe to call this function more than once.
.. ## pygame.cdrom.quit ##
.. function:: get_init
| :sl:`true if the cdrom module is initialized`
| :sg:`get_init() -> bool`
Test if the cdrom module is initialized or not. This is different than the
``CD.init()`` since each drive must also be initialized individually.
.. ## pygame.cdrom.get_init ##
.. function:: get_count
| :sl:`number of cd drives on the system`
| :sg:`get_count() -> count`
Return the number of cd drives on the system. When you create ``CD`` objects
you need to pass an integer id that must be lower than this count. The count
will be 0 if there are no drives on the system.
.. ## pygame.cdrom.get_count ##
.. class:: CD
| :sl:`class to manage a cdrom drive`
| :sg:`CD(id) -> CD`
You can create a ``CD`` object for each cdrom on the system. Use
``pygame.cdrom.get_count()`` to determine how many drives actually exist.
The id argument is an integer of the drive, starting at zero.
The ``CD`` object is not initialized, you can only call ``CD.get_id()`` and
``CD.get_name()`` on an uninitialized drive.
It is safe to create multiple ``CD`` objects for the same drive, they will
all cooperate normally.
.. method:: init
| :sl:`initialize a cdrom drive for use`
| :sg:`init() -> None`
Initialize the cdrom drive for use. The drive must be initialized for
most ``CD`` methods to work. Even if the rest of pygame has been
initialized.
There may be a brief pause while the drive is initialized. Avoid
``CD.init()`` if the program should not stop for a second or two.
.. ## CD.init ##
.. method:: quit
| :sl:`uninitialize a cdrom drive for use`
| :sg:`quit() -> None`
Uninitialize a drive for use. Call this when your program will not be
accessing the drive for awhile.
.. ## CD.quit ##
.. method:: get_init
| :sl:`true if this cd device initialized`
| :sg:`get_init() -> bool`
Test if this ``CDROM`` device is initialized. This is different than the
``pygame.cdrom.init()`` since each drive must also be initialized
individually.
.. ## CD.get_init ##
.. method:: play
| :sl:`start playing audio`
| :sg:`play(track, start=None, end=None) -> None`
Playback audio from an audio cdrom in the drive. Besides the track number
argument, you can also pass a starting and ending time for playback. The
start and end time are in seconds, and can limit the section of an audio
track played.
If you pass a start time but no end, the audio will play to the end of
the track. If you pass a start time and 'None' for the end time, the
audio will play to the end of the entire disc.
See the ``CD.get_numtracks()`` and ``CD.get_track_audio()`` to find
tracks to playback.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.play ##
.. method:: stop
| :sl:`stop audio playback`
| :sg:`stop() -> None`
Stops playback of audio from the cdrom. This will also lose the current
playback position. This method does nothing if the drive isn't already
playing audio.
.. ## CD.stop ##
.. method:: pause
| :sl:`temporarily stop audio playback`
| :sg:`pause() -> None`
Temporarily stop audio playback on the ``CD``. The playback can be
resumed at the same point with the ``CD.resume()`` method. If the ``CD``
is not playing this method does nothing.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.pause ##
.. method:: resume
| :sl:`unpause audio playback`
| :sg:`resume() -> None`
Unpause a paused ``CD``. If the ``CD`` is not paused or already playing,
this method does nothing.
.. ## CD.resume ##
.. method:: eject
| :sl:`eject or open the cdrom drive`
| :sg:`eject() -> None`
This will open the cdrom drive and eject the cdrom. If the drive is
playing or paused it will be stopped.
.. ## CD.eject ##
.. method:: get_id
| :sl:`the index of the cdrom drive`
| :sg:`get_id() -> id`
Returns the integer id that was used to create the ``CD`` instance. This
method can work on an uninitialized ``CD``.
.. ## CD.get_id ##
.. method:: get_name
| :sl:`the system name of the cdrom drive`
| :sg:`get_name() -> name`
Return the string name of the drive. This is the system name used to
represent the drive. It is often the drive letter or device name. This
method can work on an uninitialized ``CD``.
.. ## CD.get_name ##
.. method:: get_busy
| :sl:`true if the drive is playing audio`
| :sg:`get_busy() -> bool`
Returns True if the drive busy playing back audio.
.. ## CD.get_busy ##
.. method:: get_paused
| :sl:`true if the drive is paused`
| :sg:`get_paused() -> bool`
Returns True if the drive is currently paused.
.. ## CD.get_paused ##
.. method:: get_current
| :sl:`the current audio playback position`
| :sg:`get_current() -> track, seconds`
Returns both the current track and time of that track. This method works
when the drive is either playing or paused.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_current ##
.. method:: get_empty
| :sl:`False if a cdrom is in the drive`
| :sg:`get_empty() -> bool`
Return False if there is a cdrom currently in the drive. If the drive is
empty this will return True.
.. ## CD.get_empty ##
.. method:: get_numtracks
| :sl:`the number of tracks on the cdrom`
| :sg:`get_numtracks() -> count`
Return the number of tracks on the cdrom in the drive. This will return
zero of the drive is empty or has no tracks.
.. ## CD.get_numtracks ##
.. method:: get_track_audio
| :sl:`true if the cdrom track has audio data`
| :sg:`get_track_audio(track) -> bool`
Determine if a track on a cdrom contains audio data. You can also call
``CD.num_tracks()`` and ``CD.get_all()`` to determine more information
about the cdrom.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_track_audio ##
.. method:: get_all
| :sl:`get all track information`
| :sg:`get_all() -> [(audio, start, end, length), ...]`
Return a list with information for every track on the cdrom. The
information consists of a tuple with four values. The audio value is True
if the track contains audio data. The start, end, and length values are
floating point numbers in seconds. Start and end represent absolute times
on the entire disc.
.. ## CD.get_all ##
.. method:: get_track_start
| :sl:`start time of a cdrom track`
| :sg:`get_track_start(track) -> seconds`
Return the absolute time in seconds where at start of the cdrom track.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_track_start ##
.. method:: get_track_length
| :sl:`length of a cdrom track`
| :sg:`get_track_length(track) -> seconds`
Return a floating point value in seconds of the length of the cdrom
track.
Note, track 0 is the first track on the ``CD``. Track numbers start at
zero.
.. ## CD.get_track_length ##
.. ## pygame.cdrom.CD ##
.. ## pygame.cdrom ##

View File

@@ -0,0 +1,283 @@
.. include:: common.txt
:mod:`pygame.Color`
===================
.. currentmodule:: pygame
.. class:: Color
| :sl:`pygame object for color representations`
| :sg:`Color(r, g, b) -> Color`
| :sg:`Color(r, g, b, a=255) -> Color`
| :sg:`Color(color_value) -> Color`
The ``Color`` class represents ``RGBA`` color values using a value range of
0 to 255 inclusive. It allows basic arithmetic operationsbinary
operations ``+``, ``-``, ``*``, ``//``, ``%``, and unary operation ``~``to
create new colors, supports conversions to other color spaces such as ``HSV``
or ``HSL`` and lets you adjust single color channels.
Alpha defaults to 255 (fully opaque) when not given.
The arithmetic operations and ``correct_gamma()`` method preserve subclasses.
For the binary operators, the class of the returned color is that of the
left hand color object of the operator.
Color objects support equality comparison with other color objects and 3 or
4 element tuples of integers. There was a bug in pygame 1.8.1
where the default alpha was 0, not 255 like previously.
Color objects export the C level array interface. The interface exports a
read-only one dimensional unsigned byte array of the same assigned length
as the color. The new buffer interface is also exported, with the same
characteristics as the array interface.
The floor division, ``//``, and modulus, ``%``, operators do not raise
an exception for division by zero. Instead, if a color, or alpha, channel
in the right hand color is 0, then the result is 0. For example: ::
# These expressions are True
Color(255, 255, 255, 255) // Color(0, 64, 64, 64) == Color(0, 3, 3, 3)
Color(255, 255, 255, 255) % Color(64, 64, 64, 0) == Color(63, 63, 63, 0)
Use ``int(color)`` to return the immutable integer value of the color,
usable as a ``dict`` key. This integer value differs from the mapped
pixel values of :meth:`pygame.Surface.get_at_mapped`,
:meth:`pygame.Surface.map_rgb` and :meth:`pygame.Surface.unmap_rgb`.
It can be passed as a ``color_value`` argument to :class:`Color`
(useful with sets).
See :doc:`color_list` for samples of the available named colors.
:param int r: red value in the range of 0 to 255 inclusive
:param int g: green value in the range of 0 to 255 inclusive
:param int b: blue value in the range of 0 to 255 inclusive
:param int a: (optional) alpha value in the range of 0 to 255 inclusive,
default is 255
:param color_value: color value (see note below for the supported formats)
.. note::
Supported ``color_value`` formats:
| - **Color object:** clones the given :class:`Color` object
| - **Color name: str:** name of the color to use, e.g. ``'red'``
(all the supported name strings can be found in the
:doc:`color_list`, with sample swatches)
| - **HTML color format str:** ``'#rrggbbaa'`` or ``'#rrggbb'``,
where rr, gg, bb, and aa are 2-digit hex numbers in the range
of 0 to 0xFF inclusive, the aa (alpha) value defaults to 0xFF
if not provided
| - **hex number str:** ``'0xrrggbbaa'`` or ``'0xrrggbb'``, where
rr, gg, bb, and aa are 2-digit hex numbers in the range of 0x00
to 0xFF inclusive, the aa (alpha) value defaults to 0xFF if not
provided
| - **int:** int value of the color to use, using hex numbers can
make this parameter more readable, e.g. ``0xrrggbbaa``, where rr,
gg, bb, and aa are 2-digit hex numbers in the range of 0x00 to
0xFF inclusive, note that the aa (alpha) value is not optional for
the int format and must be provided
| - **tuple/list of int color values:** ``(R, G, B, A)`` or
``(R, G, B)``, where R, G, B, and A are int values in the range of
0 to 255 inclusive, the A (alpha) value defaults to 255 if not
provided
:type color_value: Color or str or int or tuple(int, int, int, [int]) or
list(int, int, int, [int])
:returns: a newly created :class:`Color` object
:rtype: Color
.. versionchanged:: 2.0.0
Support for tuples, lists, and :class:`Color` objects when creating
:class:`Color` objects.
.. versionchanged:: 1.9.2 Color objects export the C level array interface.
.. versionchanged:: 1.9.0 Color objects support 4-element tuples of integers.
.. versionchanged:: 1.8.1 New implementation of the class.
.. attribute:: r
| :sl:`Gets or sets the red value of the Color.`
| :sg:`r -> int`
The red value of the Color.
.. ## Color.r ##
.. attribute:: g
| :sl:`Gets or sets the green value of the Color.`
| :sg:`g -> int`
The green value of the Color.
.. ## Color.g ##
.. attribute:: b
| :sl:`Gets or sets the blue value of the Color.`
| :sg:`b -> int`
The blue value of the Color.
.. ## Color.b ##
.. attribute:: a
| :sl:`Gets or sets the alpha value of the Color.`
| :sg:`a -> int`
The alpha value of the Color.
.. ## Color.a ##
.. attribute:: cmy
| :sl:`Gets or sets the CMY representation of the Color.`
| :sg:`cmy -> tuple`
The ``CMY`` representation of the Color. The ``CMY`` components are in
the ranges ``C`` = [0, 1], ``M`` = [0, 1], ``Y`` = [0, 1]. Note that this
will not return the absolutely exact ``CMY`` values for the set ``RGB``
values in all cases. Due to the ``RGB`` mapping from 0-255 and the
``CMY`` mapping from 0-1 rounding errors may cause the ``CMY`` values to
differ slightly from what you might expect.
.. ## Color.cmy ##
.. attribute:: hsva
| :sl:`Gets or sets the HSVA representation of the Color.`
| :sg:`hsva -> tuple`
The ``HSVA`` representation of the Color. The ``HSVA`` components are in
the ranges ``H`` = [0, 360], ``S`` = [0, 100], ``V`` = [0, 100], A = [0,
100]. Note that this will not return the absolutely exact ``HSV`` values
for the set ``RGB`` values in all cases. Due to the ``RGB`` mapping from
0-255 and the ``HSV`` mapping from 0-100 and 0-360 rounding errors may
cause the ``HSV`` values to differ slightly from what you might expect.
.. ## Color.hsva ##
.. attribute:: hsla
| :sl:`Gets or sets the HSLA representation of the Color.`
| :sg:`hsla -> tuple`
The ``HSLA`` representation of the Color. The ``HSLA`` components are in
the ranges ``H`` = [0, 360], ``S`` = [0, 100], ``L`` = [0, 100], A = [0,
100]. Note that this will not return the absolutely exact ``HSL`` values
for the set ``RGB`` values in all cases. Due to the ``RGB`` mapping from
0-255 and the ``HSL`` mapping from 0-100 and 0-360 rounding errors may
cause the ``HSL`` values to differ slightly from what you might expect.
.. ## Color.hsla ##
.. attribute:: i1i2i3
| :sl:`Gets or sets the I1I2I3 representation of the Color.`
| :sg:`i1i2i3 -> tuple`
The ``I1I2I3`` representation of the Color. The ``I1I2I3`` components are
in the ranges ``I1`` = [0, 1], ``I2`` = [-0.5, 0.5], ``I3`` = [-0.5,
0.5]. Note that this will not return the absolutely exact ``I1I2I3``
values for the set ``RGB`` values in all cases. Due to the ``RGB``
mapping from 0-255 and the ``I1I2I3`` mapping from 0-1 rounding errors
may cause the ``I1I2I3`` values to differ slightly from what you might
expect.
.. ## Color.i1i2i3 ##
.. method:: normalize
| :sl:`Returns the normalized RGBA values of the Color.`
| :sg:`normalize() -> tuple`
Returns the normalized ``RGBA`` values of the Color as floating point
values.
.. ## Color.normalize ##
.. method:: correct_gamma
| :sl:`Applies a certain gamma value to the Color.`
| :sg:`correct_gamma (gamma) -> Color`
Applies a certain gamma value to the Color and returns a new Color with
the adjusted ``RGBA`` values.
.. ## Color.correct_gamma ##
.. method:: set_length
| :sl:`Set the number of elements in the Color to 1,2,3, or 4.`
| :sg:`set_length(len) -> None`
DEPRECATED: You may unpack the values you need like so,
``r, g, b, _ = pygame.Color(100, 100, 100)``
If you only want r, g and b
Or
``r, g, *_ = pygame.Color(100, 100, 100)``
if you only want r and g
The default Color length is 4. Colors can have lengths 1,2,3 or 4. This
is useful if you want to unpack to r,g,b and not r,g,b,a. If you want to
get the length of a Color do ``len(acolor)``.
.. deprecated:: 2.1.3
.. versionadded:: 1.9.0
.. ## Color.set_length ##
.. method:: grayscale
| :sl:`returns the grayscale of a Color`
| :sg:`grayscale() -> Color`
Returns a Color which represents the grayscaled version of self using the luminosity formula which weights red, green and blue according to their wavelengths..
.. ## Color.grayscale ##
.. method:: lerp
| :sl:`returns a linear interpolation to the given Color.`
| :sg:`lerp(Color, float) -> Color`
Returns a Color which is a linear interpolation between self and the
given Color in RGBA space. The second parameter determines how far
between self and other the result is going to be.
It must be a value between 0 and 1 where 0 means self and 1 means
other will be returned.
.. versionadded:: 2.0.1
.. ## Color.lerp ##
.. method:: premul_alpha
| :sl:`returns a Color where the r,g,b components have been multiplied by the alpha.`
| :sg:`premul_alpha() -> Color`
Returns a new Color where each of the red, green and blue colour
channels have been multiplied by the alpha channel of the original
color. The alpha channel remains unchanged.
This is useful when working with the ``BLEND_PREMULTIPLIED`` blending mode
flag for :meth:`pygame.Surface.blit()`, which assumes that all surfaces using
it are using pre-multiplied alpha colors.
.. versionadded:: 2.0.0
.. ## Color.premul_alpha ##
.. method:: update
| :sl:`Sets the elements of the color`
| :sg:`update(r, g, b) -> None`
| :sg:`update(r, g, b, a=255) -> None`
| :sg:`update(color_value) -> None`
Sets the elements of the color. See parameters for :meth:`pygame.Color` for the
parameters of this function. If the alpha value was not set it will not change.
.. versionadded:: 2.0.1
.. ## Color.update ##
.. ## pygame.Color ##

View File

@@ -0,0 +1,251 @@
.. include:: common.txt
:mod:`pygame.cursors`
=====================
.. module:: pygame.cursors
:synopsis: pygame module for cursor resources
| :sl:`pygame module for cursor resources`
Pygame offers control over the system hardware cursor. Pygame supports
black and white cursors (bitmap cursors), as well as system variant cursors and color cursors.
You control the cursor with functions inside :mod:`pygame.mouse`.
This cursors module contains functions for loading and decoding various
cursor formats. These allow you to easily store your cursors in external files
or directly as encoded python strings.
The module includes several standard cursors. The :func:`pygame.mouse.set_cursor()`
function takes several arguments. All those arguments have been stored in a
single tuple you can call like this:
::
>>> pygame.mouse.set_cursor(*pygame.cursors.arrow)
The following variables can be passed to ``pygame.mouse.set_cursor`` function:
* ``pygame.cursors.arrow``
* ``pygame.cursors.diamond``
* ``pygame.cursors.broken_x``
* ``pygame.cursors.tri_left``
* ``pygame.cursors.tri_right``
This module also contains a few cursors as formatted strings. You'll need to
pass these to ``pygame.cursors.compile()`` function before you can use them.
The example call would look like this:
::
>>> cursor = pygame.cursors.compile(pygame.cursors.textmarker_strings)
>>> pygame.mouse.set_cursor((8, 16), (0, 0), *cursor)
The following strings can be converted into cursor bitmaps with
``pygame.cursors.compile()`` :
* ``pygame.cursors.thickarrow_strings``
* ``pygame.cursors.sizer_x_strings``
* ``pygame.cursors.sizer_y_strings``
* ``pygame.cursors.sizer_xy_strings``
* ``pygame.cursor.textmarker_strings``
.. function:: compile
| :sl:`create binary cursor data from simple strings`
| :sg:`compile(strings, black='X', white='.', xor='o') -> data, mask`
A sequence of strings can be used to create binary cursor data for the
system cursor. This returns the binary data in the form of two tuples.
Those can be passed as the third and fourth arguments respectively of the
:func:`pygame.mouse.set_cursor()` function.
If you are creating your own cursor strings, you can use any value represent
the black and white pixels. Some system allow you to set a special toggle
color for the system color, this is also called the xor color. If the system
does not support xor cursors, that color will simply be black.
The height must be divisible by 8. The width of the strings must all be equal
and be divisible by 8. If these two conditions are not met, ``ValueError`` is
raised.
An example set of cursor strings looks like this
::
thickarrow_strings = ( #sized 24x24
"XX ",
"XXX ",
"XXXX ",
"XX.XX ",
"XX..XX ",
"XX...XX ",
"XX....XX ",
"XX.....XX ",
"XX......XX ",
"XX.......XX ",
"XX........XX ",
"XX........XXX ",
"XX......XXXXX ",
"XX.XXX..XX ",
"XXXX XX..XX ",
"XX XX..XX ",
" XX..XX ",
" XX..XX ",
" XX..XX ",
" XXXX ",
" XX ",
" ",
" ",
" ")
.. ## pygame.cursors.compile ##
.. function:: load_xbm
| :sl:`load cursor data from an XBM file`
| :sg:`load_xbm(cursorfile) -> cursor_args`
| :sg:`load_xbm(cursorfile, maskfile) -> cursor_args`
This loads cursors for a simple subset of ``XBM`` files. ``XBM`` files are
traditionally used to store cursors on UNIX systems, they are an ASCII
format used to represent simple images.
Sometimes the black and white color values will be split into two separate
``XBM`` files. You can pass a second maskfile argument to load the two
images into a single cursor.
The cursorfile and maskfile arguments can either be filenames or file-like
object with the readlines method.
The return value cursor_args can be passed directly to the
``pygame.mouse.set_cursor()`` function.
.. ## pygame.cursors.load_xbm ##
.. class:: Cursor
| :sl:`pygame object representing a cursor`
| :sg:`Cursor(size, hotspot, xormasks, andmasks) -> Cursor`
| :sg:`Cursor(hotspot, surface) -> Cursor`
| :sg:`Cursor(constant) -> Cursor`
| :sg:`Cursor(Cursor) -> Cursor`
| :sg:`Cursor() -> Cursor`
In pygame 2, there are 3 types of cursors you can create to give your
game that little bit of extra polish. There's **bitmap** type cursors,
which existed in pygame 1.x, and are compiled from a string or load from an xbm file.
Then there are **system** type cursors, where you choose a preset that will
convey the same meaning but look native across different operating systems.
Finally you can create a **color** cursor, which displays a pygame surface as the cursor.
**Creating a system cursor**
Choose a constant from this list, pass it into ``pygame.cursors.Cursor(constant)``,
and you're good to go. Be advised that not all systems support every system
cursor, and you may get a substitution instead. For example, on MacOS,
WAIT/WAITARROW should show up as an arrow, and SIZENWSE/SIZENESW/SIZEALL
should show up as a closed hand. And on Wayland, every SIZE cursor should
show up as a hand.
::
Pygame Cursor Constant Description
--------------------------------------------
pygame.SYSTEM_CURSOR_ARROW arrow
pygame.SYSTEM_CURSOR_IBEAM i-beam
pygame.SYSTEM_CURSOR_WAIT wait
pygame.SYSTEM_CURSOR_CROSSHAIR crosshair
pygame.SYSTEM_CURSOR_WAITARROW small wait cursor
(or wait if not available)
pygame.SYSTEM_CURSOR_SIZENWSE double arrow pointing
northwest and southeast
pygame.SYSTEM_CURSOR_SIZENESW double arrow pointing
northeast and southwest
pygame.SYSTEM_CURSOR_SIZEWE double arrow pointing
west and east
pygame.SYSTEM_CURSOR_SIZENS double arrow pointing
north and south
pygame.SYSTEM_CURSOR_SIZEALL four pointed arrow pointing
north, south, east, and west
pygame.SYSTEM_CURSOR_NO slashed circle or crossbones
pygame.SYSTEM_CURSOR_HAND hand
**Creating a cursor without passing arguments**
In addition to the cursor constants available and described above,
you can also call ``pygame.cursors.Cursor()``, and your cursor is ready (doing that is the same as
calling ``pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_ARROW)``.
Doing one of those calls actually creates a system cursor using the default native image.
**Creating a color cursor**
To create a color cursor, create a ``Cursor`` from a ``hotspot`` and a ``surface``.
``hotspot`` is an (x,y) coordinate that determines where in the cursor the exact point is.
The hotspot position must be within the bounds of the ``surface``.
**Creating a bitmap cursor**
When the mouse cursor is visible, it will be displayed as a black and white
bitmap using the given bitmask arrays. The ``size`` is a sequence containing
the cursor width and height. ``hotspot`` is a sequence containing the cursor
hotspot position.
A cursor has a width and height, but a mouse position is represented by a
set of point coordinates. So the value passed into the cursor ``hotspot``
variable helps pygame to actually determine at what exact point the cursor
is at.
``xormasks`` is a sequence of bytes containing the cursor xor data masks.
Lastly ``andmasks``, a sequence of bytes containing the cursor bitmask data.
To create these variables, we can make use of the
:func:`pygame.cursors.compile()` function.
Width and height must be a multiple of 8, and the mask arrays must be the
correct size for the given width and height. Otherwise an exception is raised.
.. method:: copy
| :sl:`copy the current cursor`
| :sg:`copy() -> Cursor`
Returns a new Cursor object with the same data and hotspot as the original.
.. ## pygame.cursors.Cursor.copy ##
.. attribute:: type
| :sl:`Gets the cursor type`
| :sg:`type -> string`
The type will be ``"system"``, ``"bitmap"``, or ``"color"``.
.. ## pygame.cursors.Cursor.type ##
.. attribute:: data
| :sl:`Gets the cursor data`
| :sg:`data -> tuple`
Returns the data that was used to create this cursor object, wrapped up in a tuple.
.. ## pygame.cursors.Cursor.data ##
.. versionadded:: 2.0.1
.. ## pygame.cursors.Cursor ##
.. ## pygame.cursors ##
Example code for creating and settings cursors. (Click the mouse to switch cursor)
.. literalinclude:: code_examples/cursors_module_example.py

View File

@@ -0,0 +1,737 @@
.. include:: common.txt
:mod:`pygame.display`
=====================
.. module:: pygame.display
:synopsis: pygame module to control the display window and screen
| :sl:`pygame module to control the display window and screen`
This module offers control over the pygame display. Pygame has a single display
Surface that is either contained in a window or runs full screen. Once you
create the display you treat it as a regular Surface. Changes are not
immediately visible onscreen; you must choose one of the two flipping functions
to update the actual display.
The origin of the display, where x = 0 and y = 0, is the top left of the
screen. Both axes increase positively towards the bottom right of the screen.
The pygame display can actually be initialized in one of several modes. By
default, the display is a basic software driven framebuffer. You can request
special modules like automatic scaling or OpenGL support. These are
controlled by flags passed to ``pygame.display.set_mode()``.
Pygame can only have a single display active at any time. Creating a new one
with ``pygame.display.set_mode()`` will close the previous display. To detect
the number and size of attached screens, you can use
``pygame.display.get_desktop_sizes`` and then select appropriate window size
and display index to pass to ``pygame.display.set_mode()``.
For backward compatibility ``pygame.display`` allows precise control over
the pixel format or display resolutions. This used to be necessary with old
graphics cards and CRT screens, but is usually not needed any more. Use the
functions ``pygame.display.mode_ok()``, ``pygame.display.list_modes()``, and
``pygame.display.Info()`` to query detailed information about the display.
Once the display Surface is created, the functions from this module affect the
single existing display. The Surface becomes invalid if the module is
uninitialized. If a new display mode is set, the existing Surface will
automatically switch to operate on the new display.
When the display mode is set, several events are placed on the pygame event
queue. ``pygame.QUIT`` is sent when the user has requested the program to
shut down. The window will receive ``pygame.ACTIVEEVENT`` events as the display
gains and loses input focus. If the display is set with the
``pygame.RESIZABLE`` flag, ``pygame.VIDEORESIZE`` events will be sent when the
user adjusts the window dimensions. Hardware displays that draw direct to the
screen will get ``pygame.VIDEOEXPOSE`` events when portions of the window must
be redrawn.
A new windowevent API was introduced in pygame 2.0.1. Check event module docs
for more information on that
Some display environments have an option for automatically stretching all
windows. When this option is enabled, this automatic stretching distorts the
appearance of the pygame window. In the pygame examples directory, there is
example code (prevent_display_stretching.py) which shows how to disable this
automatic stretching of the pygame display on Microsoft Windows (Vista or newer
required).
.. function:: init
| :sl:`Initialize the display module`
| :sg:`init() -> None`
Initializes the pygame display module. The display module cannot do anything
until it is initialized. This is usually handled for you automatically when
you call the higher level ``pygame.init()``.
Pygame will select from one of several internal display backends when it is
initialized. The display mode will be chosen depending on the platform and
permissions of current user. Before the display module is initialized the
environment variable ``SDL_VIDEODRIVER`` can be set to control which backend
is used. The systems with multiple choices are listed here.
::
Windows : windib, directx
Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib
On some platforms it is possible to embed the pygame display into an already
existing window. To do this, the environment variable ``SDL_WINDOWID`` must
be set to a string containing the window id or handle. The environment
variable is checked when the pygame display is initialized. Be aware that
there can be many strange side effects when running in an embedded display.
It is harmless to call this more than once, repeated calls have no effect.
.. ## pygame.display.init ##
.. function:: quit
| :sl:`Uninitialize the display module`
| :sg:`quit() -> None`
This will shut down the entire display module. This means any active
displays will be closed. This will also be handled automatically when the
program exits.
It is harmless to call this more than once, repeated calls have no effect.
.. ## pygame.display.quit ##
.. function:: get_init
| :sl:`Returns True if the display module has been initialized`
| :sg:`get_init() -> bool`
Returns True if the :mod:`pygame.display` module is currently initialized.
.. ## pygame.display.get_init ##
.. function:: set_mode
| :sl:`Initialize a window or screen for display`
| :sg:`set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface`
This function will create a display Surface. The arguments passed in are
requests for a display type. The actual created display will be the best
possible match supported by the system.
Note that calling this function implicitly initializes ``pygame.display``, if
it was not initialized before.
The size argument is a pair of numbers representing the width and
height. The flags argument is a collection of additional options. The depth
argument represents the number of bits to use for color.
The Surface that gets returned can be drawn to like a regular Surface but
changes will eventually be seen on the monitor.
If no size is passed or is set to ``(0, 0)`` and pygame uses ``SDL``
version 1.2.10 or above, the created Surface will have the same size as the
current screen resolution. If only the width or height are set to ``0``, the
Surface will have the same width or height as the screen resolution. Using a
``SDL`` version prior to 1.2.10 will raise an exception.
It is usually best to not pass the depth argument. It will default to the
best and fastest color depth for the system. If your game requires a
specific color format you can control the depth with this argument. Pygame
will emulate an unavailable color depth which can be slow.
When requesting fullscreen display modes, sometimes an exact match for the
requested size cannot be made. In these situations pygame will select
the closest compatible match. The returned surface will still always match
the requested size.
On high resolution displays(4k, 1080p) and tiny graphics games (640x480)
show up very small so that they are unplayable. SCALED scales up the window
for you. The game thinks it's a 640x480 window, but really it can be bigger.
Mouse events are scaled for you, so your game doesn't need to do it. Note
that SCALED is considered an experimental API and may change in future
releases.
The flags argument controls which type of display you want. There are
several to choose from, and you can even combine multiple types using the
bitwise or operator, (the pipe "|" character). Here are the display
flags you will want to choose from:
::
pygame.FULLSCREEN create a fullscreen display
pygame.DOUBLEBUF only applicable with OPENGL
pygame.HWSURFACE (obsolete in pygame 2) hardware accelerated, only in FULLSCREEN
pygame.OPENGL create an OpenGL-renderable display
pygame.RESIZABLE display window should be sizeable
pygame.NOFRAME display window will have no border or controls
pygame.SCALED resolution depends on desktop size and scale graphics
pygame.SHOWN window is opened in visible mode (default)
pygame.HIDDEN window is opened in hidden mode
.. versionadded:: 2.0.0 ``SCALED``, ``SHOWN`` and ``HIDDEN``
By setting the ``vsync`` parameter to ``1``, it is possible to get a display
with vertical sync, but you are not guaranteed to get one. The request only
works at all for calls to ``set_mode()`` with the ``pygame.OPENGL`` or
``pygame.SCALED`` flags set, and is still not guaranteed even with one of
those set. What you get depends on the hardware and driver configuration
of the system pygame is running on. Here is an example usage of a call
to ``set_mode()`` that may give you a display with vsync:
::
flags = pygame.OPENGL | pygame.FULLSCREEN
window_surface = pygame.display.set_mode((1920, 1080), flags, vsync=1)
Vsync behaviour is considered experimental, and may change in future releases.
.. versionadded:: 2.0.0 ``vsync``
Basic example:
::
# Open a window on the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width, screen_height])
The display index ``0`` means the default display is used. If no display
index argument is provided, the default display can be overridden with an
environment variable.
.. versionchanged:: 1.9.5 ``display`` argument added
.. versionchanged:: 2.1.3
pygame now ensures that subsequent calls to this function clears the
window to black. On older versions, this was an implementation detail
on the major platforms this function was tested with.
.. ## pygame.display.set_mode ##
.. function:: get_surface
| :sl:`Get a reference to the currently set display surface`
| :sg:`get_surface() -> Surface`
Return a reference to the currently set display Surface. If no display mode
has been set this will return None.
.. ## pygame.display.get_surface ##
.. function:: flip
| :sl:`Update the full display Surface to the screen`
| :sg:`flip() -> None`
This will update the contents of the entire display. If your display mode is
using the flags ``pygame.HWSURFACE`` and ``pygame.DOUBLEBUF`` on pygame 1,
this will wait for a vertical retrace and swap the surfaces.
When using an ``pygame.OPENGL`` display mode this will perform a gl buffer
swap.
.. ## pygame.display.flip ##
.. function:: update
| :sl:`Update portions of the screen for software displays`
| :sg:`update(rectangle=None) -> None`
| :sg:`update(rectangle_list) -> None`
This function is like an optimized version of ``pygame.display.flip()`` for
software displays. It allows only a portion of the screen to be updated,
instead of the entire area. If no argument is passed it updates the entire
Surface area like ``pygame.display.flip()``.
Note that calling ``display.update(None)`` means no part of the window is
updated. Whereas ``display.update()`` means the whole window is updated.
You can pass the function a single rectangle, or a sequence of rectangles.
It is more efficient to pass many rectangles at once than to call update
multiple times with single or a partial list of rectangles. If passing a
sequence of rectangles it is safe to include None values in the list, which
will be skipped.
This call cannot be used on ``pygame.OPENGL`` displays and will generate an
exception.
.. ## pygame.display.update ##
.. function:: get_driver
| :sl:`Get the name of the pygame display backend`
| :sg:`get_driver() -> name`
Pygame chooses one of many available display backends when it is
initialized. This returns the internal name used for the display backend.
This can be used to provide limited information about what display
capabilities might be accelerated. See the ``SDL_VIDEODRIVER`` flags in
``pygame.display.set_mode()`` to see some of the common options.
.. ## pygame.display.get_driver ##
.. function:: Info
| :sl:`Create a video display information object`
| :sg:`Info() -> VideoInfo`
Creates a simple object containing several attributes to describe the
current graphics environment. If this is called before
``pygame.display.set_mode()`` some platforms can provide information about
the default display mode. This can also be called after setting the display
mode to verify specific display options were satisfied. The VidInfo object
has several attributes:
::
hw: 1 if the display is hardware accelerated
wm: 1 if windowed display modes can be used
video_mem: The megabytes of video memory on the display. This is 0 if
unknown
bitsize: Number of bits used to store each pixel
bytesize: Number of bytes used to store each pixel
masks: Four values used to pack RGBA values into pixels
shifts: Four values used to pack RGBA values into pixels
losses: Four values used to pack RGBA values into pixels
blit_hw: 1 if hardware Surface blitting is accelerated
blit_hw_CC: 1 if hardware Surface colorkey blitting is accelerated
blit_hw_A: 1 if hardware Surface pixel alpha blitting is accelerated
blit_sw: 1 if software Surface blitting is accelerated
blit_sw_CC: 1 if software Surface colorkey blitting is accelerated
blit_sw_A: 1 if software Surface pixel alpha blitting is accelerated
current_h, current_w: Height and width of the current video mode, or
of the desktop mode if called before the display.set_mode
is called. (current_h, current_w are available since
SDL 1.2.10, and pygame 1.8.0). They are -1 on error, or if
an old SDL is being used.
.. ## pygame.display.Info ##
.. function:: get_wm_info
| :sl:`Get information about the current windowing system`
| :sg:`get_wm_info() -> dict`
Creates a dictionary filled with string keys. The strings and values are
arbitrarily created by the system. Some systems may have no information and
an empty dictionary will be returned. Most platforms will return a "window"
key with the value set to the system id for the current display.
.. versionadded:: 1.7.1
.. ## pygame.display.get_wm_info ##
.. function:: get_desktop_sizes
| :sl:`Get sizes of active desktops`
| :sg:`get_desktop_sizes() -> list`
This function returns the sizes of the currently configured
virtual desktops as a list of (x, y) tuples of integers.
The length of the list is not the same as the number of attached monitors,
as a desktop can be mirrored across multiple monitors. The desktop sizes
do not indicate the maximum monitor resolutions supported by the hardware,
but the desktop size configured in the operating system.
In order to fit windows into the desktop as it is currently configured, and
to respect the resolution configured by the operating system in fullscreen
mode, this function *should* be used to replace many use cases of
``pygame.display.list_modes()`` whenever applicable.
.. versionadded:: 2.0.0
.. function:: list_modes
| :sl:`Get list of available fullscreen modes`
| :sg:`list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list`
This function returns a list of possible sizes for a specified color
depth. The return value will be an empty list if no display modes are
available with the given arguments. A return value of ``-1`` means that
any requested size should work (this is likely the case for windowed
modes). Mode sizes are sorted from biggest to smallest.
If depth is ``0``, the current/best color depth for the display is used.
The flags defaults to ``pygame.FULLSCREEN``, but you may need to add
additional flags for specific fullscreen modes.
The display index ``0`` means the default display is used.
Since pygame 2.0, ``pygame.display.get_desktop_sizes()`` has taken over
some use cases from ``pygame.display.list_modes()``:
To find a suitable size for non-fullscreen windows, it is preferable to
use ``pygame.display.get_desktop_sizes()`` to get the size of the *current*
desktop, and to then choose a smaller window size. This way, the window is
guaranteed to fit, even when the monitor is configured to a lower resolution
than the maximum supported by the hardware.
To avoid changing the physical monitor resolution, it is also preferable to
use ``pygame.display.get_desktop_sizes()`` to determine the fullscreen
resolution. Developers are strongly advised to default to the current
physical monitor resolution unless the user explicitly requests a different
one (e.g. in an options menu or configuration file).
.. versionchanged:: 1.9.5 ``display`` argument added
.. ## pygame.display.list_modes ##
.. function:: mode_ok
| :sl:`Pick the best color depth for a display mode`
| :sg:`mode_ok(size, flags=0, depth=0, display=0) -> depth`
This function uses the same arguments as ``pygame.display.set_mode()``. It
is used to determine if a requested display mode is available. It will
return ``0`` if the display mode cannot be set. Otherwise it will return a
pixel depth that best matches the display asked for.
Usually the depth argument is not passed, but some platforms can support
multiple display depths. If passed it will hint to which depth is a better
match.
The function will return ``0`` if the passed display flags cannot be set.
The display index ``0`` means the default display is used.
.. versionchanged:: 1.9.5 ``display`` argument added
.. ## pygame.display.mode_ok ##
.. function:: gl_get_attribute
| :sl:`Get the value for an OpenGL flag for the current display`
| :sg:`gl_get_attribute(flag) -> value`
After calling ``pygame.display.set_mode()`` with the ``pygame.OPENGL`` flag,
it is a good idea to check the value of any requested OpenGL attributes. See
``pygame.display.gl_set_attribute()`` for a list of valid flags.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## pygame.display.gl_get_attribute ##
.. function:: gl_set_attribute
| :sl:`Request an OpenGL display attribute for the display mode`
| :sg:`gl_set_attribute(flag, value) -> None`
When calling ``pygame.display.set_mode()`` with the ``pygame.OPENGL`` flag,
Pygame automatically handles setting the OpenGL attributes like color and
double-buffering. OpenGL offers several other attributes you may want control
over. Pass one of these attributes as the flag, and its appropriate value.
This must be called before ``pygame.display.set_mode()``.
Many settings are the requested minimum. Creating a window with an OpenGL context
will fail if OpenGL cannot provide the requested attribute, but it may for example
give you a stencil buffer even if you request none, or it may give you a larger
one than requested.
The ``OPENGL`` flags are:
::
GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE,
GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE,
GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO
:const:`GL_MULTISAMPLEBUFFERS`
Whether to enable multisampling anti-aliasing.
Defaults to 0 (disabled).
Set ``GL_MULTISAMPLESAMPLES`` to a value
above 0 to control the amount of anti-aliasing.
A typical value is 2 or 3.
:const:`GL_STENCIL_SIZE`
Minimum bit size of the stencil buffer. Defaults to 0.
:const:`GL_DEPTH_SIZE`
Minimum bit size of the depth buffer. Defaults to 16.
:const:`GL_STEREO`
1 enables stereo 3D. Defaults to 0.
:const:`GL_BUFFER_SIZE`
Minimum bit size of the frame buffer. Defaults to 0.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. versionadded:: 2.0.0 Additional attributes:
::
GL_ACCELERATED_VISUAL,
GL_CONTEXT_MAJOR_VERSION, GL_CONTEXT_MINOR_VERSION,
GL_CONTEXT_FLAGS, GL_CONTEXT_PROFILE_MASK,
GL_SHARE_WITH_CURRENT_CONTEXT,
GL_CONTEXT_RELEASE_BEHAVIOR,
GL_FRAMEBUFFER_SRGB_CAPABLE
:const:`GL_CONTEXT_PROFILE_MASK`
Sets the OpenGL profile to one of these values:
::
GL_CONTEXT_PROFILE_CORE disable deprecated features
GL_CONTEXT_PROFILE_COMPATIBILITY allow deprecated features
GL_CONTEXT_PROFILE_ES allow only the ES feature
subset of OpenGL
:const:`GL_ACCELERATED_VISUAL`
Set to 1 to require hardware acceleration, or 0 to force software render.
By default, both are allowed.
.. ## pygame.display.gl_set_attribute ##
.. function:: get_active
| :sl:`Returns True when the display is active on the screen`
| :sg:`get_active() -> bool`
Returns True when the display Surface is considered actively
renderable on the screen and may be visible to the user. This is
the default state immediately after ``pygame.display.set_mode()``.
This method may return True even if the application is fully hidden
behind another application window.
This will return False if the display Surface has been iconified or
minimized (either via ``pygame.display.iconify()`` or via an OS
specific method such as the minimize-icon available on most
desktops).
The method can also return False for other reasons without the
application being explicitly iconified or minimized by the user. A
notable example being if the user has multiple virtual desktops and
the display Surface is not on the active virtual desktop.
.. note:: This function returning True is unrelated to whether the
application has input focus. Please see
``pygame.key.get_focused()`` and ``pygame.mouse.get_focused()``
for APIs related to input focus.
.. ## pygame.display.get_active ##
.. function:: iconify
| :sl:`Iconify the display surface`
| :sg:`iconify() -> bool`
Request the window for the display surface be iconified or hidden. Not all
systems and displays support an iconified display. The function will return
True if successful.
When the display is iconified ``pygame.display.get_active()`` will return
``False``. The event queue should receive an ``ACTIVEEVENT`` event when the
window has been iconified. Additionally, the event queue also receives a
``WINDOWEVENT_MINIMIZED`` event when the window has been iconified on pygame 2.
.. ## pygame.display.iconify ##
.. function:: toggle_fullscreen
| :sl:`Switch between fullscreen and windowed displays`
| :sg:`toggle_fullscreen() -> int`
Switches the display window between windowed and fullscreen modes.
Display driver support is not great when using pygame 1, but with
pygame 2 it is the most reliable method to switch to and from fullscreen.
Supported display drivers in pygame 1:
* x11 (Linux/Unix)
* wayland (Linux/Unix)
Supported display drivers in pygame 2:
* windows (Windows)
* x11 (Linux/Unix)
* wayland (Linux/Unix)
* cocoa (OSX/Mac)
.. Note:: :func:`toggle_fullscreen` doesn't work on Windows
unless the window size is in :func:`pygame.display.list_modes()` or
the window is created with the flag ``pygame.SCALED``.
See `issue #2380 <https://github.com/pygame/pygame/issues/2380>`_.
.. ## pygame.display.toggle_fullscreen ##
.. function:: set_gamma
| :sl:`Change the hardware gamma ramps`
| :sg:`set_gamma(red, green=None, blue=None) -> bool`
DEPRECATED: This functionality will go away in SDL3.
Set the red, green, and blue gamma values on the display hardware. If the
green and blue arguments are not passed, they will both be the same as red.
Not all systems and hardware support gamma ramps, if the function succeeds
it will return ``True``.
A gamma value of ``1.0`` creates a linear color table. Lower values will
darken the display and higher values will brighten.
.. deprecated:: 2.2.0
.. ## pygame.display.set_gamma ##
.. function:: set_gamma_ramp
| :sl:`Change the hardware gamma ramps with a custom lookup`
| :sg:`set_gamma_ramp(red, green, blue) -> bool`
DEPRECATED: This functionality will go away in SDL3.
Set the red, green, and blue gamma ramps with an explicit lookup table. Each
argument should be sequence of 256 integers. The integers should range
between ``0`` and ``0xffff``. Not all systems and hardware support gamma
ramps, if the function succeeds it will return ``True``.
.. deprecated:: 2.2.0
.. ## pygame.display.set_gamma_ramp ##
.. function:: set_icon
| :sl:`Change the system image for the display window`
| :sg:`set_icon(Surface) -> None`
Sets the runtime icon the system will use to represent the display window.
All windows default to a simple pygame logo for the window icon.
Note that calling this function implicitly initializes ``pygame.display``, if
it was not initialized before.
You can pass any surface, but most systems want a smaller image around
32x32. The image can have colorkey transparency which will be passed to the
system.
Some systems do not allow the window icon to change after it has been shown.
This function can be called before ``pygame.display.set_mode()`` to create
the icon before the display mode is set.
.. ## pygame.display.set_icon ##
.. function:: set_caption
| :sl:`Set the current window caption`
| :sg:`set_caption(title, icontitle=None) -> None`
If the display has a window title, this function will change the name on the
window. In pygame 1.x, some systems supported an alternate shorter title to
be used for minimized displays, but in pygame 2 ``icontitle`` does nothing.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## pygame.display.set_caption ##
.. function:: get_caption
| :sl:`Get the current window caption`
| :sg:`get_caption() -> (title, icontitle)`
Returns the title and icontitle for the display window. In pygame 2.x
these will always be the same value.
.. ## pygame.display.get_caption ##
.. function:: set_palette
| :sl:`Set the display color palette for indexed displays`
| :sg:`set_palette(palette=None) -> None`
This will change the video display color palette for 8-bit displays. This
does not change the palette for the actual display Surface, only the palette
that is used to display the Surface. If no palette argument is passed, the
system default palette will be restored. The palette is a sequence of
``RGB`` triplets.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## pygame.display.set_palette ##
.. function:: get_num_displays
| :sl:`Return the number of displays`
| :sg:`get_num_displays() -> int`
Returns the number of available displays. This is always 1 if
:func:`pygame.get_sdl_version()` returns a major version number below 2.
.. versionadded:: 1.9.5
.. ## pygame.display.get_num_displays ##
.. function:: get_window_size
| :sl:`Return the size of the window or screen`
| :sg:`get_window_size() -> tuple`
Returns the size of the window initialized with :func:`pygame.display.set_mode()`.
This may differ from the size of the display surface if ``SCALED`` is used.
.. versionadded:: 2.0.0
.. ## pygame.display.get_window_size ##
.. function:: get_allow_screensaver
| :sl:`Return whether the screensaver is allowed to run.`
| :sg:`get_allow_screensaver() -> bool`
Return whether screensaver is allowed to run whilst the app is running.
Default is ``False``.
By default pygame does not allow the screensaver during game play.
.. note:: Some platforms do not have a screensaver or support
disabling the screensaver. Please see
:func:`pygame.display.set_allow_screensaver()` for
caveats with screensaver support.
.. versionadded:: 2.0.0
.. ## pygame.display.get_allow_screensaver ##
.. function:: set_allow_screensaver
| :sl:`Set whether the screensaver may run`
| :sg:`set_allow_screensaver(bool) -> None`
Change whether screensavers should be allowed whilst the app is running.
The default value of the argument to the function is True.
By default pygame does not allow the screensaver during game play.
If the screensaver has been disallowed due to this function, it will automatically
be allowed to run when :func:`pygame.quit()` is called.
It is possible to influence the default value via the environment variable
``SDL_HINT_VIDEO_ALLOW_SCREENSAVER``, which can be set to either ``0`` (disable)
or ``1`` (enable).
.. note:: Disabling screensaver is subject to platform support.
When platform support is absent, this function will
silently appear to work even though the screensaver state
is unchanged. The lack of feedback is due to SDL not
providing any supported method for determining whether
it supports changing the screensaver state.
``SDL_HINT_VIDEO_ALLOW_SCREENSAVER`` is available in SDL 2.0.2 or later.
SDL1.2 does not implement this.
.. versionadded:: 2.0.0
.. ## pygame.display.set_allow_screensaver ##
.. ## pygame.display ##

View File

@@ -0,0 +1,557 @@
.. include:: common.txt
:mod:`pygame.draw`
==================
.. module:: pygame.draw
:synopsis: pygame module for drawing shapes
| :sl:`pygame module for drawing shapes`
Draw several simple shapes to a surface. These functions will work for
rendering to any format of surface.
Most of the functions take a width argument to represent the size of stroke
(thickness) around the edge of the shape. If a width of 0 is passed the shape
will be filled (solid).
All the drawing functions respect the clip area for the surface and will be
constrained to that area. The functions return a rectangle representing the
bounding area of changed pixels. This bounding rectangle is the 'minimum'
bounding box that encloses the affected area.
All the drawing functions accept a color argument that can be one of the
following formats:
- a :mod:`pygame.Color` object
- an ``(RGB)`` triplet (tuple/list)
- an ``(RGBA)`` quadruplet (tuple/list)
- an integer value that has been mapped to the surface's pixel format
(see :func:`pygame.Surface.map_rgb` and :func:`pygame.Surface.unmap_rgb`)
A color's alpha value will be written directly into the surface (if the
surface contains pixel alphas), but the draw function will not draw
transparently.
These functions temporarily lock the surface they are operating on. Many
sequential drawing calls can be sped up by locking and unlocking the surface
object around the draw calls (see :func:`pygame.Surface.lock` and
:func:`pygame.Surface.unlock`).
.. note ::
See the :mod:`pygame.gfxdraw` module for alternative draw methods.
.. function:: rect
| :sl:`draw a rectangle`
| :sg:`rect(surface, color, rect) -> Rect`
| :sg:`rect(surface, color, rect, width=0, border_radius=0, border_top_left_radius=-1, border_top_right_radius=-1, border_bottom_left_radius=-1, border_bottom_right_radius=-1) -> Rect`
Draws a rectangle on the given surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param Rect rect: rectangle to draw, position and dimensions
:param int width: (optional) used for line thickness or to indicate that
the rectangle is to be filled (not to be confused with the width value
of the ``rect`` parameter)
| if ``width == 0``, (default) fill the rectangle
| if ``width > 0``, used for line thickness
| if ``width < 0``, nothing will be drawn
|
.. versionchanged:: 2.1.1
Drawing rects with width now draws the width correctly inside the
rect's area, rather than using an internal call to draw.lines(),
which had half the width spill outside the rect area.
:param int border_radius: (optional) used for drawing rectangle with rounded corners.
The supported range is [0, min(height, width) / 2], with 0 representing a rectangle
without rounded corners.
:param int border_top_left_radius: (optional) used for setting the value of top left
border. If you don't set this value, it will use the border_radius value.
:param int border_top_right_radius: (optional) used for setting the value of top right
border. If you don't set this value, it will use the border_radius value.
:param int border_bottom_left_radius: (optional) used for setting the value of bottom left
border. If you don't set this value, it will use the border_radius value.
:param int border_bottom_right_radius: (optional) used for setting the value of bottom right
border. If you don't set this value, it will use the border_radius value.
| if ``border_radius < 1`` it will draw rectangle without rounded corners
| if any of border radii has the value ``< 0`` it will use value of the border_radius
| If sum of radii on the same side of the rectangle is greater than the rect size the radii
| will get scaled
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the given ``rect``
parameter and its width and height will be 0
:rtype: Rect
.. note::
The :func:`pygame.Surface.fill()` method works just as well for drawing
filled rectangles and can be hardware accelerated on some platforms.
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. versionchanged:: 2.0.0.dev8 Added support for border radius.
.. ## pygame.draw.rect ##
.. function:: polygon
| :sl:`draw a polygon`
| :sg:`polygon(surface, color, points) -> Rect`
| :sg:`polygon(surface, color, points, width=0) -> Rect`
Draws a polygon on the given surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param points: a sequence of 3 or more (x, y) coordinates that make up the
vertices of the polygon, each *coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats,
e.g. ``[(x1, y1), (x2, y2), (x3, y3)]``
:type points: tuple(coordinate) or list(coordinate)
:param int width: (optional) used for line thickness or to indicate that
the polygon is to be filled
| if width == 0, (default) fill the polygon
| if width > 0, used for line thickness
| if width < 0, nothing will be drawn
|
.. note::
When using ``width`` values ``> 1``, the edge lines will grow
outside the original boundary of the polygon. For more details on
how the thickness for edge lines grow, refer to the ``width`` notes
of the :func:`pygame.draw.line` function.
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the first point in the
``points`` parameter (float values will be truncated) and its width and
height will be 0
:rtype: Rect
:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs
.. note::
For an aapolygon, use :func:`aalines()` with ``closed=True``.
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.polygon ##
.. function:: circle
| :sl:`draw a circle`
| :sg:`circle(surface, color, center, radius) -> Rect`
| :sg:`circle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None) -> Rect`
Draws a circle on the given surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param center: center point of the circle as a sequence of 2 ints/floats,
e.g. ``(x, y)``
:type center: tuple(int or float, int or float) or
list(int or float, int or float) or Vector2(int or float, int or float)
:param radius: radius of the circle, measured from the ``center`` parameter,
nothing will be drawn if the ``radius`` is less than 1
:type radius: int or float
:param int width: (optional) used for line thickness or to indicate that
the circle is to be filled
| if ``width == 0``, (default) fill the circle
| if ``width > 0``, used for line thickness
| if ``width < 0``, nothing will be drawn
|
.. note::
When using ``width`` values ``> 1``, the edge lines will only grow
inward.
:param bool draw_top_right: (optional) if this is set to True then the top right corner
of the circle will be drawn
:param bool draw_top_left: (optional) if this is set to True then the top left corner
of the circle will be drawn
:param bool draw_bottom_left: (optional) if this is set to True then the bottom left corner
of the circle will be drawn
:param bool draw_bottom_right: (optional) if this is set to True then the bottom right corner
of the circle will be drawn
| if any of the draw_circle_part is True then it will draw all circle parts that have the True
| value, otherwise it will draw the entire circle.
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the ``center`` parameter value (float
values will be truncated) and its width and height will be 0
:rtype: Rect
:raises TypeError: if ``center`` is not a sequence of two numbers
:raises TypeError: if ``radius`` is not a number
.. versionchanged:: 2.0.0 Added support for keyword arguments.
Nothing is drawn when the radius is 0 (a pixel at the ``center`` coordinates
used to be drawn when the radius equaled 0).
Floats, and Vector2 are accepted for the ``center`` param.
The drawing algorithm was improved to look more like a circle.
.. versionchanged:: 2.0.0.dev8 Added support for drawing circle quadrants.
.. ## pygame.draw.circle ##
.. function:: ellipse
| :sl:`draw an ellipse`
| :sg:`ellipse(surface, color, rect) -> Rect`
| :sg:`ellipse(surface, color, rect, width=0) -> Rect`
Draws an ellipse on the given surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param Rect rect: rectangle to indicate the position and dimensions of the
ellipse, the ellipse will be centered inside the rectangle and bounded
by it
:param int width: (optional) used for line thickness or to indicate that
the ellipse is to be filled (not to be confused with the width value
of the ``rect`` parameter)
| if ``width == 0``, (default) fill the ellipse
| if ``width > 0``, used for line thickness
| if ``width < 0``, nothing will be drawn
|
.. note::
When using ``width`` values ``> 1``, the edge lines will only grow
inward from the original boundary of the ``rect`` parameter.
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the given ``rect``
parameter and its width and height will be 0
:rtype: Rect
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.ellipse ##
.. function:: arc
| :sl:`draw an elliptical arc`
| :sg:`arc(surface, color, rect, start_angle, stop_angle) -> Rect`
| :sg:`arc(surface, color, rect, start_angle, stop_angle, width=1) -> Rect`
Draws an elliptical arc on the given surface.
The two angle arguments are given in radians and indicate the start and stop
positions of the arc. The arc is drawn in a counterclockwise direction from
the ``start_angle`` to the ``stop_angle``.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param Rect rect: rectangle to indicate the position and dimensions of the
ellipse which the arc will be based on, the ellipse will be centered
inside the rectangle
:param float start_angle: start angle of the arc in radians
:param float stop_angle: stop angle of the arc in
radians
| if ``start_angle < stop_angle``, the arc is drawn in a
counterclockwise direction from the ``start_angle`` to the
``stop_angle``
| if ``start_angle > stop_angle``, tau (tau == 2 * pi) will be added
to the ``stop_angle``, if the resulting stop angle value is greater
than the ``start_angle`` the above ``start_angle < stop_angle`` case
applies, otherwise nothing will be drawn
| if ``start_angle == stop_angle``, nothing will be drawn
|
:param int width: (optional) used for line thickness (not to be confused
with the width value of the ``rect`` parameter)
| if ``width == 0``, nothing will be drawn
| if ``width > 0``, (default is 1) used for line thickness
| if ``width < 0``, same as ``width == 0``
.. note::
When using ``width`` values ``> 1``, the edge lines will only grow
inward from the original boundary of the ``rect`` parameter.
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the given ``rect``
parameter and its width and height will be 0
:rtype: Rect
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.arc ##
.. function:: line
| :sl:`draw a straight line`
| :sg:`line(surface, color, start_pos, end_pos) -> Rect`
| :sg:`line(surface, color, start_pos, end_pos, width=1) -> Rect`
Draws a straight line on the given surface. There are no endcaps. For thick
lines the ends are squared off.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param start_pos: start position of the line, (x, y)
:type start_pos: tuple(int or float, int or float) or
list(int or float, int or float) or Vector2(int or float, int or float)
:param end_pos: end position of the line, (x, y)
:type end_pos: tuple(int or float, int or float) or
list(int or float, int or float) or Vector2(int or float, int or float)
:param int width: (optional) used for line thickness
| if width >= 1, used for line thickness (default is 1)
| if width < 1, nothing will be drawn
|
.. note::
When using ``width`` values ``> 1``, lines will grow as follows.
For odd ``width`` values, the thickness of each line grows with the
original line being in the center.
For even ``width`` values, the thickness of each line grows with the
original line being offset from the center (as there is no exact
center line drawn). As a result, lines with a slope < 1
(horizontal-ish) will have 1 more pixel of thickness below the
original line (in the y direction). Lines with a slope >= 1
(vertical-ish) will have 1 more pixel of thickness to the right of
the original line (in the x direction).
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the ``start_pos`` parameter value (float
values will be truncated) and its width and height will be 0
:rtype: Rect
:raises TypeError: if ``start_pos`` or ``end_pos`` is not a sequence of
two numbers
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.line ##
.. function:: lines
| :sl:`draw multiple contiguous straight line segments`
| :sg:`lines(surface, color, closed, points) -> Rect`
| :sg:`lines(surface, color, closed, points, width=1) -> Rect`
Draws a sequence of contiguous straight lines on the given surface. There are
no endcaps or miter joints. For thick lines the ends are squared off.
Drawing thick lines with sharp corners can have undesired looking results.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param bool closed: if ``True`` an additional line segment is drawn between
the first and last points in the ``points`` sequence
:param points: a sequence of 2 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats and adjacent
coordinates will be connected by a line segment, e.g. for the
points ``[(x1, y1), (x2, y2), (x3, y3)]`` a line segment will be drawn
from ``(x1, y1)`` to ``(x2, y2)`` and from ``(x2, y2)`` to ``(x3, y3)``,
additionally if the ``closed`` parameter is ``True`` another line segment
will be drawn from ``(x3, y3)`` to ``(x1, y1)``
:type points: tuple(coordinate) or list(coordinate)
:param int width: (optional) used for line thickness
| if width >= 1, used for line thickness (default is 1)
| if width < 1, nothing will be drawn
|
.. note::
When using ``width`` values ``> 1`` refer to the ``width`` notes
of :func:`line` for details on how thick lines grow.
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the first point in the
``points`` parameter (float values will be truncated) and its width and
height will be 0
:rtype: Rect
:raises ValueError: if ``len(points) < 2`` (must have at least 2 points)
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.lines ##
.. function:: aaline
| :sl:`draw a straight antialiased line`
| :sg:`aaline(surface, color, start_pos, end_pos) -> Rect`
| :sg:`aaline(surface, color, start_pos, end_pos, blend=1) -> Rect`
Draws a straight antialiased line on the given surface.
The line has a thickness of one pixel and the endpoints have a height and
width of one pixel each.
The way a line and its endpoints are drawn:
If both endpoints are equal, only a single pixel is drawn (after
rounding floats to nearest integer).
Otherwise if the line is not steep (i.e. if the length along the x-axis
is greater than the height along the y-axis):
For each endpoint:
If ``x``, the endpoint's x-coordinate, is a whole number find
which pixels would be covered by it and draw them.
Otherwise:
Calculate the position of the nearest point with a whole number
for its x-coordinate, when extending the line past the
endpoint.
Find which pixels would be covered and how much by that point.
If the endpoint is the left one, multiply the coverage by (1 -
the decimal part of ``x``).
Otherwise multiply the coverage by the decimal part of ``x``.
Then draw those pixels.
*e.g.:*
| The left endpoint of the line ``((1, 1.3), (5, 3))`` would
cover 70% of the pixel ``(1, 1)`` and 30% of the pixel
``(1, 2)`` while the right one would cover 100% of the
pixel ``(5, 3)``.
| The left endpoint of the line ``((1.2, 1.4), (4.6, 3.1))``
would cover 56% *(i.e. 0.8 * 70%)* of the pixel ``(1, 1)``
and 24% *(i.e. 0.8 * 30%)* of the pixel ``(1, 2)`` while
the right one would cover 42% *(i.e. 0.6 * 70%)* of the
pixel ``(5, 3)`` and 18% *(i.e. 0.6 * 30%)* of the pixel
``(5, 4)`` while the right
Then for each point between the endpoints, along the line, whose
x-coordinate is a whole number:
Find which pixels would be covered and how much by that point and
draw them.
*e.g.:*
| The points along the line ``((1, 1), (4, 2.5))`` would be
``(2, 1.5)`` and ``(3, 2)`` and would cover 50% of the pixel
``(2, 1)``, 50% of the pixel ``(2, 2)`` and 100% of the pixel
``(3, 2)``.
| The points along the line ``((1.2, 1.4), (4.6, 3.1))`` would
be ``(2, 1.8)`` (covering 20% of the pixel ``(2, 1)`` and 80%
of the pixel ``(2, 2)``), ``(3, 2.3)`` (covering 70% of the
pixel ``(3, 2)`` and 30% of the pixel ``(3, 3)``) and ``(4,
2.8)`` (covering 20% of the pixel ``(2, 1)`` and 80% of the
pixel ``(2, 2)``)
Otherwise do the same for steep lines as for non-steep lines except
along the y-axis instead of the x-axis (using ``y`` instead of ``x``,
top instead of left and bottom instead of right).
.. note::
Regarding float values for coordinates, a point with coordinate
consisting of two whole numbers is considered being right in the center
of said pixel (and having a height and width of 1 pixel would therefore
completely cover it), while a point with coordinate where one (or both)
of the numbers have non-zero decimal parts would be partially covering
two (or four if both numbers have decimal parts) adjacent pixels, *e.g.*
the point ``(1.4, 2)`` covers 60% of the pixel ``(1, 2)`` and 40% of the
pixel ``(2,2)``.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param start_pos: start position of the line, (x, y)
:type start_pos: tuple(int or float, int or float) or
list(int or float, int or float) or Vector2(int or float, int or float)
:param end_pos: end position of the line, (x, y)
:type end_pos: tuple(int or float, int or float) or
list(int or float, int or float) or Vector2(int or float, int or float)
:param int blend: (optional) (deprecated) if non-zero (default) the line will be blended
with the surface's existing pixel shades, otherwise it will overwrite them
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the ``start_pos`` parameter value (float
values will be truncated) and its width and height will be 0
:rtype: Rect
:raises TypeError: if ``start_pos`` or ``end_pos`` is not a sequence of
two numbers
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.aaline ##
.. function:: aalines
| :sl:`draw multiple contiguous straight antialiased line segments`
| :sg:`aalines(surface, color, closed, points) -> Rect`
| :sg:`aalines(surface, color, closed, points, blend=1) -> Rect`
Draws a sequence of contiguous straight antialiased lines on the given
surface.
:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or int or tuple(int, int, int, [int])
:param bool closed: if ``True`` an additional line segment is drawn between
the first and last points in the ``points`` sequence
:param points: a sequence of 2 or more (x, y) coordinates, where each
*coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats and adjacent
coordinates will be connected by a line segment, e.g. for the
points ``[(x1, y1), (x2, y2), (x3, y3)]`` a line segment will be drawn
from ``(x1, y1)`` to ``(x2, y2)`` and from ``(x2, y2)`` to ``(x3, y3)``,
additionally if the ``closed`` parameter is ``True`` another line segment
will be drawn from ``(x3, y3)`` to ``(x1, y1)``
:type points: tuple(coordinate) or list(coordinate)
:param int blend: (optional) (deprecated) if non-zero (default) each line will be blended
with the surface's existing pixel shades, otherwise the pixels will be
overwritten
:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the first point in the
``points`` parameter (float values will be truncated) and its width and
height will be 0
:rtype: Rect
:raises ValueError: if ``len(points) < 2`` (must have at least 2 points)
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs
.. versionchanged:: 2.0.0 Added support for keyword arguments.
.. ## pygame.draw.aalines ##
.. ## pygame.draw ##
.. figure:: code_examples/draw_module_example.png
:alt: draw module example
Example code for draw module.
.. literalinclude:: code_examples/draw_module_example.py

View File

@@ -0,0 +1,565 @@
.. include:: common.txt
:mod:`pygame.event`
===================
.. module:: pygame.event
:synopsis: pygame module for interacting with events and queues
| :sl:`pygame module for interacting with events and queues`
Pygame handles all its event messaging through an event queue. The routines in
this module help you manage that event queue. The input queue is heavily
dependent on the :mod:`pygame.display` module. If the display has not been
initialized and a video mode not set, the event queue may not work properly.
The event queue has an upper limit on the number of events it can hold. When
the queue becomes full new events are quietly dropped. To prevent lost events,
especially input events which signal a quit command, your program must handle
events every frame (with ``pygame.event.get()``, ``pygame.event.pump()``,
``pygame.event.wait()``, ``pygame.event.peek()`` or ``pygame.event.clear()``)
and process them. Not handling events may cause your system to decide your
program has locked up. To speed up queue processing use
:func:`pygame.event.set_blocked()` to limit which events get queued.
To get the state of various input devices, you can forego the event queue and
access the input devices directly with their appropriate modules:
:mod:`pygame.mouse`, :mod:`pygame.key`, and :mod:`pygame.joystick`. If you use
this method, remember that pygame requires some form of communication with the
system window manager and other parts of the platform. To keep pygame in sync
with the system, you will need to call :func:`pygame.event.pump()` to keep
everything current. Usually, this should be called once per game loop.
Note: Joysticks will not send any events until the device has been initialized.
The event queue contains :class:`pygame.event.Event` event objects.
There are a variety of ways to access the queued events, from simply
checking for the existence of events, to grabbing them directly off the stack.
The event queue also offers some simple filtering which can slightly help
performance by blocking certain event types from the queue. Use
:func:`pygame.event.set_allowed()` and :func:`pygame.event.set_blocked()` to
change this filtering. By default, all event types can be placed on the queue.
All :class:`pygame.event.Event` instances contain an event type identifier
and attributes specific to that event type. The event type identifier is
accessible as the :attr:`pygame.event.Event.type` property. Any of the
event specific attributes can be accessed through the
:attr:`pygame.event.Event.__dict__` attribute or directly as an attribute
of the event object (as member lookups are passed through to the object's
dictionary values). The event object has no method functions. Users can create
their own new events with the :func:`pygame.event.Event()` function.
The event type identifier is in between the values of ``NOEVENT`` and
``NUMEVENTS``. User defined events should have a value in the inclusive range
of ``USEREVENT`` to ``NUMEVENTS - 1``. User defined events can get a custom
event number with :func:`pygame.event.custom_type()`.
It is recommended all user events follow this system.
Events support equality and inequality comparisons. Two events are equal if
they are the same type and have identical attribute values.
While debugging and experimenting, you can print an event object for a quick
display of its type and members. The function :func:`pygame.event.event_name()`
can be used to get a string representing the name of the event type.
Events that come from the system will have a guaranteed set of member
attributes based on the type. The following is a list event types with their
specific attributes.
::
QUIT none
ACTIVEEVENT gain, state
KEYDOWN key, mod, unicode, scancode
KEYUP key, mod, unicode, scancode
MOUSEMOTION pos, rel, buttons, touch
MOUSEBUTTONUP pos, button, touch
MOUSEBUTTONDOWN pos, button, touch
JOYAXISMOTION joy (deprecated), instance_id, axis, value
JOYBALLMOTION joy (deprecated), instance_id, ball, rel
JOYHATMOTION joy (deprecated), instance_id, hat, value
JOYBUTTONUP joy (deprecated), instance_id, button
JOYBUTTONDOWN joy (deprecated), instance_id, button
VIDEORESIZE size, w, h
VIDEOEXPOSE none
USEREVENT code
.. versionchanged:: 2.0.0 The ``joy`` attribute was deprecated, ``instance_id`` was added.
.. versionchanged:: 2.0.1 The ``unicode`` attribute was added to ``KEYUP`` event.
Note that ``ACTIVEEVENT``, ``VIDEORESIZE`` and ``VIDEOEXPOSE`` are considered
as "legacy" events, the use of pygame2 ``WINDOWEVENT`` API is recommended over
the use of this older API.
You can also find a list of constants for keyboard keys
:ref:`here <key-constants-label>`.
A keyboard event occurs when a key is pressed (``KEYDOWN``) and when a key is released (``KEYUP``)
The ``key`` attribute of keyboard events contains the value of what key was pressed or released.
The ``mod`` attribute contains information about the state of keyboard modifiers (SHIFT, CTRL, ALT, etc.).
The ``unicode`` attribute stores the 16-bit unicode value of the key that was pressed or released.
The ``scancode`` attribute represents the physical location of a key on the keyboard.
The ``ACTIVEEVENT`` contains information about the application gaining or losing focus. The ``gain`` attribute
will be 1 if the mouse enters the window, otherwise ``gain`` will be 0. The ``state`` attribute will have a
value of ``SDL_APPMOUSEFOCUS`` if mouse focus was gained/lost, ``SDL_APPINPUTFOCUS`` if the application loses
or gains keyboard focus, or ``SDL_APPACTIVE`` if the application is minimized (``gain`` will be 0) or restored.
|
When compiled with SDL2, pygame has these additional events and their
attributes.
::
AUDIODEVICEADDED which, iscapture (SDL backend >= 2.0.4)
AUDIODEVICEREMOVED which, iscapture (SDL backend >= 2.0.4)
FINGERMOTION touch_id, finger_id, x, y, dx, dy
FINGERDOWN touch_id, finger_id, x, y, dx, dy
FINGERUP touch_id, finger_id, x, y, dx, dy
MOUSEWHEEL which, flipped, x, y, touch, precise_x, precise_y
MULTIGESTURE touch_id, x, y, pinched, rotated, num_fingers
TEXTEDITING text, start, length
TEXTINPUT text
.. versionadded:: 1.9.5
.. versionchanged:: 2.0.2 Fixed amount horizontal scroll (x, positive to the right and negative to the left).
.. versionchanged:: 2.0.2 The ``touch`` attribute was added to all the ``MOUSE`` events.
The ``touch`` attribute of ``MOUSE`` events indicates whether or not the events were generated
by a touch input device, and not a real mouse. You might want to ignore such events, if your application
already handles ``FINGERMOTION``, ``FINGERDOWN`` and ``FINGERUP`` events.
.. versionadded:: 2.1.3 Added ``precise_x`` and ``precise_y`` to ``MOUSEWHEEL`` events
``MOUSEWHEEL`` event occurs whenever the mouse wheel is moved.
The ``which`` attribute determines if the event was generated from a touch input device vs an actual
mousewheel.
The ``preciseX`` attribute contains a float with the amount scrolled horizontally (positive to the right,
negative to the left).
The ``preciseY`` attribute contains a float with the amount scrolled vertically (positive away from user,
negative towards user).
The ``flipped`` attribute determines if the values in x and y will be opposite or not. If ``SDL_MOUSEWHEEL_FLIPPED``
is defined, the direction of x and y will be opposite.
``TEXTEDITING`` event is triggered when a user activates an input method via hotkey or selecting an
input method in a GUI and starts typing
The ``which`` attribute for ``AUDIODEVICE*`` events is an integer representing the index for new audio
devices that are added. ``AUDIODEVICE*`` events are used to update audio settings or device list.
|
Many new events were introduced in pygame 2.
pygame can recognize text or files dropped in its window. If a file
is dropped, ``DROPFILE`` event will be sent, ``file`` will be its path.
The ``DROPTEXT`` event is only supported on X11.
``MIDIIN`` and ``MIDIOUT`` are events reserved for :mod:`pygame.midi` use.
``MIDI*`` events differ from ``AUDIODEVICE*`` events in that AUDIODEVICE
events are triggered when there is a state change related to an audio
input/output device.
pygame 2 also supports controller hot-plugging
::
Event name Attributes and notes
DROPFILE file
DROPBEGIN (SDL backend >= 2.0.5)
DROPCOMPLETE (SDL backend >= 2.0.5)
DROPTEXT text (SDL backend >= 2.0.5)
MIDIIN
MIDIOUT
CONTROLLERDEVICEADDED device_index
JOYDEVICEADDED device_index
CONTROLLERDEVICEREMOVED instance_id
JOYDEVICEREMOVED instance_id
CONTROLLERDEVICEREMAPPED instance_id
KEYMAPCHANGED (SDL backend >= 2.0.4)
CLIPBOARDUPDATE
RENDER_TARGETS_RESET (SDL backend >= 2.0.2)
RENDER_DEVICE_RESET (SDL backend >= 2.0.4)
LOCALECHANGED (SDL backend >= 2.0.14)
Also in this version, ``instance_id`` attributes were added to joystick events,
and the ``joy`` attribute was deprecated.
``KEYMAPCHANGED`` is a type of an event sent when keymap changes due to a
system event such as an input language or keyboard layout change.
``CLIPBOARDUPDATE`` is an event sent when clipboard changes. This can still
be considered as an experimental feature, some kinds of clipboard changes might
not trigger this event.
``LOCALECHANGED`` is an event sent when user locale changes
.. versionadded:: 2.0.0
.. versionadded:: 2.1.3 ``KEYMAPCHANGED``, ``CLIPBOARDUPDATE``,
``RENDER_TARGETS_RESET``, ``RENDER_DEVICE_RESET`` and ``LOCALECHANGED``
|
Since pygame 2.0.1, there are a new set of events, called window events.
Here is a list of all window events, along with a short description
::
Event type Short description
WINDOWSHOWN Window became shown
WINDOWHIDDEN Window became hidden
WINDOWEXPOSED Window got updated by some external event
WINDOWMOVED Window got moved
WINDOWRESIZED Window got resized
WINDOWSIZECHANGED Window changed its size
WINDOWMINIMIZED Window was minimized
WINDOWMAXIMIZED Window was maximized
WINDOWRESTORED Window was restored
WINDOWENTER Mouse entered the window
WINDOWLEAVE Mouse left the window
WINDOWFOCUSGAINED Window gained focus
WINDOWFOCUSLOST Window lost focus
WINDOWCLOSE Window was closed
WINDOWTAKEFOCUS Window was offered focus (SDL backend >= 2.0.5)
WINDOWHITTEST Window has a special hit test (SDL backend >= 2.0.5)
WINDOWICCPROFCHANGED Window ICC profile changed (SDL backend >= 2.0.18)
WINDOWDISPLAYCHANGED Window moved on a new display (SDL backend >= 2.0.18)
``WINDOWMOVED``, ``WINDOWRESIZED`` and ``WINDOWSIZECHANGED`` have ``x`` and
``y`` attributes, ``WINDOWDISPLAYCHANGED`` has a ``display_index`` attribute.
All windowevents have a ``window`` attribute.
.. versionadded:: 2.0.1
.. versionadded:: 2.1.3 ``WINDOWICCPROFCHANGED`` and ``WINDOWDISPLAYCHANGED``
|
On Android, the following events can be generated
::
Event type Short description
APP_TERMINATING OS is terminating the application
APP_LOWMEMORY OS is low on memory, try to free memory if possible
APP_WILLENTERBACKGROUND Application is entering background
APP_DIDENTERBACKGROUND Application entered background
APP_WILLENTERFOREGROUND Application is entering foreground
APP_DIDENTERFOREGROUND Application entered foreground
.. versionadded:: 2.1.3
|
.. function:: pump
| :sl:`internally process pygame event handlers`
| :sg:`pump() -> None`
For each frame of your game, you will need to make some sort of call to the
event queue. This ensures your program can internally interact with the rest
of the operating system. If you are not using other event functions in your
game, you should call ``pygame.event.pump()`` to allow pygame to handle
internal actions.
This function is not necessary if your program is consistently processing
events on the queue through the other :mod:`pygame.event` functions.
There are important things that must be dealt with internally in the event
queue. The main window may need to be repainted or respond to the system. If
you fail to make a call to the event queue for too long, the system may
decide your program has locked up.
.. caution::
This function should only be called in the thread that initialized :mod:`pygame.display`.
.. ## pygame.event.pump ##
.. function:: get
| :sl:`get events from the queue`
| :sg:`get(eventtype=None) -> Eventlist`
| :sg:`get(eventtype=None, pump=True) -> Eventlist`
| :sg:`get(eventtype=None, pump=True, exclude=None) -> Eventlist`
This will get all the messages and remove them from the queue. If a type or
sequence of types is given only those messages will be removed from the
queue and returned.
If a type or sequence of types is passed in the ``exclude`` argument
instead, then all only *other* messages will be removed from the queue. If
an ``exclude`` parameter is passed, the ``eventtype`` parameter *must* be
None.
If you are only taking specific events from the queue, be aware that the
queue could eventually fill up with the events you are not interested.
If ``pump`` is ``True`` (the default), then :func:`pygame.event.pump()` will be called.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. versionchanged:: 2.0.2 Added ``exclude`` argument
.. ## pygame.event.get ##
.. function:: poll
| :sl:`get a single event from the queue`
| :sg:`poll() -> Event instance`
Returns a single event from the queue. If the event queue is empty an event
of type ``pygame.NOEVENT`` will be returned immediately. The returned event
is removed from the queue.
.. caution::
This function should only be called in the thread that initialized :mod:`pygame.display`.
.. ## pygame.event.poll ##
.. function:: wait
| :sl:`wait for a single event from the queue`
| :sg:`wait() -> Event instance`
| :sg:`wait(timeout) -> Event instance`
Returns a single event from the queue. If the queue is empty this function
will wait until one is created. From pygame 2.0.0, if a ``timeout`` argument
is given, the function will return an event of type ``pygame.NOEVENT``
if no events enter the queue in ``timeout`` milliseconds. The event is removed
from the queue once it has been returned. While the program is waiting it will
sleep in an idle state. This is important for programs that want to share the
system with other applications.
.. versionchanged:: 2.0.0.dev13 Added ``timeout`` argument
.. caution::
This function should only be called in the thread that initialized :mod:`pygame.display`.
.. ## pygame.event.wait ##
.. function:: peek
| :sl:`test if event types are waiting on the queue`
| :sg:`peek(eventtype=None) -> bool`
| :sg:`peek(eventtype=None, pump=True) -> bool`
Returns ``True`` if there are any events of the given type waiting on the
queue. If a sequence of event types is passed, this will return ``True`` if
any of those events are on the queue.
If ``pump`` is ``True`` (the default), then :func:`pygame.event.pump()` will be called.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. ## pygame.event.peek ##
.. function:: clear
| :sl:`remove all events from the queue`
| :sg:`clear(eventtype=None) -> None`
| :sg:`clear(eventtype=None, pump=True) -> None`
Removes all events from the queue. If ``eventtype`` is given, removes the given event
or sequence of events. This has the same effect as :func:`pygame.event.get()` except ``None``
is returned. It can be slightly more efficient when clearing a full event queue.
If ``pump`` is ``True`` (the default), then :func:`pygame.event.pump()` will be called.
.. versionchanged:: 1.9.5 Added ``pump`` argument
.. ## pygame.event.clear ##
.. function:: event_name
| :sl:`get the string name from an event id`
| :sg:`event_name(type) -> string`
Returns a string representing the name (in CapWords style) of the given
event type.
"UserEvent" is returned for all values in the user event id range.
"Unknown" is returned when the event type does not exist.
.. versionchanged:: 2.5.0 Added support for keyword arguments.
.. ## pygame.event.event_name ##
.. function:: set_blocked
| :sl:`control which events are allowed on the queue`
| :sg:`set_blocked(type) -> None`
| :sg:`set_blocked(typelist) -> None`
| :sg:`set_blocked(None) -> None`
The given event types are not allowed to appear on the event queue. By
default all events can be placed on the queue. It is safe to disable an
event type multiple times.
If ``None`` is passed as the argument, ALL of the event types are blocked
from being placed on the queue.
.. ## pygame.event.set_blocked ##
.. function:: set_allowed
| :sl:`control which events are allowed on the queue`
| :sg:`set_allowed(type) -> None`
| :sg:`set_allowed(typelist) -> None`
| :sg:`set_allowed(None) -> None`
The given event types are allowed to appear on the event queue. By default,
all event types can be placed on the queue. It is safe to enable an event
type multiple times.
If ``None`` is passed as the argument, ALL of the event types are allowed
to be placed on the queue.
.. ## pygame.event.set_allowed ##
.. function:: get_blocked
| :sl:`test if a type of event is blocked from the queue`
| :sg:`get_blocked(type) -> bool`
| :sg:`get_blocked(typelist) -> bool`
Returns ``True`` if the given event type is blocked from the queue. If a
sequence of event types is passed, this will return ``True`` if any of those
event types are blocked.
.. ## pygame.event.get_blocked ##
.. function:: set_grab
| :sl:`control the sharing of input devices with other applications`
| :sg:`set_grab(bool) -> None`
When your program runs in a windowed environment, it will share the mouse
and keyboard devices with other applications that have focus. If your
program sets the event grab to ``True``, it will lock all input into your
program.
It is best to not always grab the input, since it prevents the user from
doing other things on their system.
.. ## pygame.event.set_grab ##
.. function:: get_grab
| :sl:`test if the program is sharing input devices`
| :sg:`get_grab() -> bool`
Returns ``True`` when the input events are grabbed for this application.
.. ## pygame.event.get_grab ##
.. function:: set_keyboard_grab
| :sl:`grab enables capture of system keyboard shortcuts like Alt+Tab or the Meta/Super key.`
| :sg:`set_keyboard_grab(bool) -> None`
Keyboard grab enables capture of system keyboard shortcuts like Alt+Tab or the Meta/Super key.
Note that not all system keyboard shortcuts can be captured by applications (one example is Ctrl+Alt+Del on Windows).
This is primarily intended for specialized applications such as VNC clients or VM frontends. Normal games should not use keyboard grab.
.. versionadded:: 2.5.0
.. ## pygame.event.set_keyboard_grab ##
.. function:: get_keyboard_grab
| :sl:`get the current keyboard grab state`
| :sg:`get_keyboard_grab() -> bool`
Returns ``True`` when keyboard grab is enabled.
.. versionadded:: 2.5.0
.. ## pygame.event.get_keyboard_grab ##
.. function:: post
| :sl:`place a new event on the queue`
| :sg:`post(Event) -> bool`
Places the given event at the end of the event queue.
This is usually used for placing custom events on the event queue.
Any type of event can be posted, and the events posted can have any attributes.
This returns a boolean on whether the event was posted or not. Blocked events
cannot be posted, and this function returns ``False`` if you try to post them.
.. versionchanged:: 2.0.1 returns a boolean, previously returned ``None``
.. ## pygame.event.post ##
.. function:: custom_type
| :sl:`make custom user event type`
| :sg:`custom_type() -> int`
Reserves a ``pygame.USEREVENT`` for a custom use.
If too many events are made a :exc:`pygame.error` is raised.
.. versionadded:: 2.0.0.dev3
.. ## pygame.event.custom_type ##
.. class:: Event
| :sl:`pygame object for representing events`
| :sg:`Event(type, dict) -> Event`
| :sg:`Event(type, \**attributes) -> Event`
A pygame object used for representing an event. ``Event`` instances
support attribute assignment and deletion.
When creating the object, the attributes may come from a dictionary
argument with string keys or from keyword arguments.
.. note::
From version 2.1.3 ``EventType`` is an alias for ``Event``. Beforehand,
``Event`` was a function that returned ``EventType`` instances. Use of
``Event`` is preferred over ``EventType`` wherever it is possible, as
the latter could be deprecated in a future version.
.. attribute:: type
| :sl:`event type identifier.`
| :sg:`type -> int`
Read-only. The event type identifier. For user created event
objects, this is the ``type`` argument passed to
:func:`pygame.event.Event()`.
For example, some predefined event identifiers are ``QUIT`` and
``MOUSEMOTION``.
.. ## pygame.event.Event.type ##
.. attribute:: __dict__
| :sl:`event attribute dictionary`
| :sg:`__dict__ -> dict`
Read-only. The event type specific attributes of an event. The
``dict`` attribute is a synonym for backward compatibility.
For example, the attributes of a ``KEYDOWN`` event would be ``unicode``,
``key``, and ``mod``
.. ## pygame.event.Event.__dict__ ##
.. versionadded:: 1.9.2 Mutable attributes.
.. ## pygame.event.Event ##
.. ## pygame.event ##

View File

@@ -0,0 +1,451 @@
.. include:: common.txt
:mod:`pygame.examples`
======================
.. module:: pygame.examples
:synopsis: module of example programs
| :sl:`module of example programs`
These examples should help get you started with pygame. Here is a brief rundown
of what you get. The source code for these examples is in the public domain.
Feel free to use for your own projects.
There are several ways to run the examples. First they can be run as
stand-alone programs. Second they can be imported and their ``main()`` methods
called (see below). Finally, the easiest way is to use the python -m option:
::
python -m pygame.examples.<example name> <example arguments>
eg:
::
python -m pygame.examples.scaletest someimage.png
Resources such as images and sounds for the examples are found in the
pygame/examples/data subdirectory.
You can find where the example files are installed by using the following
commands inside the python interpreter.
::
>>> import pygame.examples.scaletest
>>> pygame.examples.scaletest.__file__
'/usr/lib/python2.6/site-packages/pygame/examples/scaletest.py'
On each OS and version of Python the location will be slightly different.
For example on Windows it might be in 'C:/Python26/Lib/site-packages/pygame/examples/'
On Mac OS X it might be in '/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/pygame/examples/'
You can also run the examples in the python interpreter by calling each modules main() function.
::
>>> import pygame.examples.scaletest
>>> pygame.examples.scaletest.main()
We're always on the lookout for more examples and/or example requests. Code
like this is probably the best way to start getting involved with python
gaming.
examples as a package is new to pygame 1.9.0. But most of the examples came with
pygame much earlier.
.. function:: aliens.main
| :sl:`play the full aliens example`
| :sg:`aliens.main() -> None`
This started off as a port of the ``SDL`` demonstration, Aliens. Now it has
evolved into something sort of resembling fun. This demonstrates a lot of
different uses of sprites and optimized blitting. Also transparency,
colorkeys, fonts, sound, music, joystick, and more. (PS, my high score is
117! goodluck)
.. ## pygame.examples.aliens.main ##
.. function:: stars.main
| :sl:`run a simple starfield example`
| :sg:`stars.main() -> None`
A simple starfield example. You can change the center of perspective by
leftclicking the mouse on the screen.
.. ## pygame.examples.stars.main ##
.. function:: chimp.main
| :sl:`hit the moving chimp`
| :sg:`chimp.main() -> None`
This simple example is derived from the line-by-line tutorial that comes
with pygame. It is based on a 'popular' web banner. Note there are comments
here, but for the full explanation, follow along in the tutorial.
.. ## pygame.examples.chimp.main ##
.. function:: moveit.main
| :sl:`display animated objects on the screen`
| :sg:`moveit.main() -> None`
This is the full and final example from the Pygame Tutorial, "How Do I Make
It Move". It creates 10 objects and animates them on the screen.
Note it's a bit scant on error checking, but it's easy to read. :]
Fortunately, this is python, and we needn't wrestle with a pile of error
codes.
.. ## pygame.examples.moveit.main ##
.. function:: fonty.main
| :sl:`run a font rendering example`
| :sg:`fonty.main() -> None`
Super quick, super simple application demonstrating the different ways to
render fonts with the font module
.. ## pygame.examples.fonty.main ##
.. function:: freetype_misc.main
| :sl:`run a FreeType rendering example`
| :sg:`freetype_misc.main() -> None`
A showcase of rendering features the :class:`pygame.freetype.Font`
class provides in addition to those available with :class:`pygame.font.Font`.
It is a demonstration of direct to surface rendering, with vertical text
and rotated text, opaque text and semi transparent text, horizontally
stretched text and vertically stretched text.
.. ## pygame.examples.fonty.main ##
.. function:: vgrade.main
| :sl:`display a vertical gradient`
| :sg:`vgrade.main() -> None`
Demonstrates creating a vertical gradient with pixelcopy and NumPy python.
The app will create a new gradient every half second and report the time
needed to create and display the image. If you're not prepared to start
working with the NumPy arrays, don't worry about the source for this one :]
.. ## pygame.examples.vgrade.main ##
.. function:: eventlist.main
| :sl:`display pygame events`
| :sg:`eventlist.main() -> None`
Eventlist is a sloppy style of pygame, but is a handy tool for learning
about pygame events and input. At the top of the screen are the state of
several device values, and a scrolling list of events are displayed on the
bottom.
This is not quality 'ui' code at all, but you can see how to implement very
non-interactive status displays, or even a crude text output control.
.. ## pygame.examples.eventlist.main ##
.. function:: arraydemo.main
| :sl:`show various surfarray effects`
| :sg:`arraydemo.main(arraytype=None) -> None`
Another example filled with various surfarray effects. It requires the
surfarray and image modules to be installed. This little demo can also make
a good starting point for any of your own tests with surfarray
The ``arraytype`` parameter is deprecated; passing any value besides 'numpy'
will raise ValueError.
.. ## pygame.examples.arraydemo.main ##
.. function:: sound.main
| :sl:`load and play a sound`
| :sg:`sound.main(file_path=None) -> None`
Extremely basic testing of the mixer module. Load a sound and play it. All
from the command shell, no graphics.
If provided, use the audio file 'file_path', otherwise use a default file.
``sound.py`` optional command line argument: an audio file
.. ## pygame.examples.sound.main ##
.. function:: sound_array_demos.main
| :sl:`play various sndarray effects`
| :sg:`sound_array_demos.main(arraytype=None) -> None`
Uses sndarray and NumPy to create offset faded copies of the
original sound. Currently it just uses hardcoded values for the number of
echoes and the delay. Easy for you to recreate as needed.
The ``arraytype`` parameter is deprecated; passing any value besides 'numpy'
will raise ValueError.
.. ## pygame.examples.sound_array_demos.main ##
.. function:: liquid.main
| :sl:`display an animated liquid effect`
| :sg:`liquid.main() -> None`
This example was created in a quick comparison with the BlitzBasic gaming
language. Nonetheless, it demonstrates a quick 8-bit setup (with colormap).
.. ## pygame.examples.liquid.main ##
.. function:: glcube.main
| :sl:`display an animated 3D cube using OpenGL`
| :sg:`glcube.main() -> None`
Using PyOpenGL and pygame, this creates a spinning 3D multicolored cube.
.. ## pygame.examples.glcube.main ##
.. function:: scrap_clipboard.main
| :sl:`access the clipboard`
| :sg:`scrap_clipboard.main() -> None`
A simple demonstration example for the clipboard support.
.. ## pygame.examples.scrap_clipboard.main ##
.. function:: mask.main
| :sl:`display multiple images bounce off each other using collision detection`
| :sg:`mask.main(*args) -> None`
Positional arguments:
::
one or more image file names.
This ``pygame.masks`` demo will display multiple moving sprites bouncing off
each other. More than one sprite image can be provided.
If run as a program then ``mask.py`` takes one or more image files as
command line arguments.
.. ## pygame.examples.mask.main ##
.. function:: testsprite.main
| :sl:`show lots of sprites moving around`
| :sg:`testsprite.main(update_rects = True, use_static = False, use_FastRenderGroup = False, screen_dims = [640, 480], use_alpha = False, flags = 0) -> None`
Optional keyword arguments:
::
update_rects - use the RenderUpdate sprite group class
use_static - include non-moving images
use_FastRenderGroup - Use the FastRenderGroup sprite group
screen_dims - pygame window dimensions
use_alpha - use alpha blending
flags - additional display mode flags
Like the ``testsprite.c`` that comes with SDL, this pygame version shows
lots of sprites moving around.
If run as a stand-alone program then no command line arguments are taken.
.. ## pygame.examples.testsprite.main ##
.. function:: headless_no_windows_needed.main
| :sl:`write an image file that is smoothscaled copy of an input file`
| :sg:`headless_no_windows_needed.main(fin, fout, w, h) -> None`
arguments:
::
fin - name of an input image file
fout - name of the output file to create/overwrite
w, h - size of the rescaled image, as integer width and height
How to use pygame with no windowing system, like on headless servers.
Thumbnail generation with scaling is an example of what you can do with
pygame.
``NOTE``: the pygame scale function uses MMX/SSE if available, and can be
run in multiple threads.
If ``headless_no_windows_needed.py`` is run as a program it takes the
following command line arguments:
::
-scale inputimage outputimage new_width new_height
eg. -scale in.png outpng 50 50
.. ## pygame.examples.headless_no_windows_needed.main ##
.. function:: joystick.main
| :sl:`demonstrate joystick functionality`
| :sg:`joystick.main() -> None`
A demo showing full joystick support.
.. versionadded:: 2.0.2
.. ## pygame.examples.joystick.main ##
.. function:: blend_fill.main
| :sl:`demonstrate the various surface.fill method blend options`
| :sg:`blend_fill.main() -> None`
A interactive demo that lets one choose which BLEND_xxx option to apply to a
surface.
.. ## pygame.examples.blend_fill.main ##
.. function:: blit_blends.main
| :sl:`uses alternative additive fill to that of surface.fill`
| :sg:`blit_blends.main() -> None`
Fake additive blending. Using NumPy. it doesn't clamp. Press r,g,b Somewhat
like blend_fill.
.. ## pygame.examples.blit_blends.main ##
.. function:: cursors.main
| :sl:`display two different custom cursors`
| :sg:`cursors.main() -> None`
Display an arrow or circle with crossbar cursor.
.. ## pygame.examples.cursors.main ##
.. function:: pixelarray.main
| :sl:`display various pixelarray generated effects`
| :sg:`pixelarray.main() -> None`
Display various pixelarray generated effects.
.. ## pygame.examples.pixelarray.main ##
.. function:: scaletest.main
| :sl:`interactively scale an image using smoothscale`
| :sg:`scaletest.main(imagefile, convert_alpha=False, run_speed_test=True) -> None`
arguments:
::
imagefile - file name of source image (required)
convert_alpha - use convert_alpha() on the surf (default False)
run_speed_test - (default False)
A smoothscale example that resized an image on the screen. Vertical and
horizontal arrow keys are used to change the width and height of the
displayed image. If the convert_alpha option is True then the source image
is forced to have source alpha, whether or not the original images does. If
run_speed_test is True then a background timing test is performed instead of
the interactive scaler.
If ``scaletest.py`` is run as a program then the command line options are:
::
ImageFile [-t] [-convert_alpha]
[-t] = Run Speed Test
[-convert_alpha] = Use convert_alpha() on the surf.
.. ## pygame.examples.scaletest.main ##
.. function:: midi.main
| :sl:`run a midi example`
| :sg:`midi.main(mode='output', device_id=None) -> None`
Arguments:
::
mode - if 'output' run a midi keyboard output example
'input' run a midi event logger input example
'list' list available midi devices
(default 'output')
device_id - midi device number; if None then use the default midi input or
output device for the system
The output example shows how to translate mouse clicks or computer keyboard
events into midi notes. It implements a rudimentary button widget and state
machine.
The input example shows how to translate midi input to pygame events.
With the use of a virtual midi patch cord the output and input examples can
be run as separate processes and connected so the keyboard output is
displayed on a console.
new to pygame 1.9.0
.. ## pygame.examples.midi.main ##
.. function:: scroll.main
| :sl:`run a Surface.scroll example that shows a magnified image`
| :sg:`scroll.main(image_file=None) -> None`
This example shows a scrollable image that has a zoom factor of eight. It
uses the :meth:`Surface.scroll() <pygame.Surface.scroll>`
function to shift the image on the display surface.
A clip rectangle protects a margin area. If called as a function,
the example accepts an optional image file path. If run as a program it
takes an optional file path command line argument. If no file is provided a
default image file is used.
When running click on a black triangle to move one pixel in the direction
the triangle points. Or use the arrow keys. Close the window or press
``ESC`` to quit.
.. ## pygame.examples.scroll.main ##
.. function:: camera.main
| :sl:`display video captured live from an attached camera`
| :sg:`camera.main() -> None`
A simple live video player, it uses the first available camera it finds on
the system.
.. ## pygame.examples.camera.main ##
.. function:: playmus.main
| :sl:`play an audio file`
| :sg:`playmus.main(file_path) -> None`
A simple music player with window and keyboard playback control. Playback can
be paused and rewound to the beginning.
.. ## pygame.examples.playmus.main ##
.. ## pygame.examples ##

View File

@@ -0,0 +1,109 @@
.. include:: common.txt
:mod:`pygame.fastevent`
=======================
.. module:: pygame.fastevent
:synopsis: pygame module for interacting with events and queues from multiple
threads.
| :sl:`pygame module for interacting with events and queues`
IMPORTANT NOTE: THIS MODULE IS DEPRECATED IN PYGAME 2.2
In older pygame versions before pygame 2, :mod:`pygame.event` was not well
suited for posting events from different threads. This module served as a
replacement (with less features) for multithreaded use. Now, the usage of this
module is highly discouraged in favour of use of the main :mod:`pygame.event`
module. This module will be removed in a future pygame version.
Below, the legacy docs of the module is provided
.. function:: init
| :sl:`initialize pygame.fastevent`
| :sg:`init() -> None`
Initialize the pygame.fastevent module.
.. ## pygame.fastevent.init ##
.. function:: get_init
| :sl:`returns True if the fastevent module is currently initialized`
| :sg:`get_init() -> bool`
Returns True if the pygame.fastevent module is currently initialized.
.. ## pygame.fastevent.get_init ##
.. function:: pump
| :sl:`internally process pygame event handlers`
| :sg:`pump() -> None`
For each frame of your game, you will need to make some sort of call to the
event queue. This ensures your program can internally interact with the rest
of the operating system.
This function is not necessary if your program is consistently processing
events on the queue through the other :mod:`pygame.fastevent` functions.
There are important things that must be dealt with internally in the event
queue. The main window may need to be repainted or respond to the system. If
you fail to make a call to the event queue for too long, the system may
decide your program has locked up.
.. ## pygame.fastevent.pump ##
.. function:: wait
| :sl:`wait for an event`
| :sg:`wait() -> Event`
Returns the current event on the queue. If there are no messages
waiting on the queue, this will not return until one is available.
Sometimes it is important to use this wait to get events from the queue,
it will allow your application to idle when the user isn't doing anything
with it.
.. ## pygame.fastevent.wait ##
.. function:: poll
| :sl:`get an available event`
| :sg:`poll() -> Event`
Returns next event on queue. If there is no event waiting on the queue,
this will return an event with type NOEVENT.
.. ## pygame.fastevent.poll ##
.. function:: get
| :sl:`get all events from the queue`
| :sg:`get() -> list of Events`
This will get all the messages and remove them from the queue.
.. ## pygame.fastevent.get ##
.. function:: post
| :sl:`place an event on the queue`
| :sg:`post(Event) -> None`
This will post your own event objects onto the event queue. You can post
any event type you want, but some care must be taken. For example, if you
post a MOUSEBUTTONDOWN event to the queue, it is likely any code receiving
the event will expect the standard MOUSEBUTTONDOWN attributes to be
available, like 'pos' and 'button'.
Because pygame.fastevent.post() may have to wait for the queue to empty,
you can get into a dead lock if you try to append an event on to a full
queue from the thread that processes events. For that reason I do not
recommend using this function in the main thread of an SDL program.
.. ## pygame.fastevent.post ##
.. ## pygame.fastevent ##

View File

@@ -0,0 +1,499 @@
.. include:: common.txt
:mod:`pygame.font`
==================
.. module:: pygame.font
:synopsis: pygame module for loading and rendering fonts
| :sl:`pygame module for loading and rendering fonts`
The font module allows for rendering TrueType fonts into Surface objects.
This module is built on top of the SDL_ttf library, which comes with all
normal pygame installations.
Most of the work done with fonts are done by using the actual Font objects.
The module by itself only has routines to support the creation of Font objects
with :func:`pygame.font.Font`.
You can load fonts from the system by using the :func:`pygame.font.SysFont`
function. There are a few other functions to help look up the system fonts.
Pygame comes with a builtin default font, freesansbold. This can always be
accessed by passing ``None`` as the font name.
Before pygame 2.0.3, pygame.font accepts any UCS-2 / UTF-16 character
('\\u0001' to '\\uFFFF'). After 2.0.3, pygame.font built with SDL_ttf
2.0.15 accepts any valid UCS-4 / UTF-32 character
(like emojis, if the font has them) ('\\U00000001' to '\\U0010FFFF')).
More about this in :func:`Font.render`.
Before pygame 2.0.3, this character space restriction can be avoided by
using the :mod:`pygame.freetype` based ``pygame.ftfont`` to emulate the Font
module. This can be used by defining the environment variable PYGAME_FREETYPE
before the first import of :mod:`pygame`. Since the problem ``pygame.ftfont``
solves no longer exists, it will likely be removed in the future.
.. function:: init
| :sl:`initialize the font module`
| :sg:`init() -> None`
This method is called automatically by ``pygame.init()``. It initializes the
font module. The module must be initialized before any other functions will
work.
It is safe to call this function more than once.
.. ## pygame.font.init ##
.. function:: quit
| :sl:`uninitialize the font module`
| :sg:`quit() -> None`
Manually uninitialize SDL_ttf's font system. This is called automatically by
``pygame.quit()``.
It is safe to call this function even if font is currently not initialized.
.. ## pygame.font.quit ##
.. function:: get_init
| :sl:`true if the font module is initialized`
| :sg:`get_init() -> bool`
Test if the font module is initialized or not.
.. ## pygame.font.get_init ##
.. function:: get_default_font
| :sl:`get the filename of the default font`
| :sg:`get_default_font() -> string`
Return the filename of the system font. This is not the full path to the
file. This file can usually be found in the same directory as the font
module, but it can also be bundled in separate archives.
.. ## pygame.font.get_default_font ##
.. function:: get_sdl_ttf_version
| :sl:`gets SDL_ttf version`
| :sg:`get_sdl_ttf_version(linked=True) -> (major, minor, patch)`
**Experimental:** feature still in development available for testing and feedback. It may change.
`Please leave get_sdl_ttf_version feedback with authors <https://github.com/pygame/pygame/pull/3095>`_
Returns a tuple of integers that identify SDL_ttf's version.
SDL_ttf is the underlying font rendering library, written in C,
on which pygame's font module depends. If 'linked' is True (the default),
the function returns the version of the linked TTF library.
Otherwise this function returns the version of TTF pygame was compiled with
.. versionadded:: 2.1.3
.. ## pygame.font.get_sdl_ttf_version ##
.. function:: get_fonts
| :sl:`get all available fonts`
| :sg:`get_fonts() -> list of strings`
Returns a list of all the fonts available on the system. The names of the
fonts will be set to lowercase with all spaces and punctuation removed. This
works on most systems, but some will return an empty list if they cannot
find fonts.
.. versionchanged:: 2.1.3 Checks through user fonts instead of just global fonts for Windows.
.. ## pygame.font.get_fonts ##
.. function:: match_font
| :sl:`find a specific font on the system`
| :sg:`match_font(name, bold=False, italic=False) -> path`
Returns the full path to a font file on the system. If bold or italic are
set to true, this will attempt to find the correct family of font.
The font name can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
If none of the given names are found, None is returned.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. versionchanged:: 2.1.3 Checks through user fonts instead of just global fonts for Windows.
Example:
::
print pygame.font.match_font('bitstreamverasans')
# output is: /usr/share/fonts/truetype/ttf-bitstream-vera/Vera.ttf
# (but only if you have Vera on your system)
.. ## pygame.font.match_font ##
.. function:: SysFont
| :sl:`create a Font object from the system fonts`
| :sg:`SysFont(name, size, bold=False, italic=False) -> Font`
Return a new Font object that is loaded from the system fonts. The font will
match the requested bold and italic flags. Pygame uses a small set of common
font aliases. If the specific font you ask for is not available, a reasonable
alternative may be used. If a suitable system font is not found this will
fall back on loading the default pygame font.
The font name can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. versionchanged:: 2.1.3 Checks through user fonts instead of just global fonts for Windows.
.. ## pygame.font.SysFont ##
.. class:: Font
| :sl:`create a new Font object from a file`
| :sg:`Font(file_path=None, size=12) -> Font`
| :sg:`Font(file_path, size) -> Font`
| :sg:`Font(pathlib.Path, size) -> Font`
| :sg:`Font(object, size) -> Font`
Load a new font from a given filename or a python file object. The size is
the height of the font in pixels. If the filename is ``None`` the pygame
default font will be loaded. If a font cannot be loaded from the arguments
given an exception will be raised. Once the font is created the size cannot
be changed. If no arguments are given then the default font will be used and
a font size of 12 is used.
Font objects are mainly used to render text into new Surface objects. The
render can emulate bold or italic features, but it is better to load from a
font with actual italic or bold glyphs.
.. attribute:: bold
| :sl:`Gets or sets whether the font should be rendered in (faked) bold.`
| :sg:`bold -> bool`
Whether the font should be rendered in bold.
When set to True, this enables the bold rendering of text. This
is a fake stretching of the font that doesn't look good on many
font types. If possible load the font from a real bold font
file. While bold, the font will have a different width than when
normal. This can be mixed with the italic, underline and
strikethrough modes.
.. versionadded:: 2.0.0
.. ## Font.bold ##
.. attribute:: italic
| :sl:`Gets or sets whether the font should be rendered in (faked) italics.`
| :sg:`italic -> bool`
Whether the font should be rendered in italic.
When set to True, this enables fake rendering of italic
text. This is a fake skewing of the font that doesn't look good
on many font types. If possible load the font from a real italic
font file. While italic the font will have a different width
than when normal. This can be mixed with the bold, underline and
strikethrough modes.
.. versionadded:: 2.0.0
.. ## Font.italic ##
.. attribute:: underline
| :sl:`Gets or sets whether the font should be rendered with an underline.`
| :sg:`underline -> bool`
Whether the font should be rendered in underline.
When set to True, all rendered fonts will include an
underline. The underline is always one pixel thick, regardless
of font size. This can be mixed with the bold, italic and
strikethrough modes.
.. versionadded:: 2.0.0
.. ## Font.underline ##
.. attribute:: strikethrough
| :sl:`Gets or sets whether the font should be rendered with a strikethrough.`
| :sg:`strikethrough -> bool`
Whether the font should be rendered with a strikethrough.
When set to True, all rendered fonts will include an
strikethrough. The strikethrough is always one pixel thick,
regardless of font size. This can be mixed with the bold,
italic and underline modes.
.. versionadded:: 2.1.3
.. ## Font.strikethrough ##
.. method:: render
| :sl:`draw text on a new Surface`
| :sg:`render(text, antialias, color, background=None) -> Surface`
This creates a new Surface with the specified text rendered on it.
:mod:`pygame.font` provides no way to directly draw text on an existing
Surface: instead you must use :func:`Font.render` to create an image
(Surface) of the text, then blit this image onto another Surface.
The text can only be a single line: newline characters are not rendered.
Null characters ('\x00') raise a TypeError. Both Unicode and char (byte)
strings are accepted. For Unicode strings only UCS-2 characters
('\\u0001' to '\\uFFFF') were previously supported and any greater
unicode codepoint would raise a UnicodeError. Now, characters in the
UCS-4 range are supported. For char strings a ``LATIN1`` encoding is
assumed. The antialias argument is a boolean: if True the characters
will have smooth edges. The color argument is the color of the text
[e.g.: (0,0,255) for blue]. The optional background argument is a color
to use for the text background. If no background is passed the area
outside the text will be transparent.
The Surface returned will be of the dimensions required to hold the text.
(the same as those returned by :func:`Font.size`). If an empty string is passed
for the text, a blank surface will be returned that is zero pixel wide and
the height of the font.
Depending on the type of background and antialiasing used, this returns
different types of Surfaces. For performance reasons, it is good to know
what type of image will be used. If antialiasing is not used, the return
image will always be an 8-bit image with a two-color palette. If the
background is transparent a colorkey will be set. Antialiased images are
rendered to 24-bit ``RGB`` images. If the background is transparent a
pixel alpha will be included.
Optimization: if you know that the final destination for the text (on the
screen) will always have a solid background, and the text is antialiased,
you can improve performance by specifying the background color. This will
cause the resulting image to maintain transparency information by
colorkey rather than (much less efficient) alpha values.
If you render '\\n' an unknown char will be rendered. Usually a
rectangle. Instead you need to handle newlines yourself.
Font rendering is not thread safe: only a single thread can render text
at any time.
.. versionchanged:: 2.0.3 Rendering UCS4 unicode works and does not
raise an exception. Use `if hasattr(pygame.font, "UCS4"):` to see if
pygame supports rendering UCS4 unicode including more languages and
emoji.
.. ## Font.render ##
.. method:: size
| :sl:`determine the amount of space needed to render text`
| :sg:`size(text) -> (width, height)`
Returns the dimensions needed to render the text. This can be used to
help determine the positioning needed for text before it is rendered. It
can also be used for word wrapping and other layout effects.
Be aware that most fonts use kerning which adjusts the widths for
specific letter pairs. For example, the width for "ae" will not always
match the width for "a" + "e".
.. ## Font.size ##
.. method:: set_underline
| :sl:`control if text is rendered with an underline`
| :sg:`set_underline(bool) -> None`
When enabled, all rendered fonts will include an underline. The underline
is always one pixel thick, regardless of font size. This can be mixed
with the bold, italic and strikethrough modes.
.. note:: This is the same as the :attr:`underline` attribute.
.. ## Font.set_underline ##
.. method:: get_underline
| :sl:`check if text will be rendered with an underline`
| :sg:`get_underline() -> bool`
Return True when the font underline is enabled.
.. note:: This is the same as the :attr:`underline` attribute.
.. ## Font.get_underline ##
.. method:: set_strikethrough
| :sl:`control if text is rendered with a strikethrough`
| :sg:`set_strikethrough(bool) -> None`
When enabled, all rendered fonts will include a strikethrough. The
strikethrough is always one pixel thick, regardless of font size.
This can be mixed with the bold, italic and underline modes.
.. note:: This is the same as the :attr:`strikethrough` attribute.
.. versionadded:: 2.1.3
.. ## Font.set_strikethrough ##
.. method:: get_strikethrough
| :sl:`check if text will be rendered with a strikethrough`
| :sg:`get_strikethrough() -> bool`
Return True when the font strikethrough is enabled.
.. note:: This is the same as the :attr:`strikethrough` attribute.
.. versionadded:: 2.1.3
.. ## Font.get_strikethrough ##
.. method:: set_bold
| :sl:`enable fake rendering of bold text`
| :sg:`set_bold(bool) -> None`
Enables the bold rendering of text. This is a fake stretching of the font
that doesn't look good on many font types. If possible load the font from
a real bold font file. While bold, the font will have a different width
than when normal. This can be mixed with the italic, underline and
strikethrough modes.
.. note:: This is the same as the :attr:`bold` attribute.
.. ## Font.set_bold ##
.. method:: get_bold
| :sl:`check if text will be rendered bold`
| :sg:`get_bold() -> bool`
Return True when the font bold rendering mode is enabled.
.. note:: This is the same as the :attr:`bold` attribute.
.. ## Font.get_bold ##
.. method:: set_italic
| :sl:`enable fake rendering of italic text`
| :sg:`set_italic(bool) -> None`
Enables fake rendering of italic text. This is a fake skewing of the font
that doesn't look good on many font types. If possible load the font from
a real italic font file. While italic the font will have a different
width than when normal. This can be mixed with the bold, underline and
strikethrough modes.
.. note:: This is the same as the :attr:`italic` attribute.
.. ## Font.set_italic ##
.. method:: metrics
| :sl:`gets the metrics for each character in the passed string`
| :sg:`metrics(text) -> list`
The list contains tuples for each character, which contain the minimum
``X`` offset, the maximum ``X`` offset, the minimum ``Y`` offset, the
maximum ``Y`` offset and the advance offset (bearing plus width) of the
character. [(minx, maxx, miny, maxy, advance), (minx, maxx, miny, maxy,
advance), ...]. None is entered in the list for each unrecognized
character.
.. ## Font.metrics ##
.. method:: get_italic
| :sl:`check if the text will be rendered italic`
| :sg:`get_italic() -> bool`
Return True when the font italic rendering mode is enabled.
.. note:: This is the same as the :attr:`italic` attribute.
.. ## Font.get_italic ##
.. method:: get_linesize
| :sl:`get the line space of the font text`
| :sg:`get_linesize() -> int`
Return the height in pixels for a line of text with the font. When
rendering multiple lines of text this is the recommended amount of space
between lines.
.. ## Font.get_linesize ##
.. method:: get_height
| :sl:`get the height of the font`
| :sg:`get_height() -> int`
Return the height in pixels of the actual rendered text. This is the
average size for each glyph in the font.
.. ## Font.get_height ##
.. method:: get_ascent
| :sl:`get the ascent of the font`
| :sg:`get_ascent() -> int`
Return the height in pixels for the font ascent. The ascent is the number
of pixels from the font baseline to the top of the font.
.. ## Font.get_ascent ##
.. method:: get_descent
| :sl:`get the descent of the font`
| :sg:`get_descent() -> int`
Return the height in pixels for the font descent. The descent is the
number of pixels from the font baseline to the bottom of the font.
.. ## Font.get_descent ##
.. method:: set_script
| :sl:`set the script code for text shaping`
| :sg:`set_script(str) -> None`
**Experimental:** feature still in development available for testing and feedback. It may change.
`Please leave feedback with authors <https://github.com/pygame/pygame/pull/3330>`_
Sets the script used by harfbuzz text shaping, taking a 4 character
script code as input. For example, Hindi is written in the Devanagari
script, for which the script code is `"Deva"`. See the full list of
script codes in `ISO 15924 <https://www.unicode.org/iso15924/iso15924-codes.html>`_.
This method requires pygame built with SDL_ttf 2.20.0 or above. Otherwise the
method will raise a pygame.error.
.. versionadded:: 2.2.0
.. ## Font.set_script ##
.. ## pygame.font.Font ##
.. ## pygame.font ##

View File

@@ -0,0 +1,770 @@
.. include:: common.txt
:mod:`pygame.freetype`
======================
.. module:: pygame.freetype
:synopsis: Enhanced pygame module for loading and rendering computer fonts
| :sl:`Enhanced pygame module for loading and rendering computer fonts`
The ``pygame.freetype`` module is a replacement for :mod:`pygame.font`.
It has all of the functionality of the original, plus many new features.
Yet is has absolutely no dependencies on the SDL_ttf library.
It is implemented directly on the FreeType 2 library.
The ``pygame.freetype`` module is not itself backward compatible with
:mod:`pygame.font`.
Instead, use the ``pygame.ftfont`` module as a drop-in replacement
for :mod:`pygame.font`.
All font file formats supported by FreeType can be rendered by
``pygame.freetype``, namely ``TTF``, Type1, ``CFF``, OpenType,
``SFNT``, ``PCF``, ``FNT``, ``BDF``, ``PFR`` and Type42 fonts.
All glyphs having UTF-32 code points are accessible
(see :attr:`Font.ucs4`).
Most work on fonts is done using :class:`Font` instances.
The module itself only has routines for initialization and creation
of :class:`Font` objects.
You can load fonts from the system using the :func:`SysFont` function.
Extra support of bitmap fonts is available. Available bitmap sizes can
be listed (see :meth:`Font.get_sizes`). For bitmap only fonts :class:`Font`
can set the size for you (see the :attr:`Font.size` property).
For now undefined character codes are replaced with the ``.notdef``
(not defined) character.
How undefined codes are handled may become configurable in a future release.
Pygame comes with a built-in default font. This can always be accessed by
passing None as the font name to the :class:`Font` constructor.
Extra rendering features available to :class:`pygame.freetype.Font`
are direct to surface rendering (see :meth:`Font.render_to`), character kerning
(see :attr:`Font.kerning`), vertical layout (see :attr:`Font.vertical`),
rotation of rendered text (see :attr:`Font.rotation`),
and the strong style (see :attr:`Font.strong`).
Some properties are configurable, such as
strong style strength (see :attr:`Font.strength`) and underline positioning
(see :attr:`Font.underline_adjustment`). Text can be positioned by the upper
right corner of the text box or by the text baseline (see :attr:`Font.origin`).
Finally, a font's vertical and horizontal size can be adjusted separately
(see :attr:`Font.size`).
The :any:`pygame.examples.freetype_misc <pygame.examples.freetype_misc.main>`
example shows these features in use.
The pygame package does not import ``freetype`` automatically when
loaded. This module must be imported explicitly to be used. ::
import pygame
import pygame.freetype
.. versionadded:: 1.9.2 :mod:`freetype`
.. function:: get_error
| :sl:`Return the latest FreeType error`
| :sg:`get_error() -> str`
| :sg:`get_error() -> None`
Return a description of the last error which occurred in the FreeType2
library, or ``None`` if no errors have occurred.
.. function:: get_version
| :sl:`Return the FreeType version`
| :sg:`get_version(linked=True) -> (int, int, int)`
Returns the version of the FreeType library in use by this module. ``linked=True``
is the default behavior and returns the linked version of FreeType and ``linked=False``
returns the compiled version of FreeType.
Note that the ``freetype`` module depends on the FreeType 2 library.
It will not compile with the original FreeType 1.0. Hence, the first element
of the tuple will always be "2".
.. versionchanged:: 2.2.0 ``linked`` keyword argument added and default behavior changed from returning compiled version to returning linked version
.. function:: init
| :sl:`Initialize the underlying FreeType library.`
| :sg:`init(cache_size=64, resolution=72) -> None`
This function initializes the underlying FreeType library and must be
called before trying to use any of the functionality of the ``freetype``
module.
However, :func:`pygame.init()` will automatically call this function
if the ``freetype`` module is already imported. It is safe to call this
function more than once.
Optionally, you may specify a default *cache_size* for the Glyph cache: the
maximum number of glyphs that will be cached at any given time by the
module. Exceedingly small values will be automatically tuned for
performance. Also a default pixel *resolution*, in dots per inch, can
be given to adjust font scaling.
.. function:: quit
| :sl:`Shut down the underlying FreeType library.`
| :sg:`quit() -> None`
This function closes the ``freetype`` module. After calling this
function, you should not invoke any class, method or function related to the
``freetype`` module as they are likely to fail or might give unpredictable
results. It is safe to call this function even if the module hasn't been
initialized yet.
.. function:: get_init
| :sl:`Returns True if the FreeType module is currently initialized.`
| :sg:`get_init() -> bool`
Returns ``True`` if the ``pygame.freetype`` module is currently initialized.
.. versionadded:: 1.9.5
.. function:: was_init
| :sl:`DEPRECATED: Use get_init() instead.`
| :sg:`was_init() -> bool`
DEPRECATED: Returns ``True`` if the ``pygame.freetype`` module is currently
initialized. Use ``get_init()`` instead.
.. function:: get_cache_size
| :sl:`Return the glyph case size`
| :sg:`get_cache_size() -> long`
See :func:`pygame.freetype.init()`.
.. function:: get_default_resolution
| :sl:`Return the default pixel size in dots per inch`
| :sg:`get_default_resolution() -> long`
Returns the default pixel size, in dots per inch, for the module.
The default is 72 DPI.
.. function:: set_default_resolution
| :sl:`Set the default pixel size in dots per inch for the module`
| :sg:`set_default_resolution([resolution])`
Set the default pixel size, in dots per inch, for the module. If the
optional argument is omitted or zero the resolution is reset to 72 DPI.
.. function:: SysFont
| :sl:`create a Font object from the system fonts`
| :sg:`SysFont(name, size, bold=False, italic=False) -> Font`
Return a new Font object that is loaded from the system fonts. The font will
match the requested *bold* and *italic* flags. Pygame uses a small set of
common font aliases. If the specific font you ask for is not available, a
reasonable alternative may be used. If a suitable system font is not found
this will fall back on loading the default pygame font.
The font *name* can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated font names, in
which case the set of names will be searched in order.
.. versionadded:: 2.0.1 Accept an iterable of font names.
.. function:: get_default_font
| :sl:`Get the filename of the default font`
| :sg:`get_default_font() -> string`
Return the filename of the default pygame font. This is not the full path
to the file. The file is usually in the same directory as the font module,
but can also be bundled in a separate archive.
.. class:: Font
| :sl:`Create a new Font instance from a supported font file.`
| :sg:`Font(file, size=0, font_index=0, resolution=0, ucs4=False) -> Font`
| :sg:`Font(pathlib.Path) -> Font`
Argument *file* can be either a string representing the font's filename, a
file-like object containing the font, or None; if None, a default,
Pygame, font is used.
.. _freetype-font-size-argument:
Optionally, a *size* argument may be specified to set the default size in
points, which determines the size of the rendered characters.
The size can also be passed explicitly to each method call.
Because of the way the caching system works, specifying a default size on
the constructor doesn't imply a performance gain over manually passing
the size on each function call. If the font is bitmap and no *size*
is given, the default size is set to the first available size for the font.
If the font file has more than one font, the font to load can be chosen with
the *index* argument. An exception is raised for an out-of-range font index
value.
The optional *resolution* argument sets the pixel size, in dots per inch,
for use in scaling glyphs for this Font instance. If 0 then the default
module value, set by :func:`init`, is used. The Font object's
resolution can only be changed by re-initializing the Font instance.
The optional *ucs4* argument, an integer, sets the default text translation
mode: 0 (False) recognize UTF-16 surrogate pairs, any other value (True),
to treat Unicode text as UCS-4, with no surrogate pairs. See
:attr:`Font.ucs4`.
.. attribute:: name
| :sl:`Proper font name.`
| :sg:`name -> string`
Read only. Returns the real (long) name of the font, as
recorded in the font file.
.. attribute:: path
| :sl:`Font file path`
| :sg:`path -> unicode`
Read only. Returns the path of the loaded font file
.. attribute:: size
| :sl:`The default point size used in rendering`
| :sg:`size -> float`
| :sg:`size -> (float, float)`
Get or set the default size for text metrics and rendering. It can be
a single point size, given as a Python ``int`` or ``float``, or a
font ppem (width, height) ``tuple``. Size values are non-negative.
A zero size or width represents an undefined size. In this case
the size must be given as a method argument, or an exception is
raised. A zero width but non-zero height is a ValueError.
For a scalable font, a single number value is equivalent to a tuple
with width equal height. A font can be stretched vertically with
height set greater than width, or horizontally with width set
greater than height. For embedded bitmaps, as listed by :meth:`get_sizes`,
use the nominal width and height to select an available size.
Font size differs for a non-scalable, bitmap, font. During a
method call it must match one of the available sizes returned by
method :meth:`get_sizes`. If not, an exception is raised.
If the size is a single number, the size is first matched against the
point size value. If no match, then the available size with the
same nominal width and height is chosen.
.. method:: get_rect
| :sl:`Return the size and offset of rendered text`
| :sg:`get_rect(text, style=STYLE_DEFAULT, rotation=0, size=0) -> rect`
Gets the final dimensions and origin, in pixels, of *text* using the
optional *size* in points, *style*, and *rotation*. For other
relevant render properties, and for any optional argument not given,
the default values set for the :class:`Font` instance are used.
Returns a :class:`Rect <pygame.Rect>` instance containing the
width and height of the text's bounding box and the position of the
text's origin.
The origin is useful in aligning separately rendered pieces of text.
It gives the baseline position and bearing at the start of the text.
See the :meth:`render_to` method for an example.
If *text* is a char (byte) string, its encoding is assumed to be
``LATIN1``.
Optionally, *text* can be ``None``, which will return the bounding
rectangle for the text passed to a previous :meth:`get_rect`,
:meth:`render`, :meth:`render_to`, :meth:`render_raw`, or
:meth:`render_raw_to` call. See :meth:`render_to` for more
details.
.. method:: get_metrics
| :sl:`Return the glyph metrics for the given text`
| :sg:`get_metrics(text, size=0) -> [(...), ...]`
Returns the glyph metrics for each character in *text*.
The glyph metrics are returned as a list of tuples. Each tuple gives
metrics of a single character glyph. The glyph metrics are:
::
(min_x, max_x, min_y, max_y, horizontal_advance_x, horizontal_advance_y)
The bounding box min_x, max_x, min_y, and max_y values are returned as
grid-fitted pixel coordinates of type int. The advance values are
float values.
The calculations are done using the font's default size in points.
Optionally you may specify another point size with the *size* argument.
The metrics are adjusted for the current rotation, strong, and oblique
settings.
If text is a char (byte) string, then its encoding is assumed to be
``LATIN1``.
.. attribute:: height
| :sl:`The unscaled height of the font in font units`
| :sg:`height -> int`
Read only. Gets the height of the font. This is the average value of all
glyphs in the font.
.. attribute:: ascender
| :sl:`The unscaled ascent of the font in font units`
| :sg:`ascender -> int`
Read only. Return the number of units from the font's baseline to
the top of the bounding box.
.. attribute:: descender
| :sl:`The unscaled descent of the font in font units`
| :sg:`descender -> int`
Read only. Return the height in font units for the font descent.
The descent is the number of units from the font's baseline to the
bottom of the bounding box.
.. method:: get_sized_ascender
| :sl:`The scaled ascent of the font in pixels`
| :sg:`get_sized_ascender(<size>=0) -> int`
Return the number of units from the font's baseline to the top of the
bounding box. It is not adjusted for strong or rotation.
.. method:: get_sized_descender
| :sl:`The scaled descent of the font in pixels`
| :sg:`get_sized_descender(<size>=0) -> int`
Return the number of pixels from the font's baseline to the top of the
bounding box. It is not adjusted for strong or rotation.
.. method:: get_sized_height
| :sl:`The scaled height of the font in pixels`
| :sg:`get_sized_height(<size>=0) -> int`
Returns the height of the font. This is the average value of all
glyphs in the font. It is not adjusted for strong or rotation.
.. method:: get_sized_glyph_height
| :sl:`The scaled bounding box height of the font in pixels`
| :sg:`get_sized_glyph_height(<size>=0) -> int`
Return the glyph bounding box height of the font in pixels.
This is the average value of all glyphs in the font.
It is not adjusted for strong or rotation.
.. method:: get_sizes
| :sl:`return the available sizes of embedded bitmaps`
| :sg:`get_sizes() -> [(int, int, int, float, float), ...]`
| :sg:`get_sizes() -> []`
Returns a list of tuple records, one for each point size
supported. Each tuple containing the point size, the height in pixels,
width in pixels, horizontal ppem (nominal width) in fractional pixels,
and vertical ppem (nominal height) in fractional pixels.
.. method:: render
| :sl:`Return rendered text as a surface`
| :sg:`render(text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> (Surface, Rect)`
Returns a new :class:`Surface <pygame.Surface>`,
with the text rendered to it
in the color given by 'fgcolor'. If no foreground color is given,
the default foreground color, :attr:`fgcolor <Font.fgcolor>` is used.
If ``bgcolor`` is given, the surface
will be filled with this color. When no background color is given,
the surface background is transparent, zero alpha. Normally the returned
surface has a 32 bit pixel size. However, if ``bgcolor`` is ``None``
and anti-aliasing is disabled a monochrome 8 bit colorkey surface,
with colorkey set for the background color, is returned.
The return value is a tuple: the new surface and the bounding
rectangle giving the size and origin of the rendered text.
If an empty string is passed for text then the returned Rect is zero
width and the height of the font.
Optional *fgcolor*, *style*, *rotation*, and *size* arguments override
the default values set for the :class:`Font` instance.
If *text* is a char (byte) string, then its encoding is assumed to be
``LATIN1``.
Optionally, *text* can be ``None``, which will render the text
passed to a previous :meth:`get_rect`, :meth:`render`, :meth:`render_to`,
:meth:`render_raw`, or :meth:`render_raw_to` call.
See :meth:`render_to` for details.
.. method:: render_to
| :sl:`Render text onto an existing surface`
| :sg:`render_to(surf, dest, text, fgcolor=None, bgcolor=None, style=STYLE_DEFAULT, rotation=0, size=0) -> Rect`
Renders the string *text* to the :mod:`pygame.Surface` *surf*,
at position *dest*, a (x, y) surface coordinate pair.
If either x or y is not an integer it is converted to one if possible.
Any sequence where the first two items are x and y positional elements
is accepted, including a :class:`Rect <pygame.Rect>` instance.
As with :meth:`render`,
optional *fgcolor*, *style*, *rotation*, and *size* argument are
available.
If a background color *bgcolor* is given, the text bounding box is
first filled with that color. The text is blitted next.
Both the background fill and text rendering involve full alpha blits.
That is, the alpha values of the foreground, background, and destination
target surface all affect the blit.
The return value is a rectangle giving the size and position of the
rendered text within the surface.
If an empty string is passed for text then the returned
:class:`Rect <pygame.Rect>` is zero width and the height of the font.
The rect will test False.
Optionally, *text* can be set ``None``, which will re-render text
passed to a previous :meth:`render_to`, :meth:`get_rect`, :meth:`render`,
:meth:`render_raw`, or :meth:`render_raw_to` call. Primarily, this
feature is an aid to using :meth:`render_to` in combination with
:meth:`get_rect`. An example: ::
def word_wrap(surf, text, font, color=(0, 0, 0)):
font.origin = True
words = text.split(' ')
width, height = surf.get_size()
line_spacing = font.get_sized_height() + 2
x, y = 0, line_spacing
space = font.get_rect(' ')
for word in words:
bounds = font.get_rect(word)
if x + bounds.width + bounds.x >= width:
x, y = 0, y + line_spacing
if x + bounds.width + bounds.x >= width:
raise ValueError("word too wide for the surface")
if y + bounds.height - bounds.y >= height:
raise ValueError("text to long for the surface")
font.render_to(surf, (x, y), None, color)
x += bounds.width + space.width
return x, y
When :meth:`render_to` is called with the same
font properties:attr:`size`, :attr:`style`, :attr:`strength`,
:attr:`wide`, :attr:`antialiased`, :attr:`vertical`, :attr:`rotation`,
:attr:`kerning`, and :attr:`use_bitmap_strikes`as :meth:`get_rect`,
:meth:`render_to` will use the layout calculated by :meth:`get_rect`.
Otherwise, :meth:`render_to` will recalculate the layout if called
with a text string or one of the above properties has changed
after the :meth:`get_rect` call.
If *text* is a char (byte) string, then its encoding is assumed to be
``LATIN1``.
.. method:: render_raw
| :sl:`Return rendered text as a string of bytes`
| :sg:`render_raw(text, style=STYLE_DEFAULT, rotation=0, size=0, invert=False) -> (bytes, (int, int))`
Like :meth:`render` but with the pixels returned as a byte string
of 8-bit gray-scale values. The foreground color is 255, the
background 0, useful as an alpha mask for a foreground pattern.
.. method:: render_raw_to
| :sl:`Render text into an array of ints`
| :sg:`render_raw_to(array, text, dest=None, style=STYLE_DEFAULT, rotation=0, size=0, invert=False) -> Rect`
Render to an array object exposing an array struct interface. The array
must be two dimensional with integer items. The default *dest* value,
``None``, is equivalent to position (0, 0). See :meth:`render_to`.
As with the other render methods, *text* can be ``None`` to
render a text string passed previously to another method.
The return value is a :func:`pygame.Rect` giving the size and position of
the rendered text.
.. attribute:: style
| :sl:`The font's style flags`
| :sg:`style -> int`
Gets or sets the default style of the Font. This default style will be
used for all text rendering and size calculations unless overridden
specifically a render or :meth:`get_rect` call.
The style value may be a bit-wise OR of one or more of the following
constants:
::
STYLE_NORMAL
STYLE_UNDERLINE
STYLE_OBLIQUE
STYLE_STRONG
STYLE_WIDE
STYLE_DEFAULT
These constants may be found on the FreeType constants module.
Optionally, the default style can be modified or obtained accessing the
individual style attributes (underline, oblique, strong).
The ``STYLE_OBLIQUE`` and ``STYLE_STRONG`` styles are for
scalable fonts only. An attempt to set either for a bitmap font raises
an AttributeError. An attempt to set either for an inactive font,
as returned by ``Font.__new__()``, raises a RuntimeError.
Assigning ``STYLE_DEFAULT`` to the :attr:`style` property leaves
the property unchanged, as this property defines the default.
The :attr:`style` property will never return ``STYLE_DEFAULT``.
.. attribute:: underline
| :sl:`The state of the font's underline style flag`
| :sg:`underline -> bool`
Gets or sets whether the font will be underlined when drawing text. This
default style value will be used for all text rendering and size
calculations unless overridden specifically in a render or
:meth:`get_rect` call, via the 'style' parameter.
.. attribute:: strong
| :sl:`The state of the font's strong style flag`
| :sg:`strong -> bool`
Gets or sets whether the font will be bold when drawing text. This
default style value will be used for all text rendering and size
calculations unless overridden specifically in a render or
:meth:`get_rect` call, via the 'style' parameter.
.. attribute:: oblique
| :sl:`The state of the font's oblique style flag`
| :sg:`oblique -> bool`
Gets or sets whether the font will be rendered as oblique. This
default style value will be used for all text rendering and size
calculations unless overridden specifically in a render or
:meth:`get_rect` call, via the *style* parameter.
The oblique style is only supported for scalable (outline) fonts.
An attempt to set this style on a bitmap font will raise an
AttributeError. If the font object is inactive, as returned by
``Font.__new__()``, setting this property raises a RuntimeError.
.. attribute:: wide
| :sl:`The state of the font's wide style flag`
| :sg:`wide -> bool`
Gets or sets whether the font will be stretched horizontally
when drawing text. It produces a result similar to
:class:`pygame.font.Font`'s bold. This style not available for
rotated text.
.. attribute:: strength
| :sl:`The strength associated with the strong or wide font styles`
| :sg:`strength -> float`
The amount by which a font glyph's size is enlarged for the
strong or wide transformations, as a fraction of the untransformed
size. For the wide style only the horizontal dimension is
increased. For strong text both the horizontal and vertical
dimensions are enlarged. A wide style of strength 0.08333 ( 1/12 ) is
equivalent to the :class:`pygame.font.Font` bold style.
The default is 0.02778 ( 1/36 ).
The strength style is only supported for scalable (outline) fonts.
An attempt to set this property on a bitmap font will raise an
AttributeError. If the font object is inactive, as returned by
``Font.__new__()``, assignment to this property raises a RuntimeError.
.. attribute:: underline_adjustment
| :sl:`Adjustment factor for the underline position`
| :sg:`underline_adjustment -> float`
Gets or sets a factor which, when positive, is multiplied with the
font's underline offset to adjust the underline position. A negative
value turns an underline into a strike-through or overline. It is
multiplied with the ascender. Accepted values range between -2.0 and 2.0
inclusive. A value of 0.5 closely matches Tango underlining. A value of
1.0 mimics :class:`pygame.font.Font` underlining.
.. attribute:: fixed_width
| :sl:`Gets whether the font is fixed-width`
| :sg:`fixed_width -> bool`
Read only. Returns ``True`` if the font contains fixed-width
characters (for example Courier, Bitstream Vera Sans Mono, Andale Mono).
.. attribute:: fixed_sizes
| :sl:`the number of available bitmap sizes for the font`
| :sg:`fixed_sizes -> int`
Read only. Returns the number of point sizes for which the font contains
bitmap character images. If zero then the font is not a bitmap font.
A scalable font may contain pre-rendered point sizes as strikes.
.. attribute:: scalable
| :sl:`Gets whether the font is scalable`
| :sg:`scalable -> bool`
Read only. Returns ``True`` if the font contains outline glyphs.
If so, the point size is not limited to available bitmap sizes.
.. attribute:: use_bitmap_strikes
| :sl:`allow the use of embedded bitmaps in an outline font file`
| :sg:`use_bitmap_strikes -> bool`
Some scalable fonts include embedded bitmaps for particular point
sizes. This property controls whether or not those bitmap strikes
are used. Set it ``False`` to disable the loading of any bitmap
strike. Set it ``True``, the default, to permit bitmap strikes
for a non-rotated render with no style other than :attr:`wide` or
:attr:`underline`. This property is ignored for bitmap fonts.
See also :attr:`fixed_sizes` and :meth:`get_sizes`.
.. attribute:: antialiased
| :sl:`Font anti-aliasing mode`
| :sg:`antialiased -> bool`
Gets or sets the font's anti-aliasing mode. This defaults to
``True`` on all fonts, which are rendered with full 8 bit blending.
Set to ``False`` to do monochrome rendering. This should
provide a small speed gain and reduce cache memory size.
.. attribute:: kerning
| :sl:`Character kerning mode`
| :sg:`kerning -> bool`
Gets or sets the font's kerning mode. This defaults to ``False``
on all fonts, which will be rendered without kerning.
Set to ``True`` to add kerning between character pairs, if supported
by the font, when positioning glyphs.
.. attribute:: vertical
| :sl:`Font vertical mode`
| :sg:`vertical -> bool`
Gets or sets whether the characters are laid out vertically rather
than horizontally. May be useful when rendering Kanji or some other
vertical script.
Set to ``True`` to switch to a vertical text layout. The default
is ``False``, place horizontally.
Note that the :class:`Font` class does not automatically determine
script orientation. Vertical layout must be selected explicitly.
Also note that several font formats (especially bitmap based ones) don't
contain the necessary metrics to draw glyphs vertically, so drawing in
those cases will give unspecified results.
.. attribute:: rotation
| :sl:`text rotation in degrees counterclockwise`
| :sg:`rotation -> int`
Gets or sets the baseline angle of the rendered text. The angle is
represented as integer degrees. The default angle is 0, with horizontal
text rendered along the X-axis, and vertical text along the Y-axis.
A positive value rotates these axes counterclockwise that many degrees.
A negative angle corresponds to a clockwise rotation. The rotation
value is normalized to a value within the range 0 to 359 inclusive
(eg. 390 -> 390 - 360 -> 30, -45 -> 360 + -45 -> 315,
720 -> 720 - (2 * 360) -> 0).
Only scalable (outline) fonts can be rotated. An attempt to change
the rotation of a bitmap font raises an AttributeError.
An attempt to change the rotation of an inactive font instance, as
returned by ``Font.__new__()``, raises a RuntimeError.
.. attribute:: fgcolor
| :sl:`default foreground color`
| :sg:`fgcolor -> Color`
Gets or sets the default glyph rendering color. It is initially opaque
black(0, 0, 0, 255). Applies to :meth:`render` and :meth:`render_to`.
.. attribute:: bgcolor
| :sl:`default background color`
| :sg:`bgcolor -> Color`
Gets or sets the default background rendering color. Initially it is
unset and text will render with a transparent background by default.
Applies to :meth:`render` and :meth:`render_to`.
.. versionadded:: 2.0.0
.. attribute:: origin
| :sl:`Font render to text origin mode`
| :sg:`origin -> bool`
If set ``True``, :meth:`render_to` and :meth:`render_raw_to` will
take the *dest* position to be that of the text origin, as opposed to
the top-left corner of the bounding box. See :meth:`get_rect` for
details.
.. attribute:: pad
| :sl:`padded boundary mode`
| :sg:`pad -> bool`
If set ``True``, then the text boundary rectangle will be inflated
to match that of :class:`font.Font <pygame.font.Font>`.
Otherwise, the boundary rectangle is just large enough for the text.
.. attribute:: ucs4
| :sl:`Enable UCS-4 mode`
| :sg:`ucs4 -> bool`
Gets or sets the decoding of Unicode text. By default, the
freetype module performs UTF-16 surrogate pair decoding on Unicode text.
This allows 32-bit escape sequences ('\Uxxxxxxxx') between 0x10000 and
0x10FFFF to represent their corresponding UTF-32 code points on Python
interpreters built with a UCS-2 Unicode type (on Windows, for instance).
It also means character values within the UTF-16 surrogate area (0xD800
to 0xDFFF) are considered part of a surrogate pair. A malformed surrogate
pair will raise a UnicodeEncodeError. Setting ucs4 ``True`` turns
surrogate pair decoding off, allowing access the full UCS-4 character
range to a Python interpreter built with four-byte Unicode character
support.
.. attribute:: resolution
| :sl:`Pixel resolution in dots per inch`
| :sg:`resolution -> int`
Read only. Gets pixel size used in scaling font glyphs for this
:class:`Font` instance.

Some files were not shown because too many files have changed in this diff Show More