GAME PROGRAMMING L LINE by isp11018

VIEWS: 0 PAGES: 13

									               GAME PROGRAMMING L LINE
     These are the “tokens” from the end of each chapter of “Game Programming, the L Line” I’ve
     recombined these charts into one handy document you can print and use as a reference.
     Thanks to Ray for the suggestion.
     Note that some of the examples wrap because the table format does not allow long lines.
     Carriage returns are important in Python, so check in the chapter for syntax if you’re not
     positive where carriage returns belong.
     Originally published as part of “Game Programming – the L Line” Wiley Press 2007. This file
     is meant as a supplement to that book as part of its web site and instructional materials kit.
     For questions, write to Andy Harris: andy@aharrisbooks.net




                                     CHAPTER 1
Command                  Arguments             Description               Example
print value              value: what           Prints something to       print "Hi there"
                         will be               the console. A value
                         printed to the        can be text in quotes
                         screen                or a variable name.

variable =               variable: what        Prompts for a user        username =
raw_input(prompt)        receives the          response (usually text    raw_input("What is your
                         entered value, in     encased in quotes)        name")
                         this case prompt      and stores the
                         (a question to ask    response in a
                         the user)             variable.




                                     CHAPTER 2
Command                    Arguments                 Description            Example
string.upper()             None                      Convert string to      print
                                                     uppercase              userName.upper()
string.lower()             None                      Convert string to      print
                                                        lowercase                 userName.lower()
string.replace(a, b)      a: search text                replace all instances     news.replace(“bad”,
                                                        of a in string with b.    “good”)
                          b: replace text
string.title()            None                          capitalize each word      print
                                                        in string                 headline.title()
float(val)                val: a numeric or             convert val to a          x = float(x)
                          string value to be            floating-point
                          converted                     number
int(val)                  val: a numeric or             convert val to an         x = int(x)
                          string value to be            integer number
                          converted
str(val)                  val: a numeric or             convert val to a          x = str(x)
                          value to be converted         string
range(start, bound,       start: starting value         make a range from         print range(0, 12,
inc)                                                    start to bound - inc      2)
                          bound:upper limit
                          inc: increment
list.append(item)         item: item to add to          add item to end of        inventory.append
                          list                          list
                                                                                  (“snakebite kit”)
list.remove(content)      content: what is to be        Remove elements           inventory.remove(
                          removed (content, not         containing content
                                                                                  “nuclear waste”)
                          index)                        from list
for item in list:         item: element of list         step through list         for beatle in
                                                        placing each              (“John”, “Paul”,
                          list: list of items
                                                        element into item         “George”, “Ringo”):
help(“command”)           command: command,             get help on an            help(“float”)
                          object, or module             object from Python
                          name                          console




                                      CHAPTER 3
Command             Arguments                   Description                    Example

import module       module: module to           Makes a module            import pygame
                    import (pygame)             available to the program.

pygame.init()       <none>                      Initializes pygame     pygame.init()
                                                module and submodules.

pygame.display.s size: a tuple         Sets the screen size and pygame.display.set
et_mode(size)    containing height and mode.                    _size((640, 480)
                 width integers

pygame.display.s caption: the string to         Sets the caption if not in     pygame.display.set
et_caption(capti display in window              full-screen mode.              _caption("hello,
Command             Arguments               Description                 Example

on)                 caption                                             world!")

pygame.Surface(s size: a tuple         Creates a surface of the         background =
ize)             containing height and given size.                      pygame.Surface(scr
                 width integers                                         een.get_size())

surface.convert( surface: a pygame          Converts surface’s          background =
)                Surface object             graphics mode to an         background.convert
                                            efficient system.           ()

surface.fill(col surface: a pygame          Fills in the surface with   background.fill((2
or)              Surface object             the given color.            55, 255, 0))
                    color: a tuple
                    containing red,
                    green, and blue
                    values

surface.get_size surface: a pygame          Returns the size of the     screenSize =
()               Surface object             surface as a tuple.         screen.get_size()

pygame.time.Cloc <none>                     Creates a new Clock         clock =
k()                                         object to control game      pygame.time.Clock(
                                            speed.                      )

clock.tick(frame clock: a pygame            Sets the game’s             clock.tick(30)
rate)            Clock object               maximum speed to the
                                            framerate. Called inside
                    framerate: target
                                            the game loop.
                    game speed in
                    frames per second

pygame.event.get <none>                     Returns a list of events    eventList =
()                                          that have happened in
                                                                        pygame.event.get()
                                            the current frame.

event.type          event: a pygame         Returns the type of event if event.type ==
                    Event object            that occurred.            pygame.QUIT:
                                                                          print "bye!"

surface1.blit(su surface1: image that Draws surface1 onto               screen.blit(box,
rface2,          will be drawn         surface2 at position.            (100, 100))
position)
                 surface2: canvas that
                 surface2 is drawn to
                    position: coordinates
                    on surface2 where
                    surface1’s upper-left
                    corner will be placed

pygame.display.f <none>                     Copies everything on the pygame.display.fli
lip()                                       screen object to the     p()
                                            actual display hardware.

surface.get_heig surface: a pygame          Returns the height of the print
ht()                                                                  screen.get_height(
Command            Arguments            Description                Example

                   Surface object       surface in pixels.         )

surface.get_widt surface: a pygame      Returns the width of the   print
h()              Surface object         surface in pixels.         screen.get_width()




                                     CHAPTER 3
Command            Arguments            Description          Example

if condition:      condition: a         Runs block if        if answer == 42:
    block          comparison or        condition is True.       print "yes!"
                   Boolean expression
                   block: one or more
                   lines of indented
                   code

elif condition:    condition: a         Evaluates another if answer == 42:
    block          comparison or        condition. Always     print "yes"
                   Boolean expression   follows an if     elif answer = 5:
                                        clause.               print "huh?"
                   block: one or more
                   lines of indented
                   code

else:              condition: a         Runs block if      if answer == 42:
    block          comparison or        previous condition     print "yes"
                   Boolean expression   is False.          else:
                                                               print "no"
                   block: one or more
                   lines of indented
                   code

while condition: condition: a           Repeats block as     guess = 99
  block          comparison or          long as condition    while guess != "5":
                 Boolean expression     is evaluated to          guess =
                 block: one or more     True.                raw_input("3 + 2?")
                 lines of indented
                 code

def   fName (p1,   fName: function      Creates a function def sayHi (name):
Command             Arguments               Description           Example

p2, ...):           name                    called fName          print "Hi,", name
    block           p1, p2: parameters.     sending
                    bock: one or more       parameter values. sayHi("Matthew”)
                    lines of indented       Block is evaluated
                    code                    whenever function Hi, Matthew
                                            is called.

return value        value: some value       Returns value to  def add(a, b):
                    that will be returned   the main program.     return a + b
                    to the main program
                    when the function is                          print add(2, 3)
                    called                                        5

"pattern" %         pattern: a string       Creates a new         print "%s is %d years
(values)            containing special      string with the       old and weighs %.2f
                    characters              values                pounds.” % ("Jacob”,
                    values: values to be    interspersed.         4, 46.23)
                    interpolated into the
                    string                                        Jacob is 4 years old
                                                                  and weighs 46.23
                                                                  pounds.




                                    CHAPTER 4
Command             Arguments               Description                  Example

import module       module: module to       Makes a module            import pygame
                    import (pygame)         available to the program.

pygame.init()       <none>                  Initializes pygame     pygame.init()
                                            module and submodules.

pygame.display.s size: a tuple         Sets the screen size and pygame.display.set
et_mode(size)    containing height and mode.                    _size((640, 480)
                 width integers

pygame.display.s caption: the string to     Sets the caption if not in   pygame.display.set
et_caption(capti display in window          full-screen mode.            _caption("hello,
on)              caption                                                 world!")

pygame.Surface(s size: a tuple         Creates a surface of the          background =
ize)             containing height and given size.                       pygame.Surface(scr
                 width integers                                          een.get_size())

surface.convert( surface: a pygame          Converts surface’s           background =
)                Surface object             graphics mode to an          background.convert
                                            efficient system.            ()

surface.fill(col surface: a pygame          Fills in the surface with    background.fill((2
or)
Command             Arguments               Description                Example

                    Surface object          the given color.           55, 255, 0))
                    color: a tuple
                    containing red,
                    green, and blue
                    values

surface.get_size surface: a pygame          Returns the size of the    screenSize =
()               Surface object             surface as a tuple.        screen.get_size()

pygame.time.Cloc <none>                     Creates a new Clock        clock =
k()                                         object to control game     pygame.time.Clock(
                                            speed.                     )

clock.tick(frame clock: a pygame            Sets the game’s            clock.tick(30)
rate)            Clock object               maximum speed to the
                                            framerate. Called inside
                    framerate: target
                                            the game loop.
                    game speed in
                    frames per second

pygame.event.get <none>                     Returns a list of events   eventList =
()                                          that have happened in
                                                                       pygame.event.get()
                                            the current frame.

event.type          event: a pygame         Returns the type of event if event.type ==
                    Event object            that occurred.            pygame.QUIT:
                                                                         print "bye!"

surface1.blit(su surface1: image that Draws surface1 onto              screen.blit(box,
rface2,          will be drawn         surface2 at position.           (100, 100))
position)
                 surface2: canvas that
                 surface2 is drawn to
                    position: coordinates
                    on surface2 where
                    surface1’s upper-left
                    corner will be placed

pygame.display.f <none>                     Copies everything on the pygame.display.fli
lip()                                       screen object to the     p()
                                            actual display hardware.

surface.get_heig surface: a pygame          Returns the height of the print
ht()             Surface object             surface in pixels.        screen.get_height(
                                                                      )

surface.get_widt surface: a pygame          Returns the width of the   print
h()              Surface object             surface in pixels.         screen.get_width()
                                    CHAPTER 5
Command             Arguments                     Description             Example

pygame.draw.line(   Surface: drawing surface      Draws a line on         pygame.draw.line(
Surface,            color: color value            the surface with        background,
color,              start_pos, end_pos:           the given values        (0, 0, 0),
start_pos,          endpoints of line                                     (0, 0),
end_pos, width=1)   width: line width                                     (100, 100),
                                                                          3)

pygame.draw.rect(   Surface: drawing surface      Draws the given         pygame.draw.rect(
Surface,            color: color value            rectangle on the        background,
 color,             Rect: rectangle to draw       surface.                (0, 0, 0),
 Rect,              width: drawing width                                  ((0,0),(100,100)),
                                                  Width value of
 width=0)                                                                 1)
                                                  zero (default) fills
                                                  in the rectangle.

pygame.draw.circl   Surface: drawing surface      Draws the given         pygame.draw.circle
e(Surface,          color: color value            circle on the           (background,
Color,              pos: center of circle         surface.                (0, 0, 0),
pos,                radius: radius of circle                              (100, 100),
                                                  Width value of
radius,             width: drawing width                                  50,
                                                  zero fills in the
width=0)                                                                  1)
                                                  circle.

pygame.draw.ellip   Surface: drawing surface      Draws the largest       pygame.draw.ellips
se(Surface,         color: color value            ellipse that fits in    e(background,
 color,             Rect: bounding rectangle of   the given               (0, 0, 0),
 Rect,              ellipse                       rectangle.              ((0,0),(200,100)),
 width=0)           width: drawing width                                  1)
                                                  Width value of
                                                  zero fills in the
                                                  ellipse.

pygame.draw.arc(S   Surface: drawing surface      Generates an            pygame.draw.arc(
urface,             color: color value            ellipse inside          background,
 color,             Rect: bounding rectangle of   bounding                (0, 0, 0),
 Rect,              ellipse containing arc        rectangle, then         ((0,0),(200,100)),
start_angle,        start_angle: beginning of     uses start_angle        0,
stop_angle,         arc in radians                and stop_angle to       math.pi
 width=1)           stop_angle: end of arc in     determine portion       1)
                    radians                       of arc to draw.
                    width: drawing width          Draws this arc on
                                                  the surface.

pygame.draw.lines   Surface: drawing surface      Uses pointlist to       pointList = (
(Surface,           color: color value            generate a series       (0,0),(0,10),
color,              closed: makes polygon if      of connected lines.     (10,10), (10,0))
closed,             True                          See draw.polygon        pygame.draw.lines(
pointlist,          pointList: tuple of vertex    for a filled polygon.   background,
width=1)            points                                                (0, 0, 0),
                    width: width of line                                  True,
                                                                          pointList,
                                                                          1)

pygame.draw.aalin Surface: drawing surface        Draws lines that        pygame.draw.aaline
Command               Arguments                      Description          Example

e(Surface,            color: color value             appear smoother      (background,
color,                start_pos, end_pos:            but cannot be        (0, 0, 0),
startpos,             endpoints of line              wider than one       (0, 0),
endpos,               blend: if set to 1 (True),     pixel.               (100, 100),
blend=1)              blends drawing color with                           1)
                      background color

pygame.draw.polyg     Surface: drawing surface       Draws a closed       pointList = (
on(Surface,           color: color value             polygon using        (0,0),(0,10),
color, pointList,     closed: makes polygon if       pointList as         (10,10), (10,0))
width =0)             True                           vertices.            pygame.draw.polygo
                      pointList: tuple of vertex                          n(
                      points                                              background,
                      width: width of line                                (0, 0, 0),
                                                                          True,
                                                                          pointList,
                                                                          1)

pygame.mouse.get_ <none>                             Returns the          print
pos()                                                mouse’s position     pygame.mouse.get_p
                                                     as a tuple.          os()

pygame.mouse.get_ <none>                             Returns the button if
pressed()                                            status as a three- pygame.mouse.get_p
                                                     number tuple.      ressed == (0,0,1):
                                                                            print "right
                                                                        button clicked"

pygame.image.load filename: name of image file Returns a surface          face =
(filename)        to load                      containing the             pygame.image.load(
                                               image.                     "face.gif")

pygame.image.save Surface: surface object to   Creates a file             pygame.image.save(
(Surface,         create image from            called filename            background,
filename)         filename: name of image file from Surface.              "myImage.jpg")
                  to save

pygame.font.Font( filename: name of TrueType Generates a font             myFont =
filename,         font (.ttf) file             from a given ,ttf          pygame.font.Font(
size)             size: size of font in pixels file.                      "arial.ttf",
                                                                          20)

pygame.font.SysFo     fontName: the font name        Creates a pygame     myFont =
nt(                   (must be an installed          font based on the    pygame.font.SysFon
fontName,             system font)                   named system         t("Comic Sans MS",
size,                 size: font size                font, if possible.   20)
bold=False,           bold, italic: Booleans for
italic=False)         font style

fontObj.render(       fontObj: a font created with   Returns a surface    myFont.render(
text,                 Font or SysFont commands       with the text        "Hello, World!",
aa,                   aa: antialiasing (0 means      rendered             1,
color,                off, 1 means on)               according to         (0, 0, 0))
background =None)     text: text to render           fontObj.
                      color: foreground color
Command              Arguments                  Description         Example

                     background: background
                     color

event.key            Event: an event object     If a keyboard      if event.key ==
                     key: keycode describing    event occurred,    pygame.K_q:
                     which key was pressed      event.key is used    keepGoing =
                                                to determine which False
                                                key was pressed.

pygame.key.name(k keyCode: a keyboard code      Returns a human-    print
eyCode)           value                         readable name       pygame.key.name(
                                                corresponding to    event.key)
                                                keyCode.




                                      CHAPTER 6
Command              Arguments                  Description         Example

pygame.mixer.Soun filename: a sound file      Loads filename        mySound =
d(filename)       (usually Ogg Vorbis format) into a sound          pygame.mixer.Sound
                  you want to play            object.               (“whee.ogg”)

sound.play(loop)     sound: sound object        Plays sound         mySound.play(-1)
                                                stored in sound
                     loop: extra repetitions,
                                                object.
                     default is zero; -1 is
                     indefinite

sound.stop()         sound: sound object        Stops playing the   mySound.stop()
                                                sound.


sound.set_volume( sound: sound object           Sets the play       mySound.set_volume
level)                                          volume for this     (.5)
                  level:A float between 0
                                                sound.
                  (silent) and 1.0 (maximum)

class             className: name of a class Defines a new      class
className( parent you want to define         class based on the myClass(pygame.spr
Class):                                      parent class.      ite.Sprite):
                  parentClass: class you are
                  inheriting from

self                 <none>                     Within a class      self.rect =
Command               Arguments                  Description          Example

                                                 definition, a        self.image.get_rec
                                                 special name         t()
                                                 referring to the
                                                 current object.

pygame.sprite.Gro sprites: sprites you want to   Creates a group     myGroup =
up(sprites)       add to the group               containing sprites. pygame.sprite.Grou
                                                                     p(sprite1,
                                                                     sprite2)

group.clear(scree group: a sprite group       Clears any sprites      myGroup.clear( scr
n, background)                                that were drawn         een, background)
                  screen: the drawing surface
                                              during the last
                  background: the             frame.
                  background surface

group.update()        group: a sprite group      Calls the update() myGroup.update()
                                                 method of every
                                                 sprite in the group.

group.draw(screen group: a sprite group       Draws each sprite       myGroup.draw( scre
)                                             onto the screen.        en)
                  screen: the drawing surface

group.add(sprites group: a sprite group          Adds one or more     myGroup.add(sprite
)                                                sprites to the       3)
                  sprites: sprites to add to the
                                                 group.
                  group

group.remove(spri group: a sprite group          Removes one or       myGroup.remvoe(spr
tes)                                             more sprites from    ite3)
                  sprites: sprites to remove
                                                 the group.
                  from the group

group.has(sprites group: a sprite group          Checks to see        if
)                                                whether sprites      myGroup.has(sprite
                  sprites: sprites to check
                                                 are in the group.    3):
                                                 (All sprites
                                                                        print “it’s
                                                 mentioned must
                                                                      there”
                                                 be present for the
                                                 method to return
                                                 True.).



group.sprites()       group: a sprite group      Returns a list of    print
                                                 sprites in the       myGroup.sprites()
                                                 group.

rect1.colliderect rect1, rect2: two Rect         Returns True if the if
( rect2)          objects (can be the rect       rects are           car.rect.collidere
                  attributes of sprites)         overlapping.        ct(tree.rect):
                                                                        print “Your
                                                                      insurance just
                                                                      went up”
Command               Arguments                    Description          Example

pygame.sprite.spr sprite: a sprite object          Checks for a        if
itecollide(sprite                                  collision between a pygame.sprite.spri
                  group: a sprite group
, group, kill)                                     sprite and a group. tecollide(car,
                  kill: if True, removes the hit                       trees, False):
                  objects from group
                                                                           print “uh, oh”

surface.set_color surface: a surface (often a      Specifies a color    myImage.set_colork
key(color)        sprite image)                    on the surface to    ey(255, 255, 255)
                                                   treat as.
                      color: color to be changed
                      to transparent




                                     CHAPTER 7
Command                       Arguments                                Description

rect.inflate(x, y)            rect: a pygame.Rect object               Allows you to change the
                                                                       size of a rect. Positive
                              x,y: How much to inflate in each
                                                                       values make the rect
                              direction
                                                                       larger, negative make it
                                                                       smaller. Deflate a sprite’s
                                                                       rect to simulate smaller
                                                                       bounding rectangles.




                                     CHAPTER 8
Command                       Arguments                                Description

A.blit(B, pos, (offset, A: surface to be drawn on                      Extracts a sub-image
size))                  B: surface to extract image from               from one image and
                        pos: surface position at which the             draws it to another. Useful
                        image will be drawn                            when several images are
                        offset: upper-left position of sub-image       stored on the same image
                        size: size of extracted image                  file.

pygame.transform.rotate surface: Surface object (image) to be          Rotates an image the
(Surface, angle)        rotated                                        specified angle and
                        angle: amount of rotation in degrees.          returns a new image.
                        (increasing counterclockwise)

pygame.transform.scale( surface: Surface object (image) to be          Changes an image’s size.
surface, size)          resized                                        Can result in a loss of
                        size: new size of objects in pixels
Command                 Arguments                                Description

                        (width, height)                          detail.




                               CHAPTER 9
Command                 Arguments                                Description

pygame.key.get_pressed( <none>                                   Returns a tuple of
)                                                                Boolean values, one for
                                                                 each key.

pygame.event.pump()     <none>                                   Used if the program has
                                                                 no event.get() call, so as
                                                                 to ensure that event-
                                                                 handling is processed.

math.sin(theta)         Theta: an angle in radians               Performs the sine function
                                                                 on theta.

math.cos(theta)         Theta: an angle in radians               Performs the cosine
                                                                 function on theta.

math.atan2(dy, dx)      dy: the vertical component of a vector   Returns the angle of a
                                                                 triangle with the dx and dy
                        dx: the horizontal component of a
                                                                 component sides. Result
                        vector
                                                                 is in radians.

math.pi                 <none>                                   Returns an approximation
                                                                 of the constant pi:
                                                                 approximately 3.1415927.




                             CHAPTER 10
Command                 Arguments                                Description

Pass                    <none>                                   Does nothing. Typically
                                                                 used to indicate that a
                                                                 method is meant to be
                                                                 overwritten.

def __method            <none>                                   A method name
                                                                 beginning with two
                                                                 underscores defines the
                                                                 method as private. Two
Command   Arguments   Description

                      underscores can also be
                      used to define a private
                      attribute.

								
To top