python 下类使用记录小实例
使用pygame显示的碰撞的一个小例子
简单运动
import pygame
import random
SETARTING_BLUE_BLOBS = 10
SETARTING_RED_BLOBS = 3
# 设置边界
WIDTH = 800
HEIGHT = 600
# 设置背景与颜色
WHITH = (255,255,255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
game_display = pygame.display.set_mode((WIDTH,HEIGHT))
# 窗口标题
pygame.display.set_caption("Blob World")
clock = pygame.time.Clock()
# 定义一个Blob类
class Blob:
# 初始化
def __init__(self,color):
self.x = random.randrange(0,WIDTH)
self.y = random.randrange(0,HEIGHT)
self.size = random.randrange(4,8)
self.color = color
#定义行为
def move(self):
self.move_x = random.randrange(-1,2)
self.move_y = random.randrange(-1,2)
self.x += self.move_x
self.y += self.move_y
if self.x < 0: self.x = 0
elif self.x > WIDTH: self.x = WIDTH
if self.y < 0: self.y = 0
elif self.y > HEIGHT: self.y = HEIGHT
# 显示出来
def draw_environment(blob_list):
game_display.fill(WHITH)
for blob_dict in blob_list:
for blob_id in blob_dict:
blob = blob_dict[blob_id]
pygame.draw.circle(game_display,blob.color,[blob.x,blob.y], blob.size)
blob.move()
pygame.display.update()
def main():
# 生成索引的blog, 联合采用enumerate 与 dict
blue_blobs = dict(enumerate([Blob(BLUE) for i in range(SETARTING_BLUE_BLOBS)]))
red_blobs = dict(enumerate([Blob(RED) for i in range(SETARTING_RED_BLOBS)]))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw_environment([blue_blobs,red_blobs])
clock.tick(60)
if __name__ == '__main__':
main()
另一个方面可以将类封装成一个单独的文件供其他人调用,比如这里可以将相关部分封装到blob的类中(独立成一个blob.py文件):
import random
# 定义一个Blob类
class Blob:
# 初始化
def __init__(self,color,x_boundary,y_boundary):
self.x_boundary = x_boundary
self.y_boundary = y_boundary
self.x = random.randrange(0,self.x_boundary)
self.y = random.randrange(0,self.y_boundary)
self.size = random.randrange(4,8)
self.color = color
#定义行为
def move(self):
self.move_x = random.randrange(-1,2)
self.move_y = random.randrange(-1,2)
self.x += self.move_x
self.y += self.move_y
if self.x < 0: self.x = 0
elif self.x > self.x_boundary: self.x = self.x_boundary
if self.y < 0: self.y = 0
elif self.y > self.y_boundary: self.y = self.y_boundary
在其他的 .py 文件中只需要调用即可:
from blob import Blob
关于类的继承
类的继承实现子类继承父类的所有方法,同时可以修改方法以及添加自己独有的方法
import pygame
import random
from blob import Blob
SETARTING_BLUE_BLOBS = 10
SETARTING_RED_BLOBS = 3
# 设置边界
WIDTH = 800
HEIGHT = 600
# 设置背景与颜色
WHITH = (255,255,255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
game_display = pygame.display.set_mode((WIDTH,HEIGHT))
# 窗口标题
pygame.display.set_caption("Blob World")
clock = pygame.time.Clock()
class BlueBlob(Blob):
def __init__(self,color,x_boundary,y_boundary):
super().__init__(color,x_boundary,y_boundary)
self.color = BLUE
def move_fast(self):
self.x += random.randrange(-7,7)
self.y += random.randrange(-7,7)
# 显示出来
def draw_environment(blob_list):
game_display.fill(WHITH)
for blob_dict in blob_list:
for blob_id in blob_dict:
blob = blob_dict[blob_id]
pygame.draw.circle(game_display,blob.color,[blob.x,blob.y], blob.size)
blob.move_fast()
pygame.display.update()
def main():
# 生成索引的blog, 联合采用enumerate 与 dict
blue_blobs = dict(enumerate([BlueBlob(BLUE,WIDTH,HEIGHT) for i in range(SETARTING_BLUE_BLOBS)]))
red_blobs = dict(enumerate([BlueBlob(RED,WIDTH,HEIGHT) for i in range(SETARTING_RED_BLOBS)]))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
draw_environment([blue_blobs,red_blobs])
clock.tick(60)
if __name__ == '__main__':
main()
比如这里写一个继承blob类并且修改其中方法的类。(这里注意继承类中间的super方法的使用)
进一步重载
import pygame
import random
from blob import Blob
import numpy as np
SETARTING_BLUE_BLOBS = 50
SETARTING_RED_BLOBS = 50
SETARTING_GREEN_BLOBS = 50
# 设置边界
WIDTH = 800
HEIGHT = 600
# 设置背景与颜色
WHITH = (255,255,255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
game_display = pygame.display.set_mode((WIDTH,HEIGHT))
# 窗口标题
pygame.display.set_caption("Blob World")
clock = pygame.time.Clock()
class BlueBlob(Blob):
def __init__(self,color,x_boundary,y_boundary):
Blob.__init__(self, (0,0,255), x_boundary, y_boundary)
def __add__(self,other_blob):
if other_blob.color == (255, 0, 0):
self.size -= other_blob.size
other_blob.size -= self.size
elif other_blob.color == (0,255,0):
self.size += other_blob.size
other_blob.size = 0
elif other_blob.color == (0,0,255):
pass
else:
raise Exception('Tried to combine one or other blobs')
class RedBlob(Blob):
def __init__(self,color,x_boundary,y_boundary):
Blob.__init__(self, (255,0,0), x_boundary, y_boundary)
class GreenBlob(Blob):
def __init__(self,color,x_boundary,y_boundary):
Blob.__init__(self, (0,255,0), x_boundary, y_boundary)
def is_touching(b1,b2):
return np.linalg.norm(np.array([b1.x,b1.y]) - np.array([b2.x,b2.y])) < (b1.size + b2.size)
def handle_collision(blob_list):
blues,reds,greens = blob_list
for blue_id, blue_blob in blues.copy().items():
for other_blobs in blues,reds,greens:
for other_blob_id, other_blob in other_blobs.copy().items():
if blue_blob == other_blob:
pass
else:
if is_touching(blue_blob,other_blob):
blue_blob + other_blob
if other_blob.size <= 0:
del other_blobs[other_blob_id]
if blue_blob.size <= 0 :
del blues[blue_id]
return blues, reds, greens
# 显示出来
def draw_environment(blob_list):
game_display.fill(WHITH)
blues, reds, greens = handle_collision(blob_list)
for blob_dict in blob_list:
for blob_id in blob_dict:
blob = blob_dict[blob_id]
pygame.draw.circle(game_display,blob.color,[blob.x,blob.y], blob.size)
blob.move()
blob.check_bounds()
pygame.display.update()
return blues, reds, greens
def main():
# 生成索引的blog, 联合采用enumerate 与 dict
blue_blobs = dict(enumerate([BlueBlob(BLUE,WIDTH,HEIGHT) for i in range(SETARTING_BLUE_BLOBS)]))
red_blobs = dict(enumerate([RedBlob(RED,WIDTH,HEIGHT) for i in range(SETARTING_RED_BLOBS)]))
green_blobs = dict(enumerate([GreenBlob(RED,WIDTH,HEIGHT) for i in range(SETARTING_GREEN_BLOBS)]))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
blues, reds, greens = draw_environment([blue_blobs,red_blobs,green_blobs])
clock.tick(60)
if __name__ == '__main__':
main()
关于错误的处理
两种方式:可以采用logging 或者一般的try - except 方法:
try - except 方法
import sys
import logging
def error_handling():
return 'Error: {}. {}, line: {}'.format(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2].tb_lineno)
try:
a+b
except Exception as e:
print('Error: {}. {}, line: {}'.format(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2].tb_lineno))
>>> ERROR:root:Error: <class 'NameError'>. name 'a' is not defined, line: 33
logging
import sys
import logging
def error_handling():
return 'Error: {}. {}, line: {}'.format(sys.exc_info()[0],
sys.exc_info()[1],
sys.exc_info()[2].tb_lineno)
try:
a+b
except Exception as e:
logging.error(error_handling())
>>> ERROR:root:Error: <class 'NameError'>. name 'a' is not defined, line: 33
关于自适应处理参数方法: args 和 kwargs
关于args,自适应改变参数个数,单*,一个例子
blog_1 = 'I am so awesome.'
blog_2 = 'Cars are cool.'
blog_3 = 'Aww look at my cat!'
def blog_posts(*args):
for post in args:
print(post)
blog_posts(blog_1)
blog_posts(blog_1,blog_2)
blog_posts(blog_1,blog_2,blog_3)
>>>
I am so awesome.
I am so awesome.
Cars are cool.
I am so awesome.
Cars are cool.
Aww look at my cat!
kwargs 在调用的时候指定,双**
def blog_posts_3(**kwargs):
for title, post in kwargs.items():
print(title,post)
blog_posts_3(blog_1 = 'I am so awesome',
blog_2 = 'Cars are cool.',
blog_3 = 'Aww look at my cat.')
>>>
blog_2 Cars are cool.
blog_1 I am so awesome
blog_3 Aww look at my cat.