您好,登錄后才能下訂單哦!
Pygame實(shí)現(xiàn)小球躲避實(shí)例代碼怎么寫,相信很多沒有經(jīng)驗(yàn)的人對(duì)此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
這學(xué)期的Python課,要寫代碼是真的多…
課程實(shí)驗(yàn)一是一個(gè)五子棋,但是發(fā)了代碼。
至于代碼質(zhì)量嘛~ 我直接全部根據(jù)自己劃分的結(jié)構(gòu)改了
這里吐槽下 (真的發(fā)下來的代碼 慘不忍睹 )
我改了快4個(gè)小時(shí) 后面功能不想加了…
這次是自己寫嘛~ 那就寫個(gè)想樣的。
我分為了
run 入口
setting 設(shè)置
main 主邏輯
utils 倉庫
其實(shí)我想的是:全部設(shè)置到頁面上去,但是偷懶~ (期末要去弄績點(diǎn))
直接開始貼代碼
import sys from main import main banner = """ ____ _ _ _____ | __ ) __ _| | | ____|___ ___ | _ \ / _` | | | _| / __|/ __| | |_) | (_| | | | |___\__ \ (__ |____/ \__,_|_|_|_____|___/\___| """ if __name__ == '__main__': print(banner) print("Author: HengYi") print("[*] 簡單:輸入 1") print("[*] 普通:輸入 2") print("[*] 困難:輸入 3") try: num = int(input("請(qǐng)選擇難度:")) if num in [1, 2, 3]: main(num) else: print("無法處理~") sys.exit() except Exception as e: raise Exception("無法處理~")
WIDTH = 900 # 寬 HEIGHT = 600 # 高 SCORE = 0 # 分?jǐn)?shù) TIME = 0 # 時(shí)間 FIRST_STEP = 10 # 到達(dá)第二關(guān)時(shí)間 SECOND_STEP = 20 # 到達(dá)第三關(guān)時(shí)間 FPS = 60 # 刷新率 BG_COLOR = (255, 239, 213) # 背景顏色
# -*- coding: utf-8 -*- import pygame from setting import FIRST_STEP, SECOND_STEP, BG_COLOR, WIDTH, HEIGHT # Note: 根據(jù)難度生成對(duì)應(yīng)的小球 # Time: 2021/12/17 8:35 下午 # Author: HengYi def ballNum(ladderNum, time): index = 0 if FIRST_STEP <= time < SECOND_STEP: index = 1 if SECOND_STEP <= time: index = 2 numMap = [ [2, 3, 5], [3, 5, 6], [4, 6, 7] ] return numMap[ladderNum - 1][index] # Note: 根據(jù)小球個(gè)數(shù)設(shè)置防止誤觸時(shí)間 # Time: 2021/12/17 8:43 下午 # Author: HengYi def protectTime(ballsNum): if ballsNum in [2, 3, 4]: return 1 else: return 2 # Note: 根據(jù)時(shí)間設(shè)置小球大小 # Time: 2021/12/17 8:58 下午 # Author: HengYi def howBigBallIs(ladderNum, time): index = 0 if FIRST_STEP <= time < SECOND_STEP: index = 1 if SECOND_STEP <= time: index = 2 numMap = [ [25, 20, 15], [24, 20, 16], [26, 20, 16] ] return numMap[ladderNum - 1][index] # Note: 根據(jù)時(shí)間難度計(jì)算球體的大小和速度 # Time: 2021/12/17 9:15 下午 # Author: HengYi def judgeDiff(ladderNum, time): index = 0 if FIRST_STEP <= time < SECOND_STEP: index = 1 if SECOND_STEP <= time: index = 2 numMap = [ [(30, 30, 3.5, 3.5), (28, 28, 6, 6), (26, 26, 9, 9)], [(30, 30, 4.5, 4.5), (27, 27, 8, 8), (25, 25, 10, 10)], [(30, 30, 5, 5), (26, 26, 9, 9), (24, 24, 12, 12)] ] return numMap[ladderNum - 1][index] # Note: 創(chuàng)建平臺(tái)窗口 # Time: 2021/12/17 2:58 下午 # Author: HengYi def makeGameBg(width, height): pygame.init() screen = pygame.display.set_mode((width, height)) # 設(shè)置窗口大小 pygame.display.set_caption('小球逃逃逃') # 設(shè)置窗口標(biāo)題 background = pygame.Surface(screen.get_size()) # 填充背景 return screen, background # Note: 添加小球產(chǎn)生的事件 # Time: 2021/12/17 3:06 下午 # Author: HengYi def ballCome(): COME_AGAIN = pygame.USEREVENT pygame.time.set_timer(COME_AGAIN, 1000) return COME_AGAIN # Note: 提示字體 # Time: 2021/12/17 3:11 下午 # Author: HengYi def makeTips(content, size, color, position, screen): font = pygame.font.SysFont('arial', size) text_sf = font.render(content, True, color, BG_COLOR) screen.blit(text_sf, position) # Note: 字體展示 # Time: 2021/12/18 4:20 下午 # Author: HengYi def draw(screen, SCORE, TIME): screen.fill(BG_COLOR) # 防止出現(xiàn)拖影 makeTips('SCORE: ', 30, (34, 139, 34), (5, 40), screen) makeTips('TIME(s): ', 30, (64, 158, 255), (5, 75), screen) makeTips(str(int(SCORE)), 30, (34, 139, 34), (135, 40), screen) makeTips(str(int(TIME)), 30, (64, 158, 255), (135, 75), screen) if TIME in [FIRST_STEP, FIRST_STEP + 1]: makeTips('Ops! LEVEL_2~', 30, (60, 179, 113), (WIDTH / 2 - 30 * 3.5, HEIGHT / 2 - 50), screen) elif TIME in [SECOND_STEP, SECOND_STEP + 1]: makeTips('Congratulations! LEVEL_3', 25, (60, 179, 113), (WIDTH / 2 - 25 * 6.25, HEIGHT / 2 - 50), screen)
# -*- coding: utf-8 -*- import random from setting import * from utils import * class Ball(pygame.sprite.Sprite): def __init__(self, *keys): # 創(chuàng)建球 super().__init__() self.timeSec = 0 w, h, xs, ys = keys[0] self.w = w self.h = h self.xs = xs self.ys = ys x = random.randint(0, WIDTH - self.w) y = random.randint(0, HEIGHT - self.h) self.rect = pygame.Rect(x, y, self.w * 2, self.h * 2) def update(self, screen, *args): # 根據(jù)設(shè)置的速度進(jìn)行運(yùn)動(dòng) self.rect.x += self.xs self.rect.y += self.ys # 當(dāng)遇到墻的時(shí)候進(jìn)行反彈 if self.rect.x > WIDTH - self.w or self.rect.x < 0: self.xs = -self.xs elif self.rect.y > HEIGHT - self.h or self.rect.y < 0: self.ys = -self.ys if self.timeSec <= args[0]: pygame.draw.rect(screen, (100, 149, 237), [self.rect.x, self.rect.y, self.rect.w, self.rect.h], 2) pygame.draw.circle(screen, (255, 0, 0), [self.rect.center[0], self.rect.center[1]], self.w) def timerAdd(self): self.timeSec += 1 return self.timeSec def __del__(self): # 銷毀的時(shí)候 pass class Mouse(pygame.sprite.Sprite): def __init__(self, *keys): super().__init__() self.size = keys[0] # 設(shè)置圓的大小 self.rect = pygame.Rect(WIDTH / 2 - self.size, HEIGHT / 2 - self.size, self.size * 2, self.size * 2) # 實(shí)則是一個(gè)正方形 def update(self, screen, *args): if pygame.mouse.get_focused(): # 如果存在于頁面內(nèi) self.rect.center = pygame.mouse.get_pos() # 限制球不能半身跑到邊框上 if self.rect.x < 0: self.rect.x = 0 elif self.rect.x > WIDTH - self.rect.w: self.rect.x = WIDTH - self.rect.w elif self.rect.y < 0: self.rect.y = 0 elif self.rect.y > HEIGHT - self.rect.h: self.rect.y = HEIGHT - self.rect.h pygame.draw.circle(screen, (255, 0, 0), [self.rect.center[0], self.rect.center[1]], self.size) # 根據(jù)圓心畫圓 def main(ladderNum): # -------------------畫布初始化----------------------- screen, background = makeGameBg(WIDTH, HEIGHT) clock = pygame.time.Clock() comeAgain = ballCome() # -------------------------------------------------- # --------------------對(duì)象存儲(chǔ)------------------------- global TIME, SCORE balls = pygame.sprite.Group(Ball(judgeDiff(ladderNum, TIME))) mouse = Mouse(howBigBallIs(ladderNum, TIME)) mouseObject = pygame.sprite.Group(mouse) # -------------------------------------------------- # ---------------------游戲主程序----------------------- RUNNING = True SHOWINFO = False while True: draw(screen, SCORE, TIME) # 動(dòng)態(tài)添加文字 if SHOWINFO: makeTips('Please Press The Space To Restart', 30, (255, 99, 71), (WIDTH / 2 - 240, HEIGHT / 2 - 50), screen) for each in balls: if pygame.sprite.spritecollide(each, mouseObject, False, collided=None) and each.timeSec > 2: RUNNING = False SHOWINFO = True for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit(0) elif event.type == pygame.KEYDOWN: # 重新開始 if event.key == pygame.K_SPACE: SCORE = 0 TIME = 0 for each in balls.sprites(): balls.remove(each) SHOWINFO = False RUNNING = True elif event.type == comeAgain and RUNNING: # 每秒增加 TIME += 1 ballsNum = ballNum(ladderNum, TIME) diff = judgeDiff(ladderNum, TIME) SCORE += (ballsNum * diff[3]) if TIME in [10, 20]: mouseObject.remove(mouseObject.sprites()[0]) mouseObject.add(Mouse(howBigBallIs(ladderNum, TIME))) if len(balls) < ballsNum: balls.add(Ball(diff)) for each in balls: # 防止誤觸的保護(hù)罩 each.timerAdd() balls.update(screen, protectTime(ballNum(ladderNum, TIME))) mouseObject.update(screen) clock.tick(FPS) pygame.display.update() # 刷新 print('游戲結(jié)束')
把上面4處代碼Copy下來在用run.py
啟動(dòng)
里面設(shè)計(jì)的 如何判斷;如何重來;… (我覺得我的變量名字已經(jīng)夠清楚了????)
看完上述內(nèi)容,你們掌握Pygame實(shí)現(xiàn)小球躲避實(shí)例代碼怎么寫的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。