您的位置:首页 > 编程语言 > Python开发

我的python学习之路-类对象的创建

2018-03-16 00:45 555 查看
2018.03.15*********************Day17*************************************

author: wills

今天事太多,就给大家写一个大球吃小球的游戏代码。

import pygame
from math import sqrt
import time
from random import randint

class Ball(object):

def __init__(self, center, color, radius, sx, sy):
self._center = center
self._color = color
self._radius = radius
# sx速度x分量,sy速度y分量
self._sx = sx
self._sy = sy

@property
def center(self):
return self._center

@property
def radius(self):
return self._radius

@radius.setter
def radius(self, x):
self._radius = x
return self._radius

def move(self):
x, y = self._center[0], self._center[1]

if x + self._radius >= 950 or \
x - self._radius <= -50:
self._sx = -self._sx
if y + self._radius >= 650 or \
y - self._radius <= -50:
self._sy = -self._sy
x += self._sx
y += self._sy
self._center = (x, y)

def eat(self, other):
if self._radius == 0 or other._radius == 0:
return self
if sqrt((self._center[0] - other._center[0]) ** 2 +
(self._center[1] - other._center[1]) ** 2) < \
self._radius + other._radius:
if self._radius > other._radius:
self._radius += other._radius % 5
other._radius = 0

elif self._radius < other._radius:
other._radius += self._radius % 5
self._radius = 0
return self

def draw(self, screen):
# 最后一个参数 0 表示图形填充,不是0就只有一个边框
pygame.draw.circle(screen, self._color, self._center,
self._radius, 0)

def main():
balls = []
clock = pygame.time.Clock()

pygame.init()
screen = pygame.display.set_mode((900,600))
pygame.display.set_caption('大球吃小球')

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 键盘按键任意键被按下事件触发,执行此分支结构语句
elif event.type == pygame.KEYDOWN or \
event.type == pygame.KEYUP:
# 判断任意两个球的关系,并且让它们互吃
for n in range(len(balls) - 1):
for i, ball in enumerate(balls):
if n != i:
ball.eat(balls
)
# 鼠标被按下事件触发,并且按下的是左键,执行此分支结构语句
elif event.type == pygame.MOUSEBUTTONDOWN and \
event.button == 1:
balls.append(create_ball(event.pos))
# 刷新屏幕
refresh(screen, balls)
clock.tick(20)

# 遍历所有的球,给所有的球发消息,让他们移动
for ball in balls:
ball.move()
# 删除已经被吃掉的球
flag = True
while flag:
flag = False
for n in range(len(balls)):
if balls
.radius == 0:
del balls

flag = True
break

pygame.quit()

def create_ball(pos):
color = random_color()
radius = randint(1, 50)
sx = randint(-10, 10)
sy = randint(-10, 10)
return Ball(pos, color, radius, sx, sy)

def random_color():
red = randint(0,255)
green = randint(0, 255)
blue = randint(0, 255)
return red, green, blue

def refresh(screen, balls):
bg_color = (166, 166, 188)
screen.fill(bg_color)
for ball in balls:
ball.draw(screen)
pygame.display.flip()

if __name__ == '__main__':
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python