美文网首页
day16 2D小游戏开发

day16 2D小游戏开发

作者: 我去买个橘子o | 来源:发表于2019-03-26 09:28 被阅读0次

1. 小球碰撞

#tool.py
from random import randint


class Color:
    """颜色类"""

    red = (255, 0, 0)
    greed = (0, 255, 0)
    white = (255, 255, 255)
    black = (0, 0, 0)

    # def __init__(self, r, g, b):
    #     self.r = r
    #     self.g = g
    #     self.b = b
    @staticmethod
    def RGB(r, g, b):
        return r, g, b


    @staticmethod
    def random_color():
        return randint(0, 255), randint(0, 255), randint(0, 255)
import pygame
from random import randint


class Ball:
    """球"""
    def __init__(self, x, y, r, color, x_speed, y_speed):
        self.x = x  #球的x坐标
        self.y = y  #球的y坐标
        self.r = r  #球的半径
        self.color = color  #球的颜色
        self.x_speed = x_speed  #球的横向移动速度
        self.y_speed = y_speed  #球的纵向移动速度

    def show(self, window):     #球的绘制
        pygame.draw.circle(window, self.color, (self.x, self.y), self.r)

    def move(self, move_range=None):    #球的移动
        """
        让球移动,如果move_range没有赋值就不做边界检测,如果有值就在指定范围内移动
        :param move_range:(width, height)
        :return:
        """
        new_x = self.x + self.x_speed   #更新横坐标
        new_y = self.y + self.y_speed   #更新纵坐标
        self.x, self.y = new_x, new_y
        if move_range:
            if new_x <= self.r or new_x >= move_range[0] - self.r:
                self.x_speed *= -1      #撞到左右边缘后反弹
            if new_y <= self.r or new_y >= move_range[1] - self.r:
                self.y_speed *= -1      #撞到上下边缘后反弹

    def is_crash(self, other):
        """
        判断当前球是否和另外一个球碰撞
        :param other: 另外一个球
        :return: bool, 是否碰撞
        """
        distance = ((self.x - other.x)**2 + (self.y - other.y)**2)**1/2
        return distance <= self.r + other.r

class BallGame:
    """球球游戏类"""
    def __init__(self, window_width=600, window_height=400, name=''):
        self.window_width = window_width    #窗口的宽
        self.window_height = window_height  #窗口的高
        self.name = name    #窗口标题
        self.all_ball = [] #一个空列表保存游戏中所有的小球

    def __creat_ball(self, window):   #创建球的方法
        if len(self.all_ball) == 15:    #设置小球总数上限为15
            return
        #确定球的属性值
        r = randint(30, 80)     #随机半径
        x = randint(r, self.window_width-r) #随机x坐标
        y = randint(r, self.window_height-r)    #随机y坐标
        color = Color.random_color()    #随机颜色
        x_s = randint(-5, 5)    #随机横向移动速度
        y_s = randint(-5, 5)    #随机纵向移动速度
        # 创建球的对象
        ball = Ball(x, y, r, color, x_s, y_s)
        #画球
        ball.show(window)
        #保存小球
        self.all_ball.append(ball)

    def __move_balls(self, window):
        for ball in self.all_ball:
            ball.move(window.get_size())
            ball.show(window=window)

    def __eat_ball(self):
        for ball1 in self.all_ball:
            for ball2 in self.all_ball:
                if ball1 == ball2:
                    continue

                if ball1.is_crash(ball2):
                    if randint(0, 1) == 0:
                        ball1.r += int(ball2.r * 0.5)
                        self.all_ball.remove(ball2)
                    else:
                        ball2.r += int(ball1.r * 0.5)
                        self.all_ball.remove(ball1)
                    break


    def game_start(self):
        pygame.init()   #初始化
        window = pygame.display.set_mode((self.window_width, self.window_height))  #创建窗口
        pygame.display.set_caption(self.name)   #设置游戏标题
        window.fill(Color.white)    #设置背景颜色
        pygame.display.flip()

        flag = True
        num = 0
        while flag:
            num += 1
            #每隔一段时间产生一个球
            if num % 2000 == 0:
                num = 0
                self.__creat_ball(window)
                pygame.display.update()
            #让球动起来
            if num % 200 == 0:
                window.fill(Color.white)
                self.__move_balls(window)
                pygame.display.update()

            #3.吃球
            self.__eat_ball()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit()





def main():
    game = BallGame(600, 400, 'BallGame')
    game.game_start()



if __name__ == '__main__':
    main()


2. 坦克大战

from random import randint


class Color:
    """颜色类"""

    red = (255, 0, 0)
    greed = (0, 255, 0)
    white = (255, 255, 255)
    black = (0, 0, 0)

    # def __init__(self, r, g, b):
    #     self.r = r
    #     self.g = g
    #     self.b = b
    @staticmethod
    def RGB(r, g, b):
        return r, g, b


    @staticmethod
    def random_color():
        return randint(0, 255), randint(0, 255), randint(0, 255)
"""__author__ = 余婷"""
import pygame
from tool import Color


class Direction:
    Left = 276
    Right = 275
    Up = 273
    Down = 274


# 想要通过键盘控制塔克移动,移动前需要保存原来的坦克的坐标、方向  --> 一个变量保存多个数据,这多个数据需要区分
#  --> 需要字典   -->  面向对象编程,字典用对象代替  --> 想要有对象,先有类
class Tank:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self._direction = Direction.Up
        self.image = './files/p1tankU.gif'
        self.x_speed = 0
        self.y_speed = -3

    @property
    def direction(self):
        return self._direction

    @direction.setter
    def direction(self, x):
        self._direction = x
        if x == Direction.Down:
            self.image = './files/p1tankD.gif'
            self.x_speed = 0
            self.y_speed = 3
        elif x == Direction.Up:
            self.image = './files/p1tankU.gif'
            self.x_speed = 0
            self.y_speed = -3
        elif x == Direction.Left:
            self.image = './files/p1tankL.gif'
            self.x_speed = -3
            self.y_speed = 0
        elif x == Direction.Right:
            self.image = './files/p1tankR.gif'
            self.x_speed = 3
            self.y_speed = 0

    def show(self, window):
        image = pygame.image.load(self.image)
        window.blit(image, (self.x, self.y))

    def move(self):
        self.x, self.y = self.x + self.x_speed,  self.y + self.y_speed


def game_start():
    pygame.init()
    window = pygame.display.set_mode((400, 600))
    pygame.display.set_caption('坦克大战')
    window.fill(Color.white)

    # 创建一个静态的坦克
    tank = Tank(200, 400)
    tank.show(window)

    pygame.display.flip()
    flag = True
    is_move = False
    while flag:
        # 坦克
        if is_move:
            tank.move()
            window.fill(Color.white)
            tank.show(window)
            pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                flag = False
            elif event.type == pygame.KEYDOWN:
                if event.key in (Direction.Left, Direction.Right, Direction.Up, Direction.Down):
                    # 键盘按下改变坦克方向
                    tank.direction = event.key
                    window.fill(Color.white)
                    tank.show(window)
                    pygame.display.update()

                    is_move = True
            elif event.type == pygame.KEYUP:
                if event.key in (Direction.Left, Direction.Right, Direction.Up, Direction.Down):
                    is_move = False








def main():
    game_start()


if __name__ == '__main__':
    main()

3. 学生管理系统

class Student:
    def __init__(self, name: str, age: int, tel: str, study_id: str):
        self.name = name
        self.age = age
        self.tel = tel
        self.study_id = study_id

    def __repr__(self):
        return str(self.__dict__)[1:-1]+'\n'


class StudentManager:
    def __init__(self, name: str, max_count: int):
        # 学号生成器
        self.id_creater = (name + str(x).zfill(len(str(max_count))) for x in range(max_count))
        self.all_students = []

    def add_student(self):
        while True:
            # 收集学生信息
            name = input('姓名:')
            age = int(input('年龄:'))
            tel = input('电话:')
            stu_id = next(self.id_creater)
            # 创建学生对象
            stu = Student(name, age, tel, stu_id)
            self.all_students.append(stu)
            print('===添加成功!===')
            print('1.继续\n2.返回')
            value = input('请选择(1-2):')
            if value != '1':
                break

    def find_student(self):
        while True:
            print('1.查看所有学生\n2.按姓名查找学生\n3.按学号查找学生\n4.返回')
            value = input('请选择(1-4):')
            if value == '1':
                # 查看所有
                print(self.all_students)
            elif value == '2':
                # 按姓名查找
                is_find = False
                find_name = input('需要查找的学生姓名:')
                for stu in self.all_students:
                    if stu.name == find_name:
                        is_find = True
                        print(stu)
                if not is_find:
                    print('没有找到该学生!')

            elif value == '3':
                # 3.按学号查找
                find_id = input('请输入需要查找的学生学号:')
                for stu in self.all_students:
                    if stu.study_id == find_id:
                        print(stu)
                        break
                else:
                    print('没有该学生!')
            else:
                break

    def del_student(self):
        while True:
            print('1.按姓名删除\n2.按学号删除\n3.返回')
            value = input('请选择(1-3):')
            if value == '1':
                # 按姓名删除
                del_name = input('请输入要删除的学生的姓名:')
                del_stus = []
                for stu in self.all_students:
                    if stu.name == del_name:
                        del_stus.append(stu)

                for index in range(len(del_stus)):
                    stu = del_stus[index]
                    print(index, stu)

                print('q 返回上一层')
                value = input('请输入要删除的学生对应的标号(q是退出):')
                if value == 'q':
                    continue
                else:
                    del_stu = del_stus[int(value)]
                    self.all_students.remove(del_stu)
                    print('删除成功!')

            elif value == '2':
                # 按学号删除
                pass
            else:
                break


    def update_student(self):
        pass

    def show_page(self):
        """展示主页"""
        while True:
            page = """
    ====================================
        🌺🌺欢迎来到千锋学生管理系统🌺🌺
    
        ♥ 1.  添加学生
        ♥ 2.  查看学生
        ♥ 3.  修改学生信息
        ♥ 4.  删除学生
        ♥ 5.  退出
    ======================================
            """
            print(page)
            value = input('请选择(1-5):')
            if value == '1':
                # 添加学生
                self.add_student()
            elif value == '2':
                # 查看学生
                self.find_student()

            elif value == '3':
                # 修改学生信息
                pass
            elif value == '4':
                # 删除学生
                self.del_student()
            else:
                exit()


def main():
    sy = StudentManager('qianfeng', 5000)
    sy.show_page()


if __name__ == '__main__':
    main()

相关文章

网友评论

      本文标题:day16 2D小游戏开发

      本文链接:https://www.haomeiwen.com/subject/clmwvqtx.html