PlayTheBall游戏制作一
PlayTheBall游戏的功能是:图片中有五个球和五个洞,用鼠标控制球的移动方向,当五个球都移动到洞时,游戏成功。
今天能达到的效果:球随机的显示在背景图上,设计思路:显示背景图 -> 定义球类 -> 随机产生球的位置,运动速度属性 -> 在背景图上显示球类
新学的知识:pygame.sprite.Sprite 类, 官方文档介绍:http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite pygame官方介绍,当把Sprite归为子类时,在添加Sprite到某个组前,一定要调用基本的初始化程序,官方初始化例程:
class Block(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.Surface([width, height])
self.image.fill(color)
# Fetch the rectangle object that has the dimensions of the image
# Update the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect()
本游戏运用到的初始化程序:
class Ball(pygame.sprite.Sprite):
def __init__(self, image, position, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = position
self.speed = speed
该初始化程序重新定义了image,rect,speed等属性
本小结重要程序段分析:
1. 随机生成球的位置及速度,代码如下:
# 随机生成球的位置及速度,并调用Ball方法,添加各个球对象到链表中
for i in range(5):
position = randint(0, width - 100), randint(0, height - 100)
speed = [randint(-10, 10), randint(-10, 10)]
ball = Ball(ball_image, position, speed)
balls.append(ball)
2.显示五个球在背景图上
# 显示五个球
for each in balls:
screen.blit(each.image, each.rect)
完整源代码:
# -*- coding: utf-8 -*-
# @Author: 四叶草
# @Date: 2017-11-08 20:15:55
# @Last Modified by: Administrator
# @Last Modified time: 2017-11-09 11:00:35
# 导入相应的模块
import pygame
import sys
from pygame.locals import *
from random import *
# 定义一个球类
class Ball(pygame.sprite.Sprite):
def __init__(self, image, position, speed):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image).convert_alpha()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = position
self.speed = speed
def main():
# 初始化pygame
pygame.init()
# 设置窗口大小
bg_size = width, height = 1024, 681
screen = pygame.display.set_mode(bg_size)
# 载入图片
ball_image = "gray_ball.png"
bg_image = "background.png"
background = pygame.image.load(bg_image).convert_alpha()
# 设置界面主题
pygame.display.set_caption("Play The Ball - Four Leaf Clover")
# 定义循环标志s
running = True
# 定义球的链表
balls = []
# 创建频率对象
clock = pygame.time.Clock()
# 随机生成球的位置及速度,并调用Ball方法,添加各个球对象到链表中
for i in range(5):
position = randint(0, width - 100), randint(0, height - 100)
speed = [randint(-10, 10), randint(-10, 10)]
ball = Ball(ball_image, position, speed)
balls.append(ball)
# 主循环
while running:
# 寻找关闭窗口事件
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
# 显示背景
screen.blit(background, (0, 0))
# 显示五个球
for each in balls:
screen.blit(each.image, each.rect)
# 刷新缓冲区图像
pygame.display.flip()
# 控制帧率为30帧
clock.tick(30)
# 在本文件中调用main函数
if __name__ == "__main__":
main()