溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python?Pygame如何實現(xiàn)水果忍者游戲

發(fā)布時間:2022-02-19 14:26:18 來源:億速云 閱讀:288 作者:小新 欄目:開發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)Python Pygame如何實現(xiàn)水果忍者游戲的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

一、準(zhǔn)備中

1.0 游戲規(guī)則

Python版本的水果忍者小編初始化設(shè)置是玩家3條生命值,切到相應(yīng)的水果相應(yīng)加分,切到易爆物

比如炸彈這些就會相應(yīng)的減少生命值,在生命值內(nèi)可以一直切切切,切的越多分數(shù)越高,相應(yīng)的生命值耗盡即結(jié)束游戲哦!快試試你能得幾分?

哈哈哈,今天也錄制了游戲視頻的,看著視頻更有玩游戲的感覺嘛~

1.1 游戲圖片素材(可修改)

Python?Pygame如何實現(xiàn)水果忍者游戲

Python?Pygame如何實現(xiàn)水果忍者游戲

1.2 游戲字體素材(可修改)

Python?Pygame如何實現(xiàn)水果忍者游戲

二、環(huán)境安裝

本文用的Python3、Pycharm寫的。模塊Pygame、random隨機出現(xiàn)水果以及一些自帶的。

這里模塊安裝命令統(tǒng)一鏡像源豆瓣:

pip install -i https://pypi.douban.com/simple/ +模塊名

三、開始敲代碼

3.0 設(shè)置界面玩家生命值等

player_lives = 3                                                # 生命
score = 0                                                       # 得分
fruits = ['melon', 'orange', 'pomegranate', 'guava', 'bomb']    # 水果和炸彈

3.1 導(dǎo)入模塊

import pygame, sys
import os
import random

3.2 界面背景、字體設(shè)置

background = pygame.image.load('背景圖/02.png')                                  # 背景
font = pygame.font.Font(os.path.join(os.getcwd(), '字體/comic.ttf'), 42)         # 字體
score_text = font.render('Score : ' + str(score), True, (255, 255, 255))    # 得分的字體樣式

3.3 游戲窗口設(shè)置

WIDTH = 800
HEIGHT = 500
FPS = 12                                                # gameDisplay的幀率,1/12秒刷新一次
pygame.init()
pygame.display.set_caption('水果忍者_csdn賬號:顧木子吖')                   # 標(biāo)題
gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))   # 游戲窗口
clock = pygame.time.Clock()

3.4 隨機生成水果的位置與數(shù)據(jù)存放

def generate_random_fruits(fruit):
    fruit_path = "images/" + fruit + ".png"
    data[fruit] = {
        'img': pygame.image.load(fruit_path),
        'x' : random.randint(100,500),          # 水果在x坐標(biāo)軸上的位置
        'y' : 800,
        'speed_x': random.randint(-10,10),      # 水果在x方向時的速度和對角線移動
        'speed_y': random.randint(-80, -60),    # y方向時的速度
        'throw': False,                         # 如果生成水果的位置在gameDisplay之外,將被丟棄
        't': 0,                                 
        'hit': False,
    }
 
    if random.random() >= 0.75:     # 返回在[0.0, 1.0]范圍內(nèi)的下一個隨機浮點數(shù),以保持水果在游戲中的顯示。
        data[fruit]['throw'] = True
    else:
        data[fruit]['throw'] = False

3.5 用一個字典來存放水果的數(shù)據(jù)

data = {}
for fruit in fruits:
    generate_random_fruits(fruit)
 
def hide_cross_lives(x, y):
    gameDisplay.blit(pygame.image.load("images/red_lives.png"), (x, y))

3.6 在屏幕中繪制字體

font_name = pygame.font.match_font('comic.ttf')
def draw_text(display, text, size, x, y):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, WHITE)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    gameDisplay.blit(text_surface, text_rect)

3.7 繪制玩家的生命

def draw_lives(display, x, y, lives, image) :
    for i in range(lives) :
        img = pygame.image.load(image)
        img_rect = img.get_rect()       
        img_rect.x = int(x + 35 * i)    
        img_rect.y = y                  
        display.blit(img, img_rect)

3.8 游戲開始與結(jié)束畫面

def show_gameover_screen():
    gameDisplay.blit(background, (0,0))
    draw_text(gameDisplay, "FRUIT NINJA!", 90, WIDTH / 2, HEIGHT / 4)
    if not game_over :
        draw_text(gameDisplay,"Score : " + str(score), 50, WIDTH / 2, HEIGHT /2)
    draw_text(gameDisplay, "Press any key to start the game", 64, WIDTH / 2, HEIGHT * 3 / 4)
    pygame.display.flip()
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYUP:
                waiting = False

3.9 游戲主循環(huán)

first_round = True
game_over = True        # 超過3個炸彈,終止游戲循環(huán)
game_running = True     # 管理游戲循環(huán)
while game_running :
    if game_over :
        if first_round :
            show_gameover_screen()
            first_round = False
        game_over = False
        player_lives = 3
        draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')
        score = 0
 
    for event in pygame.event.get():
        # 檢查是否關(guān)閉窗口
        if event.type == pygame.QUIT:
            game_running = False
 
    gameDisplay.blit(background, (0, 0))
    gameDisplay.blit(score_text, (0, 0))
    draw_lives(gameDisplay, 690, 5, player_lives, 'images/red_lives.png')
 
    for key, value in data.items():
        if value['throw']:
            value['x'] += value['speed_x']          # x方向上移動水果
            value['y'] += value['speed_y']          # y方向上移動 
            value['speed_y'] += (1 * value['t'])    # 遞增
            value['t'] += 1                         
 
            if value['y'] <= 800:
                gameDisplay.blit(value['img'], (value['x'], value['y']))    # 動態(tài)顯示水果
            else:
                generate_random_fruits(key)
 
            current_position = pygame.mouse.get_pos()   # 獲取鼠標(biāo)的位置,單位為像素
 
            if not value['hit'] and current_position[0] > value['x'] and current_position[0] < value['x']+60 \
                    and current_position[1] > value['y'] and current_position[1] < value['y']+60:
                if key == 'bomb':
                    player_lives -= 1
                    if player_lives == 0:
                        
                        hide_cross_lives(690, 15)
                    elif player_lives == 1 :
                        hide_cross_lives(725, 15)
                    elif player_lives == 2 :
                        hide_cross_lives(760, 15)
                    # 超過3次炸彈,提示游戲結(jié)束,重置窗口
                    if player_lives < 0 :
                        show_gameover_screen()
                        game_over = True
 
                    half_fruit_path = "images/explosion.png"
                else:
                    half_fruit_path = "images/" + "half_" + key + ".png"
 
                value['img'] = pygame.image.load(half_fruit_path)
                value['speed_x'] += 10
                if key != 'bomb' :
                    score += 1
                score_text = font.render('Score : ' + str(score), True, (255, 255, 255))
                value['hit'] = True
        else:
            generate_random_fruits(key)
 
    pygame.display.update()
    clock.tick(FPS)      
                        
 
pygame.quit()

四、游戲展示效果

4.1 Part 1 動態(tài)視頻展示效果如下

視頻鏈接

Python版水果忍者,有趣有趣~

4.2 Part 2 靜態(tài)截圖展示效果如下

(1)游戲進入界面&mdash;&mdash;

Python?Pygame如何實現(xiàn)水果忍者游戲

(2)修改下背景圖進入的界面&mdash;&mdash;這個感覺貌似好看點兒~

Python?Pygame如何實現(xiàn)水果忍者游戲

4.3 Part 3 靜態(tài)進入游戲界面截圖如下

Python?Pygame如何實現(xiàn)水果忍者游戲

Python?Pygame如何實現(xiàn)水果忍者游戲

感謝各位的閱讀!關(guān)于“Python Pygame如何實現(xiàn)水果忍者游戲”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI