Python跳跳兔小游戲源代碼,兔年必玩小游戲,兔年大吉,小兔子跳跳,按空格鍵向上跳躍,按鍵盤(pán)方向鍵進(jìn)行左右移動(dòng),以避開(kāi)飛彈,以防被炸,還可以撿到火箭道具哦。 https://download.csdn.net/download/weixin_42756970/86951518 main.py import pygame as pg import random import os from settings import * from sprites import *
class Game: def __init__(self): pg.init() pg.mixer.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption(TITLE) self.clock = pg.time.Clock() self.running = True # 設(shè)置繪制時(shí)使用的字體 self.font_name = pg.font.match_font(FONT_NAME) self.load_data()
def load_data(self): # 加載數(shù)據(jù) self.dir = os.path.dirname(__file__) filepath = os.path.join(self.dir, HS_FILE) with open(filepath, 'r') as f: try: self.highscore = int(f.read()) except: self.highscore = 0 img_dir = os.path.join(self.dir, 'img') # 加載精靈圖片 self.spritesheet = Spritesheet(os.path.join(img_dir, SPRITESHEET)) # 加載云彩圖片 self.cloud_images = [] for i in range(1, 4): self.cloud_images.append(pg.image.load(os.path.join(img_dir, 'cloud{}.png'.format(i))).convert()) # 加載音樂(lè) self.snd_dir = os.path.join(self.dir, 'snd') # 跳躍時(shí)音效 self.jump_sound = pg.mixer.Sound(os.path.join(self.snd_dir, 'Jump33.wav')) # 使用道具時(shí)音效 self.boost_sound = pg.mixer.Sound(os.path.join(self.snd_dir, 'Boost16.wav'))
def new(self): self.score = 0 # self.all_sprites = pg.sprite.Group() # 層次添加,避免元素重疊顯示(如背景云遮擋住平臺(tái)與玩家) self.all_sprites = pg.sprite.LayeredUpdates() self.platforms = pg.sprite.Group() self.powerups = pg.sprite.Group() # 急速飛躍道具 self.mobs = pg.sprite.Group() # 敵人對(duì)象 self.clouds = pg.sprite.Group() # 云彩對(duì)象 self.player = Player(self) self.all_sprites.add(self.player) for plat in PLATFORM_LIST: p = Platform(self, *plat) # self.all_sprites.add(p) # self.platforms.add(p) self.mob_timer = 0 # 游戲的背景音樂(lè) pg.mixer.music.load(os.path.join(self.snd_dir, 'Happy Tune.ogg')) # 創(chuàng)建云彩 for i in range(8): c = Cloud(self) c.rect.y += 500 self.run()
def run(self): # loops表示循環(huán)次數(shù),-1表示音樂(lè)將無(wú)限播放下去 pg.mixer.music.play(loops=-1) self.playing = True while self.playing: self.clock.tick(FPS) self.events() self.update() self.draw() # 退出后停止音樂(lè),fadeout(time)設(shè)置音樂(lè)淡出的時(shí)間,該方法會(huì)阻塞到音樂(lè)消失 pg.mixer.music.fadeout(500)
def update(self): self.all_sprites.update()
# 產(chǎn)生敵人 now = pg.time.get_ticks() # 通過(guò)時(shí)間間隔來(lái)判斷是否要產(chǎn)生敵人 if now - self.mob_timer > 5000 + random.choice([-1000, -500, 0, 500, 1000]): self.mob_timer = now Mob(self) # 碰撞檢測(cè) - 如果碰撞到了敵人,游戲結(jié)束 mob_hits = pg.sprite.spritecollide(self.player, self.mobs, False, pg.sprite.collide_mask) if mob_hits: self.playing = False
# 玩家在界面中時(shí)(y>0),進(jìn)行碰撞檢測(cè),檢測(cè)玩家是否碰撞到平臺(tái) if self.player.vel.y > 0: hits = pg.sprite.spritecollide(self.player, self.platforms, False)
if hits: lowest = hits[0] for hit in hits: if hit.rect.bottom > lowest.rect.bottom: lowest = hit # 保存最小的值 # 避免平移效果 - 兔子最底部沒(méi)有小于碰撞檢測(cè)中的最小值,則不算跳躍到平臺(tái)上 if self.player.pos.y < lowest.rect.centery: self.player.pos.y = lowest.rect.top self.player.vel.y = 0 self.player.jumping = False # 會(huì)產(chǎn)生平移效果 # if hits: # self.player.pos.y = hits[0].rect.top # self.player.vel.y = 0
# 玩家到達(dá)游戲框 1/4 處時(shí)(注意,游戲框,頭部為0,底部為游戲框長(zhǎng)度,到到游戲框的1/4處,表示已經(jīng)到達(dá)了頂部一部分了) if self.player.rect.top <= HEIGHT / 4: # 玩家位置移動(dòng)(往下移動(dòng)) # self.player.pos.y += abs(self.player.vel.y) self.player.pos.y += max(abs(self.player.vel.y), 2) # 隨機(jī)生成新云朵 if random.randrange(100) < 10: Cloud(self) # 云彩同步移動(dòng) for cloud in self.clouds: cloud.rect.y += max(abs(self.player.vel.y / 2), 2)
# 敵人位置同步往下移動(dòng) for mob in self.mobs: mob.rect.y += max(abs(self.player.vel.y), 2)
# 平臺(tái)在游戲框外時(shí),將其注銷,避免資源浪費(fèi) for plat in self.platforms: # 平臺(tái)移動(dòng)位置(往下移動(dòng),移動(dòng)的距離與玩家相同,這樣玩家才能依舊站立在原本的平臺(tái)上) # plat.rect.y += abs(self.player.vel.y) plat.rect.y += max(abs(self.player.vel.y), 2) if plat.rect.top >= HEIGHT: plat.kill() # 分?jǐn)?shù)增加 - 平臺(tái)銷毀,分?jǐn)?shù)相加 self.score += 10
# 碰撞檢測(cè) - 玩家碰撞到急速飛躍道具 pow_hits = pg.sprite.spritecollide(self.player, self.powerups, True) for pow in pow_hits: # 道具類型 - 不同道具可以實(shí)現(xiàn)不同的效果 if pow.type == 'boost': self.boost_sound.play() # 播放相應(yīng)的音效 self.player.vel.y = -BOOST_POWER # 快遞移動(dòng)的距離 self.player.jumping = False # 此時(shí)不為跳躍狀態(tài)
# 死亡 - 玩家底部大于游戲框高度 if self.player.rect.bottom > HEIGHT: for sprite in self.all_sprites: sprite.rect.y -= max(self.player.vel.y, 10) # 元素底部小于0 - 說(shuō)明在游戲框外面,將其刪除 if sprite.rect.bottom < 0: sprite.kill()
# 平臺(tái)個(gè)數(shù)為0,游戲結(jié)束 if len(self.platforms) == 0: self.playing = False
# 判斷平臺(tái)數(shù),產(chǎn)生新的平臺(tái) while len(self.platforms) < 6: width = random.randrange(50, 100) # 平臺(tái)雖然是隨機(jī)生成的,但會(huì)生成在某一個(gè)范圍內(nèi) p = Platform(self, random.randrange(0, WIDTH - width), random.randrange(-75, -30)) self.platforms.add(p) self.all_sprites.add(p)
# 事件處理 def events(self): for event in pg.event.get(): # 關(guān)閉 if event.type == pg.QUIT: if self.playing: self.playing = False self.running = False # 跳躍 if event.type == pg.KEYDOWN: if event.key == pg.K_SPACE: self.player.jump() # 按鈕抬起,減小跳躍速度,從而實(shí)現(xiàn),快速點(diǎn)擊,短跳,長(zhǎng)按,長(zhǎng)跳的效果 if event.type == pg.KEYUP: if event.key == pg.K_SPACE: self.player.jump_cut()
def draw(self): # 繪制 self.screen.fill(BGCOLOR) self.all_sprites.draw(self.screen) # 繪制文字 - 具體的分?jǐn)?shù) self.draw_text(str(self.score), 22, WHITE, WIDTH / 2, 15) # 翻轉(zhuǎn) pg.display.flip()
# 開(kāi)始游戲的鉤子函數(shù) def show_start_screen(self): pg.mixer.music.load(os.path.join(self.snd_dir, 'Yippee.ogg')) pg.mixer.music.play(loops=-1)
self.screen.fill(BGCOLOR) # 填充顏色 # 繪制文字 self.draw_text(TITLE, 48, WHITE, WIDTH / 2, HEIGHT / 4) self.draw_text('Left and right button move, space bar jump', 22, WHITE, WIDTH / 2, HEIGHT / 2) self.draw_text('Press any key to start the game', 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4) # 畫(huà)布翻轉(zhuǎn) pg.display.flip() self.wait_for_key() # 等待用戶敲擊鍵盤(pán)中的仍以位置 pg.mixer.music.fadeout(500)
def wait_for_key(self): waiting = True while waiting: self.clock.tick(FPS) for event in pg.event.get(): if event.type == pg.QUIT: # 點(diǎn)擊退出,結(jié)束等待循環(huán) waiting = False self.running = False if event.type == pg.KEYUP: # 按下鍵盤(pán),結(jié)束等待循環(huán) waiting = False
def show_go_screen(self): # game over/continue if not self.running: # 是否在運(yùn)行 return
pg.mixer.music.load(os.path.join(self.snd_dir, 'Yippee.ogg')) pg.mixer.music.play(loops=-1) self.screen.fill(BGCOLOR) # 游戲框背景顏色填充 # 繪制文字 self.draw_text('GAME OVER', 48, WHITE, WIDTH / 2, HEIGHT / 4) self.draw_text('Score: ' + str(self.score), 22, WHITE, WIDTH / 2, HEIGHT / 2) self.draw_text('Press a key to play again', 22, WHITE, WIDTH / 2, HEIGHT * 3 / 4) # 判斷分?jǐn)?shù) if self.score > self.highscore: self.highscore = self.score self.draw_text('NEW HIGH SCORE!', 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40) # 記錄新的最高分到文件中 - 持久化 with open(os.path.join(self.dir, HS_FILE), 'w') as f: f.write(str(self.score)) else: self.draw_text('High Score: ' + str(self.highscore), 22, WHITE, WIDTH / 2, HEIGHT / 2 + 40) # 翻轉(zhuǎn) pg.display.flip() # 等待敲擊任意鍵, self.wait_for_key() pg.mixer.music.fadeout(500)
# 繪制文字 def draw_text(self, text, size, color, x, y): font = pg.font.Font(self.font_name, size) # 設(shè)置字體與大小 text_surface = font.render(text, True, color) # 設(shè)置顏色 text_rect = text_surface.get_rect() # 獲得字體對(duì)象 text_rect.midtop = (x, y) # 定義位置 self.screen.blit(text_surface, text_rect) # 在屏幕中繪制字體
g = Game() g.show_start_screen() while g.running: g.new() g.show_go_screen()
pg.quit()
|
|
來(lái)自: 學(xué)習(xí)筆記分享 > 《源碼分享》