This section implements a small ball program that moves freely in the window. It provides detailed comments and does not need to be explained.
Code:
[Python]
#-*-Coding: UTF-8 -*-
Import sys
Import pygame
From pygame. locals import *
Def play_ball ():
Pygame. init ()
# Window size
Windows size = (width, height) = (700,500)
# Offset of the ball running [horizontal, vertical]. The larger the value, the faster the movement.
Speed = [1, 1]
# Window background color RGB values
Color_black = (0, 0,139)
# Set window mode
Screen = pygame. display. set_mode (window_size)
# Set the window title
Pygame. display. set_caption ('moving ball ')
# Loading small ball Images
Ball_image = pygame.image.load('ball.gif ')
# Obtain the opening area of a small ball Image
Ball_rect = ball_image.get_rect ()
While True:
# Exit event processing
For event in pygame. event. get ():
If event. type = pygame. QUIT:
Pygame. quit ()
Sys. exit ()
# Make the ball move, and the speed is controlled by the speed variable
Ball_rect = ball_rect.move (speed)
# Reset the offset when the ball moves out of the window
If (ball_rect.left <0) or (ball_rect.right> width ):
Speed [0] =-speed [0]
If (ball_rect.top <0) or (ball_rect.bottom> height ):
Speed [1] =-speed [1]
# Filling the window background
Screen. fill (color_black)
# Draw a ball on the background Surface
Screen. Bits (ball_image, ball_rect)
# Update window content
Pygame. display. update ()
If _ name _ = '_ main __':
Play_ball ()
#-*-Coding: UTF-8 -*-
Import sys
Import pygame
From pygame. locals import *
Def play_ball ():
Pygame. init ()
# Window size
Windows size = (width, height) = (700,500)
# Offset of the ball running [horizontal, vertical]. The larger the value, the faster the movement.
Speed = [1, 1]
# Window background color RGB values
Color_black = (0, 0,139)
# Set window mode
Screen = pygame. display. set_mode (window_size)
# Set the window title
Pygame. display. set_caption ('moving ball ')
# Loading small ball Images
Ball_image = pygame.image.load('ball.gif ')
# Obtain the opening area of a small ball Image
Ball_rect = ball_image.get_rect ()
While True:
# Exit event processing
For event in pygame. event. get ():
If event. type = pygame. QUIT:
Pygame. quit ()
Sys. exit ()
# Make the ball move, and the speed is controlled by the speed variable
Ball_rect = ball_rect.move (speed)
# Reset the offset when the ball moves out of the window
If (ball_rect.left <0) or (ball_rect.right> width ):
Speed [0] =-speed [0]
If (ball_rect.top <0) or (ball_rect.bottom> height ):
Speed [1] =-speed [1]
# Fill in the window background www.2cto.com
Screen. fill (color_black)
# Draw a ball on the background Surface
Screen. Bits (ball_image, ball_rect)
# Update window content
Pygame. display. update ()
If _ name _ = '_ main __':
Play_ball ()
Test:
Animation program, capture several pictures at different times.
1,
2,
3,
From Socrates Column