import pygame
import random
WIDTH = 800
HEIGHT = 600
WHITE = ( 255 , 255 , 255 )
BLACK = ( 0 , 0 , 0 )
RED = ( 255 , 0 , 0 )
GREEN = ( 0 , 255 , 0 )
BLUE = ( 0 , 0 , 255 )
class Ball : def __init__ ( self) : self. radius = 10 self. speed = [ random. randint( 2 , 4 ) , random. randint( 2 , 4 ) ] self. color = REDself. rect = pygame. Rect( 400 , 300 , self. radius * 2 , self. radius * 2 ) def move ( self) : self. rect. move_ip( self. speed[ 0 ] , self. speed[ 1 ] ) if self. rect. left <= 0 or self. rect. right >= WIDTH: self. speed[ 0 ] = - self. speed[ 0 ] if self. rect. top <= 0 or self. rect. bottom >= HEIGHT: self. speed[ 1 ] = - self. speed[ 1 ] def draw ( self, screen) : pygame. draw. circle( screen, self. color, self. rect. center, self. radius)
pygame. init( )
screen = pygame. display. set_mode( ( WIDTH, HEIGHT) )
pygame. display. set_caption( "壁球小游戏" )
ball = Ball( )
running = True
clock = pygame. time. Clock( ) while running: for event in pygame. event. get( ) : if event. type == pygame. QUIT: running = False ball. move( ) screen. fill( BLACK) ball. draw( screen) pygame. display. flip( ) clock. tick( 60 )
pygame. quit( )