- . , :
import pygame, sys, time
from pygame.locals import *
pygame.init()
WINDOWWIDTH = 480
WINDOWHEIGHT = 800
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Jumper')
LEFT = 4
RIGHT = 6
UP = 8
DOWN = 2
MOVESPEED = 4
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
b1 = {'rect':pygame.Rect(240, 700, 20, 20), 'color':GREEN, 'dir':LEFT}
blocks = [b1]
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
windowSurface.fill(BLACK)
for b in blocks:
if b['dir'] == LEFT:
b['rect'].left -= MOVESPEED
if b['dir'] == RIGHT:
b['rect'].left += MOVESPEED
if b['rect'].left < 0:
b['dir'] = RIGHT
if b['rect'].right > WINDOWWIDTH:
b['dir'] = LEFT
pygame.draw.rect(windowSurface, b['color'], b['rect'])
pygame.display.update()
time.sleep(0.02)
Python , , . # , , , . Python . ( - , .)
, , .
. Inventing With Python - ... , .
, , , . ?
. DOWNLEFT, DOWNRIGHT, UPLEFT, UPRIGHT , , .
, , , : " ?"
, - .
, , , , .
, DOWNLEFT .. ? ? , .
, , : .
, /? , x y. , x=0, y=0, , , , , .
, ! DOWNRIGHT x=1, y=1, UPLEFT x=-1, y=-1 ..
. , (if b['rect'].left < 0). , DOWNLEFT DOWNRIGHT UPLEFT UPRIGHT, y x=-1 x=1.
, , x=1 x=-1. , x -1.
, : , , x -1. y.
, , :
import pygame, sys, time
from pygame.locals import *
class Block( object ):
def __init__( self, rect, color, dir ):
self.rect = rect
self.color = color
self.dir = dir
def move( self ):
if self.rect.left < SPEED or self.rect.right > WIN_WIDTH - SPEED:
self.dir.x *= -1
if self.rect.top < SPEED or self.rect.bottom > WIN_HEIGHT - SPEED:
self.dir.y *= -1
self.rect.left += self.dir.x * SPEED
self.rect.top += self.dir.y * SPEED
def draw( self ):
pygame.draw.rect( windowSurface, self.color, self.rect )
class Direction( object ):
def __init__( self, x, y ):
self.x = x
self.y = y
pygame.init()
WIN_WIDTH = 400
WIN_HEIGHT = 400
windowSurface = pygame.display.set_mode( ( WIN_WIDTH, WIN_HEIGHT ), 0, 32 )
pygame.display.set_caption( 'Animation' )
SPEED = 4
BLACK = ( 0, 0, 0 )
RED = ( 255, 0, 0 )
GREEN = ( 0, 255, 0 )
BLUE = ( 0, 0, 255 )
blocks = [
Block( pygame.Rect( 300, 80, 50, 100 ), RED, Direction( -1, 1 ) ),
Block( pygame.Rect( 200, 200, 20, 20 ), GREEN, Direction( -1, -1 ) ),
Block( pygame.Rect( 100, 150, 60, 60 ), BLUE, Direction( 1, -1 ) ),
]
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
windowSurface.fill( BLACK )
for block in blocks:
block.move()
block.draw()
pygame.display.update()
time.sleep( 0.02 )
, . , " " .
#. Python - , __init__() - , . , - .
. , , , . , , if self.rect.left < SPEED if self.rect.left < 0.