三个分数、大球吃小球、五子棋

本文通过三个实例介绍面向对象编程的应用,包括分数计算类的实现、大球吃小球游戏及五子棋游戏的设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

主要是面向对象的方法,通过三个例子进行
第一个是:计算分数的加减乘除

from math import gcd
class Fraction(object):
    def __init__(self, num, den):
        if den == 0:
            raise ValueError('分母不能为0')
        self._num = num
        self._den = den
        self.normalize()   ## 如果分母为负数 则处理整个分数
        self.simplify()    ## 约分数 

    @property
    def num(self):
        return self._num

    @property
    def den(self):
        return self._den

    def add(self, other):
        return Fraction(self._num * other.den + self._den * other.num,
                        self._den * other.den).simplify().normalize()

    def sub(self, other):
        return Fraction(self._num * other.den - self._den * other.num,
                        self._den * other.den).simplify().normalize()

    def mul(self, other):
        return Fraction(self._num * other.num, self._den * other.den)\
            .simplify().normalize()

    def div(self, other):
        return Fraction(self._num * other.den, self._den * other.num)\
            .simplify().normalize()

    def __add__(self, other):    ## 这是用内置加减乘法运算
        return self.add(other)

    def __sub__(self, other):
        return self.sub(other)

    def __mul__(self, other):
        return self.mul(other)

    def __truediv__(self, other):
        return self.div(other)

    def simplify(self):
        if self._num != 0 and self._den != 1:
            factor = gcd(abs(self._num), abs(self._den))
            if factor > 1:
                self._num //= factor
                self._den //= factor
        return self

    def normalize(self):
        if self._den < 0:
            self._num = -self._num
            self._den = -self._den
        return self

    def __str__(self):
        if self._num == 0:
            return '0'
        elif self._den == 1:
            return str(self._num)
        else:
            return '%d/%d' % (self._num, self._den)


def main():
    f1 = Fraction(3, -6)
    f2 = Fraction(3, 4)
    print(f1)
    print(f2)
    print(f1 + f2)
    print(f1 - f2)
    print(f1 * f2)
    print(f1 / f2)
    print((f1 - f2) * f2)


if __name__ == '__main__':
    main()

结果如下:

-1/2
3/4
1/4
-5/4
-3/8
-2/3
-15/16

第二个程序:大球吃小球

from random import randint

import pygame

class Ball(object):

    def __init__(self, center, color, radius, speed):  
    # 中心点 ,颜色,半径,速度
        self._center = center
        self._color = color
        self._radius = radius
        self._speed = speed

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

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

    def move(self): ## 移动
        x, y = self._center[0], self._center[1]
        sx, sy = self._speed[0], self._speed[1]
        self._center = x, y = x + sx, y + sy
        if x + self._radius >= 800 or x - self._radius <= 0:
            self._speed = -sx, sy
        if y + self._radius >= 600 or y - self._radius <= 0:
            self._speed = sx, -sy



    def draw(self, screen):
        pygame.draw.circle(screen, self._color, self._center,
                           self._radius, 0)

def main():
    balls = []
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption('大球吃小球')
    clock = pygame.time.Clock()
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN \
                    and event.button == 1:
                color = random_color()
                radius = randint(10, 100)
                speed = randint(-10, 10), randint(-10, 10)
                ball = Ball(event.pos, color, radius, speed)
                balls.append(ball)
        refresh(screen, balls)
        clock.tick(24)
        for ball in balls:
            ball.move()
    pygame.quit()

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

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

if __name__ == '__main__':
    main()

这个的BUG是四个角落点击出现的 球会出现类似卡住抖动的效果,还需要改进

第三个程序是五子棋:

import pygame

EMPTY = 0
BLACK = 1
WHITE = 2

black_color = [0,0,0]    # 黑棋
white_color = [255, 255,255]   #白棋

class RenjuBoard(object):

    def __init__(self):
        self._board = [[]] * 15
        self.reset()            #  棋盘状态

    def reset(self):
        for row in range(len(self._board)):
            self._board[row] = [EMPTY] * 15    # 清空棋盘


    #走棋
    def move(self,row,col,is_black):
        if self._board[row][col] == EMPTY:
            self._board[row][col] = BLACK if is_black else WHITE
            return True
        return False

    # 画棋盘
    # 传屏幕
    def draw(self,screen):
        for index in range(1, 16):
            pygame.draw.line(screen, black_color,
                             [40, 40 * index], [600, 40 * index], 2)          #  划线   屏幕 起点位置 初始位置 结束位置 线段粗细
            pygame.draw.line(screen, black_color,
                             [40 * index, 40], [40 * index, 600], 2)  
        pygame.draw.rect(screen, black_color, [36, 36, 568, 568], 4)  # 画矩形  左上角起点前两个 后两个宽高
        pygame.draw.circle(screen, black_color, [320, 320], 5, 0)  # 画圆 后面0表示填充
        pygame.draw.circle(screen, black_color, [160, 160], 5, 0)
        pygame.draw.circle(screen, black_color, [480, 480], 5, 0)
        pygame.draw.circle(screen, black_color, [480, 160], 5, 0)
        pygame.draw.circle(screen, black_color, [160, 480], 5, 0)
        for row in range(len(self._board)):
            for col in range(len(self._board[row])):
                if self._board[row][col] != EMPTY:
                    ccolor = black_color \
                        if self._board[row][col] == BLACK else white_color
                    pos = [40 * (col + 1), 40 * (row + 1)]
                    pygame.draw.circle(screen, ccolor, pos, 20, 0)

def main():
    board = RenjuBoard()
    is_black = True
    pygame.init()                                  #  初始化 
    pygame.display.set_caption('五子棋')            #  名字命名
    screen = pygame.display.set_mode([640, 640])   # 桌面大小
    screen.fill([255, 255, 0])                  # 填充
    board.draw(screen)                              # 执行画格子动作
    pygame.display.flip()                      #更新显示到屏幕表面 
    running = True
    while running:
        for event in pygame.event.get():         ## 判断事件
            if event.type == pygame.QUIT:          ## 退出窗口
                running = False                    # 运行结束
            elif event.type == pygame.MOUSEBUTTONDOWN\
                    and event.button == 1:             # 鼠标点击事件
                x,y = event.pos           #  事件发生坐标


                row =round((y - 40)/40)
                col = round((x - 40) / 40)
                if board.move(row,col,is_black):
                    is_black = not is_black      # 检查如果不是白色
                    screen.fill([255,255,0])    # 填充
                    board.draw(screen)        # 执行画格子动作
                    pygame.display.flip()       #更新显示到屏幕表面 
    pygame.quit()                               # 退出


if __name__ == '__main__':
    main()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值