day13_python_pygame(老師例題)

球球大作戰(zhàn)

import pygame
import color
from random import randint
"""
游戲功能:點擊鼠標(biāo)生成一個球,球不能出邊界,大球吃小球

第一步:搭建游戲窗口
第二不:點擊屏幕產(chǎn)生球
第三步:讓球動起來(需要用列表來保存球,字典保存每個球的信息)
第四部:
"""


# 全局變量
Window_WIDTH = 800 # 屏幕寬度
Window_HEIGHT = 800 # 屏幕高度

key_ball_color = 'ball_color'
key_ball_center = 'ball_center'
key_ball_radius = 'ball_radius'
key_ball_xspeed = 'ball_xspeed'
key_ball_yspeed = 'ball_yspeed'
key_ball_alive = 'ball_alive'

all_ball = [] # 保存所有的球


def ball_move():
    """
    球動起來
    :return:
    """
    for ball in all_ball:
        ball_x,ball_y = ball[key_ball_center]
        new_x = ball_x + ball[key_ball_xspeed]
        new_y = ball_y + ball[key_ball_yspeed]

        if new_x <= ball[key_ball_radius]:
            ball[key_ball_xspeed] *= -1
            new_x = ball[key_ball_radius]
        if new_x >= Window_WIDTH - ball[key_ball_radius]:
            ball[key_ball_xspeed] *= -1
            new_x = Window_WIDTH - ball[key_ball_radius]
        if new_y <= ball[key_ball_radius]:
            ball[key_ball_yspeed] *= -1
            new_y = ball[key_ball_radius]
        if new_y >= Window_HEIGHT - ball[key_ball_radius]:
            ball[key_ball_yspeed] *= -1
            new_y = Window_HEIGHT - ball[key_ball_radius]
        ball[key_ball_center] = new_x,new_y


def draw_all_ball(window):
    for ball in all_ball[:]:
        if ball[key_ball_alive]:
            pygame.draw.circle(window,ball[key_ball_color],ball[key_ball_center],ball[key_ball_radius])
        else:
            all_ball.remove(ball)
    pygame.display.update()


def create_ball(window,pos):
    """
    # 在指定的位置產(chǎn)生一個隨機(jī)的球
    :param window:游戲界面
    :param pos:球的產(chǎn)生位置
    :return:
    """
    ball_color = color.rand_color()
    ball_center = pos
    ball_radius = randint(10,30)
    # 創(chuàng)建每個球?qū)?yīng)的字典
    ball = {
        key_ball_color:ball_color,
        key_ball_center:ball_center,
        key_ball_radius:ball_radius,
        key_ball_xspeed:randint(-5,5),
        key_ball_yspeed:randint(-5,5),
        key_ball_alive:True
    }
    # 保存球的信息
    all_ball.append(ball)
    pygame.draw.circle(window,ball_color,ball_center,ball_radius)
    pygame.display.update()


def ball_crash():
    """
    檢查碰撞,看屏幕上的每個球好其他球的圓心距小于等于半徑
    :return:
    """
    # 拿第一個球
    for ball in  all_ball:
        # 拿另一個球
        for other in all_ball:
            if ball == other or not ball[key_ball_alive] or not other[key_ball_alive]:
                continue
            x1,y1 = ball[key_ball_center]
            x2,y2 = other[key_ball_center]
            distance = ((x1-x2)**2 + (y1-y2)**2)**0.5
            if distance <= ball[key_ball_radius] + other[key_ball_radius]:
                if randint(0,1):
                    ball[key_ball_alive] = False
                    ball[key_ball_radius] += other[key_ball_radius]//4
                else:
                    other[key_ball_alive] = False
                    other[key_ball_radius] += ball[key_ball_radius] // 4




def main_game():

    pygame.init()
    window = pygame.display.set_mode((Window_WIDTH,Window_HEIGHT))
    window.fill(color.white)
    pygame.display.flip()
    # 游戲循環(huán)
    while True:
        pygame.time.delay(20)
        window.fill(color.white)
        ball_move()
        draw_all_ball(window)
        ball_crash()
        for event in pygame.event.get():
            # 用type判斷事件的類型
            if event.type == pygame.QUIT:
                exit()  # 退出程序
            # 鼠標(biāo)點擊事件
            if event.type == pygame.MOUSEBUTTONDOWN:
                create_ball(window,event.pos)

if __name__ == '__main__':

    main_game()
作業(yè)系統(tǒng)

字典.get(鍵值,默認(rèn)值):

當(dāng)字典沒有這個值時,會返回默認(rèn)值,get()不支持關(guān)鍵字輸入,不要用關(guān)鍵字
```python
import file_manager
import student_system

#全局變量
all_user_file = 'user_info'
key_user_name = 'username'
key_user_password = 'password'


def get_all_user():
    all_user = file_manager.read_json_file(all_user_file)
    if all_user:
        return all_user
    return []

def is_register(user_name):
    all_user = file_manager.read_json_file(all_user_file)
    if not all_user:
        return False
    for user in all_user:
        if user[key_user_name] == user_name:
            return True
    return False


# ==================注冊==========================
"""
為了下次打開系統(tǒng)是能夠正常登錄,注冊成功的信息需要保存。保存用戶名和密碼
[
    {'user_name':'用戶名','password':'密碼'}
]
保存到all_user_info.json
"""
def register():
    while True:
        user_name = input('請輸入一個用戶名(3-10位):')
        if not 3 <= len(user_name) <= 10:
            print('輸入有誤,請重新輸入!')
            continue
        if is_register(user_name):
            print('{}已經(jīng)注冊過了,請重新輸入!'.format(user_name))
            continue
        print('用戶名可用!')
        break
    while True:
        password = input('請輸入密碼!(6-16位)')
        if not 6 <= len(password) <= 16:
            print('輸入有誤,請重新輸入!')
            continue
        re_password = input('確認(rèn)密碼:')
        if password != re_password:
            print('和第一次輸入的密碼不一樣,請重新輸入!')
            continue
        break
    all_user = get_all_user()
    all_user.append({key_user_name:user_name,key_user_password:password})
    re = file_manager.write_json_file(all_user_file,all_user)
    if re:
        print('注冊成功!')
    else:
        print('注冊失??!')


# ==============登錄=============================
def login():
    user_name = input('請輸入用戶名:')
    password = input('請輸入密碼')
    all_user = get_all_user()
    for user in all_user:
        if user[key_user_name] == user_name:
            if user[key_user_password] == password:
                print('登錄成功!')
                return user_name
            else:
                print('密碼錯誤')
                return None
    print('登錄失??!')
    return None


# ==================主頁==========================
def show_main_page():
    while True:
        print(file_manager.read_text_file('login'))
        value = input('請選擇:')

        if value == '1':
            register()
        elif value == '2':
            user_name = login()
            if user_name:
                student_system.user_name = user_name
                student_system.main_page()
                print('進(jìn)入到學(xué)生管理系統(tǒng)。')
        elif value == '3':
            print('退出成功。')
            break
        else:
            print('輸入有誤,請重新輸入!')



if __name__ == '__main__':
    show_main_page()
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容