当前位置:编程学习 > 网站相关 >>

Python:pygame游戏编程之旅二(自由移动的小球)

 本节实现一个在窗口中自由运动的小球程序,做了详细注释,不多做解释了。

 代码:


[python]
# -*- coding:utf-8 -*-  
 
import sys 
 
import pygame 
from pygame.locals import * 
 
def play_ball(): 
     
    pygame.init() 
     
    #窗口大小  
    window_size = (width, height) =(700, 500) 
     
    #小球运行偏移量[水平,垂直],值越大,移动越快  
    speed = [1, 1] 
     
    #窗口背景色RGB值  
    color_black = (0, 0, 139) 
     
    #设置窗口模式  
    screen = pygame.display.set_mode(window_size) 
     
    #设置窗口标题  
    pygame.display.set_caption('运动的小球') 
     
    #加载小球图片  
    ball_image = pygame.image.load('ball.gif') 
     
    #获取小球图片的区域开状  
    ball_rect = ball_image.get_rect() 
     
    while True: 
         
        #退出事件处理  
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                pygame.quit() 
                sys.exit() 
         
        #使小球移动,速度由speed变量控制  
        ball_rect = ball_rect.move(speed) 
         
        #当小球运动出窗口时,重新设置偏移量  
        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] 
         
        #填充窗口背景  
        screen.fill(color_black) 
         
        #在背景Surface上绘制 小球  
        screen.blit(ball_image, ball_rect) 
         
        #更新窗口内容  
        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 = (width, height) =(700, 500)
   
    #小球运行偏移量[水平,垂直],值越大,移动越快
    speed = [1, 1]
   
    #窗口背景色RGB值
    color_black = (0, 0, 139)
   
    #设置窗口模式
    screen = pygame.display.set_mode(window_size)
   
    #设置窗口标题
    pygame.display.set_caption('运动的小球')
   
    #加载小球图片
    ball_image = pygame.image.load('ball.gif')
   
    #获取小球图片的区域开状
    ball_rect = ball_image.get_rect()
   
    while True:
       
        #退出事件处理
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
       
        #使小球移动,速度由speed变量控制
        ball_rect = ball_rect.move(speed)
       
        #当小球运动出窗口时,重新设置偏移量
        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]
       
        #填充窗口背景 www.zzzyk.com
        screen.fill(color_black)
       
        #在背景Surface上绘制 小球
        screen.blit(ball_image, ball_rect)
       
        #更新窗口内容
        pygame.display.update()
       
if __name__ == '__main__':
    play_ball()


测试:

  动画程序,抓几张不同时刻的图片。

 
 1、
 
2、

3、

 


摘自  Socrates的专栏
 

补充:Web开发 , Python ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,