国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

這篇具有很好參考價值的文章主要介紹了【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

前言

嗨嘍,大家好呀~這里是愛看美女的茜茜吶

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

今天給大家分享幾個好玩有趣的小游戲,

既提升了學(xué)習(xí)的興趣,又提升了學(xué)習(xí)效率,告別枯燥的學(xué)習(xí)。

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

代碼軟件:

  • python 3.8: 解釋器

  • pycharm: 代碼編輯器

一、飛機大戰(zhàn)

1. 所需素材

字體

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂
圖片

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

音樂

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

2. 源碼部分

模塊導(dǎo)入

import sys
import cfg
import pygame
from modules import *

游戲界面

def GamingInterface(num_player, screen):
    # 初始化
    pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
    fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
    font = pygame.font.Font(cfg.FONTPATH, 20)
    # 游戲背景圖
    bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']]
    bg_move_dis = 0
    bg_1 = pygame.image.load(bg_imgs[0]).convert()
    bg_2 = pygame.image.load(bg_imgs[1]).convert()
    bg_3 = pygame.image.load(bg_imgs[2]).convert()
    # 玩家, 子彈和小行星精靈組
    player_group = pygame.sprite.Group()
    bullet_group = pygame.sprite.Group()
    asteroid_group = pygame.sprite.Group()
    # 產(chǎn)生小行星的時間間隔
    asteroid_ticks = 90
    for i in range(num_player):
        player_group.add(Ship(i+1, cfg))
    clock = pygame.time.Clock()
    # 分?jǐn)?shù)
    score_1, score_2 = 0, 0
    # 游戲主循環(huán)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        # --玩家一: ↑↓←→控制, j射擊; 玩家二: wsad控制, 空格射擊
        pressed_keys = pygame.key.get_pressed()
        for idx, player in enumerate(player_group):
            direction = None
            if idx == 0:
                if pressed_keys[pygame.K_UP]:
                    direction = 'up'
                elif pressed_keys[pygame.K_DOWN]:
                    direction = 'down'
                elif pressed_keys[pygame.K_LEFT]:
                    direction = 'left'
                elif pressed_keys[pygame.K_RIGHT]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.K_j]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            elif idx == 1:
                if pressed_keys[pygame.K_w]:
                    direction = 'up'
                elif pressed_keys[pygame.K_s]:
                    direction = 'down'
                elif pressed_keys[pygame.K_a]:
                    direction = 'left'
                elif pressed_keys[pygame.K_d]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.K_SPACE]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            if player.cooling_time > 0:
                player.cooling_time -= 1
        if (score_1 + score_2) < 500:
            background = bg_1
        elif (score_1 + score_2) < 1500:
            background = bg_2
        else:
            background = bg_3
        # --向下移動背景圖實現(xiàn)飛船向上移動的效果
        screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
        screen.blit(background, (0, bg_move_dis))
        bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
        # --生成小行星
        if asteroid_ticks == 0:
            asteroid_ticks = 90
            asteroid_group.add(Asteroid(cfg))
        else:
            asteroid_ticks -= 1
        # --畫飛船
        for player in player_group:
            if pygame.sprite.spritecollide(player, asteroid_group, True, None):
                player.explode_step = 1
                explosion_sound.play()
            elif player.explode_step > 0:
                if player.explode_step > 3:
                    player_group.remove(player)
                    if len(player_group) == 0:
                        return
                else:
                    player.explode(screen)
            else:
                player.draw(screen)
        # --畫子彈
        for bullet in bullet_group:
            bullet.move()
            if pygame.sprite.spritecollide(bullet, asteroid_group, True, None):
                bullet_group.remove(bullet)
                if bullet.player_idx == 1:
                    score_1 += 1
                else:
                    score_2 += 1
            else:
                bullet.draw(screen)
        # --畫小行星
        for asteroid in asteroid_group:
            asteroid.move()
            asteroid.rotate()
            asteroid.draw(screen)
        # --顯示分?jǐn)?shù)
        score_1_text = '玩家一得分: %s' % score_1
        score_2_text = '玩家二得分: %s' % score_2
        text_1 = font.render(score_1_text, True, (0, 0, 255))
        text_2 = font.render(score_2_text, True, (255, 0, 0))
        screen.blit(text_1, (2, 5))
        screen.blit(text_2, (2, 35))
        # --屏幕刷新
        pygame.display.update()
        clock.tick(60)

主函數(shù)

def main():
    pygame.init()
    pygame.font.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('飛機大戰(zhàn) —— 九歌')
    num_player = StartInterface(screen, cfg)
    if num_player == 1:
        while True:
            GamingInterface(num_player=1, screen=screen)
            EndInterface(screen, cfg)
    else:
        while True:
            GamingInterface(num_player=2, screen=screen)
            EndInterface(screen, cfg)
3. 效果展示

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

二、打地鼠

素材獲取點擊跳轉(zhuǎn)名片領(lǐng)取

1. 所需素材

字體

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

圖片

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

音樂

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

2. 代碼部分

模塊導(dǎo)入

import cfg
import pygame
import random
from modules.sprites.mole import *
from modules.sprites.hammer import *
from modules.interfaces.endinterface import *
from modules.interfaces.startinterface import *

游戲初始化

def initGame():
	pygame.init()
	pygame.mixer.init()
	screen = pygame.display.set_mode(cfg.SCREENSIZE)
	pygame.display.set_caption('Whac A Mole-青燈教育')
	return screen

主函數(shù)

def main():
    # 初始化
    screen = initGame()
    # 加載背景音樂和其他音效
    pygame.mixer.music.load(cfg.BGM_PATH)
    pygame.mixer.music.play(-1)
    audios = {
        'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
        'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
    }
    # 加載字體
    font = pygame.font.Font(cfg.FONT_PATH, 40)
    # 加載背景圖片
    bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
    # 開始界面
    startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
    # 地鼠改變位置的計時
    hole_pos = random.choice(cfg.HOLE_POSITIONS)
    change_hole_event = pygame.USEREVENT
    pygame.time.set_timer(change_hole_event, 800)
    # 地鼠
    mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
    # 錘子
    hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
    # 時鐘
    clock = pygame.time.Clock()
    # 分?jǐn)?shù)
    your_score = 0
    flag = False
    # 初始時間
    init_time = pygame.time.get_ticks()
    # 游戲主循環(huán)
    while True:
        # --游戲時間為60s
        time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
        # --游戲時間減少, 地鼠變位置速度變快
        if time_remain == 40 and not flag:
            hole_pos = random.choice(cfg.HOLE_POSITIONS)
            mole.reset()
            mole.setPosition(hole_pos)
            pygame.time.set_timer(change_hole_event, 650)
            flag = True
        elif time_remain == 20 and flag:
            hole_pos = random.choice(cfg.HOLE_POSITIONS)
            mole.reset()
            mole.setPosition(hole_pos)
            pygame.time.set_timer(change_hole_event, 500)
            flag = False
        # --倒計時音效
        if time_remain == 10:
            audios['count_down'].play()
        # --游戲結(jié)束
        if time_remain < 0: break
        count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
        # --按鍵檢測
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                hammer.setPosition(pygame.mouse.get_pos())
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    hammer.setHammering()
            elif event.type == change_hole_event:
                hole_pos = random.choice(cfg.HOLE_POSITIONS)
                mole.reset()
                mole.setPosition(hole_pos)
        # --碰撞檢測
        if hammer.is_hammering and not mole.is_hammer:
            is_hammer = pygame.sprite.collide_mask(hammer, mole)
            if is_hammer:
                audios['hammering'].play()
                mole.setBeHammered()
                your_score += 10
        # --分?jǐn)?shù)
        your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
        # --綁定必要的游戲元素到屏幕(注意順序)
        screen.blit(bg_img, (0, 0))
        screen.blit(count_down_text, (875, 8))
        screen.blit(your_score_text, (800, 430))
        mole.draw(screen)
        hammer.draw(screen)
        # --更新
        pygame.display.flip()
        clock.tick(60)
    # 讀取最佳分?jǐn)?shù)(try塊避免第一次游戲無.rec文件)
    try:
        best_score = int(open(cfg.RECORD_PATH).read())
    except:
        best_score = 0
    # 若當(dāng)前分?jǐn)?shù)大于最佳分?jǐn)?shù)則更新最佳分?jǐn)?shù)
    if your_score > best_score:
        f = open(cfg.RECORD_PATH, 'w')
        f.write(str(your_score))
        f.close()
    # 結(jié)束界面
    score_info = {'your_score': your_score, 'best_score': best_score}
    is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
    return is_restart
3. 效果展示

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

三、打乒乓

素材獲取點擊跳轉(zhuǎn)名片領(lǐng)取

1. 所需素材

字體

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

圖片

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

音樂

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

2. 代碼部分
import os
import cfg
import sys
import pygame
import random
from modules import *

游戲初始化

def initGame():
    # 初始化pygame, 設(shè)置展示窗口
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('catch coins —— 九歌')
    # 加載必要的游戲素材
    game_images = {}
    for key, value in cfg.IMAGE_PATHS.items():
        if isinstance(value, list):
            images = []
            for item in value: images.append(pygame.image.load(item))
            game_images[key] = images
        else:
            game_images[key] = pygame.image.load(value)
    game_sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        if key == 'bgm': continue
        game_sounds[key] = pygame.mixer.Sound(value)
    # 返回初始化數(shù)據(jù)
    return screen, game_images, game_sounds

主函數(shù)

def main():
    # 初始化
    screen, game_images, game_sounds = initGame()
    # 播放背景音樂
    pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
    pygame.mixer.music.play(-1, 0.0)
    # 字體加載
    font = pygame.font.Font(cfg.FONT_PATH, 40)
    # 定義hero
    hero = Hero(game_images['hero'], position=(375, 520))
    # 定義食物組
    food_sprites_group = pygame.sprite.Group()
    generate_food_freq = random.randint(10, 20)
    generate_food_count = 0
    # 當(dāng)前分?jǐn)?shù)/歷史最高分
    score = 0
    highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
    # 游戲主循環(huán)
    clock = pygame.time.Clock()
    while True:
        # --填充背景
        screen.fill(0)
        screen.blit(game_images['background'], (0, 0))
        # --倒計時信息
        countdown_text = 'Count down: ' + str((90000 - pygame.time.get_ticks()) // 60000) + ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)
        countdown_text = font.render(countdown_text, True, (0, 0, 0))
        countdown_rect = countdown_text.get_rect()
        countdown_rect.topright = [cfg.SCREENSIZE[0]-30, 5]
        screen.blit(countdown_text, countdown_rect)
        # --按鍵檢測
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
            hero.move(cfg.SCREENSIZE, 'left')
        if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
            hero.move(cfg.SCREENSIZE, 'right')
        # --隨機生成食物
        generate_food_count += 1
        if generate_food_count > generate_food_freq:
            generate_food_freq = random.randint(10, 20)
            generate_food_count = 0
            food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)
            food_sprites_group.add(food)
        # --更新食物
        for food in food_sprites_group:
            if food.update(): food_sprites_group.remove(food)
        # --碰撞檢測
        for food in food_sprites_group:
            if pygame.sprite.collide_mask(food, hero):
                game_sounds['get'].play()
                food_sprites_group.remove(food)
                score += food.score
                if score > highest_score: highest_score = score
        # --畫hero
        hero.draw(screen)
        # --畫食物
        food_sprites_group.draw(screen)
        # --顯示得分
        score_text = f'Score: {score}, Highest: {highest_score}'
        score_text = font.render(score_text, True, (0, 0, 0))
        score_rect = score_text.get_rect()
        score_rect.topleft = [5, 5]
        screen.blit(score_text, score_rect)
        # --判斷游戲是否結(jié)束
        if pygame.time.get_ticks() >= 90000:
            break
        # --更新屏幕
        pygame.display.flip()
        clock.tick(cfg.FPS)
    # 游戲結(jié)束, 記錄最高分并顯示游戲結(jié)束畫面
    fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
    fp.write(str(highest_score))
    fp.close()
    return showEndGameInterface(screen, cfg, score, highest_score)

配置文件

WIDTH = 500
HEIGHT = 500
CURRPATH = os.path.abspath(os.path.dirname(__file__))
RESOURCESDIRPATH = os.path.join(CURRPATH, 'resources')
AUDIOSDIRPATH = os.path.join(RESOURCESDIRPATH, 'audios')
FONTDIRPATH = os.path.join(RESOURCESDIRPATH, 'font')
IMAGESDIRPATH = os.path.join(RESOURCESDIRPATH, 'images')
BALLPICPATH = os.path.join(IMAGESDIRPATH, 'ball.png')
RACKETPICPATH = os.path.join(IMAGESDIRPATH, 'racket.png')
FONTPATH = os.path.join(FONTDIRPATH, 'font.TTF')
GOALSOUNDPATH = os.path.join(AUDIOSDIRPATH, 'goal.wav')
HITSOUNDPATH = os.path.join(AUDIOSDIRPATH, 'hit.wav')
BGMPATH = os.path.join(AUDIOSDIRPATH, 'bgm.mp3')
WHITE = (255, 255, 255)
3. 效果展示

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

四、吃金幣

1. 所需素材

字體

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

圖片

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

音樂

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

2. 代碼部分

導(dǎo)入模塊

import os
import cfg
import sys
import pygame
import random
from modules import *

游戲初始化

def initGame():
    # 初始化pygame, 設(shè)置展示窗口
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('catch coins —— 九歌')
    # 加載必要的游戲素材
    game_images = {}
    for key, value in cfg.IMAGE_PATHS.items():
        if isinstance(value, list):
            images = []
            for item in value: images.append(pygame.image.load(item))
            game_images[key] = images
        else:
            game_images[key] = pygame.image.load(value)
    game_sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        if key == 'bgm': continue
        game_sounds[key] = pygame.mixer.Sound(value)
    # 返回初始化數(shù)據(jù)
    return screen, game_images, game_sounds

主函數(shù)

def main():
    # 初始化
    screen, game_images, game_sounds = initGame()
    # 播放背景音樂
    pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
    pygame.mixer.music.play(-1, 0.0)
    # 字體加載
    font = pygame.font.Font(cfg.FONT_PATH, 40)
    # 定義hero
    hero = Hero(game_images['hero'], position=(375, 520))
    # 定義食物組
    food_sprites_group = pygame.sprite.Group()
    generate_food_freq = random.randint(10, 20)
    generate_food_count = 0
    # 當(dāng)前分?jǐn)?shù)/歷史最高分
    score = 0
    highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
    # 游戲主循環(huán)
    clock = pygame.time.Clock()
    while True:
        # --填充背景
        screen.fill(0)
        screen.blit(game_images['background'], (0, 0))
        # --倒計時信息
        countdown_text = 'Count down: ' + str((90000 - pygame.time.get_ticks()) // 60000) + ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)
        countdown_text = font.render(countdown_text, True, (0, 0, 0))
        countdown_rect = countdown_text.get_rect()
        countdown_rect.topright = [cfg.SCREENSIZE[0]-30, 5]
        screen.blit(countdown_text, countdown_rect)
        # --按鍵檢測
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
            hero.move(cfg.SCREENSIZE, 'left')
        if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
            hero.move(cfg.SCREENSIZE, 'right')
        # --隨機生成食物
        generate_food_count += 1
        if generate_food_count > generate_food_freq:
            generate_food_freq = random.randint(10, 20)
            generate_food_count = 0
            food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)
            food_sprites_group.add(food)
        # --更新食物
        for food in food_sprites_group:
            if food.update(): food_sprites_group.remove(food)
        # --碰撞檢測
        for food in food_sprites_group:
            if pygame.sprite.collide_mask(food, hero):
                game_sounds['get'].play()
                food_sprites_group.remove(food)
                score += food.score
                if score > highest_score: highest_score = score
        # --畫hero
        hero.draw(screen)
        # --畫食物
        food_sprites_group.draw(screen)
        # --顯示得分
        score_text = f'Score: {score}, Highest: {highest_score}'
        score_text = font.render(score_text, True, (0, 0, 0))
        score_rect = score_text.get_rect()
        score_rect.topleft = [5, 5]
        screen.blit(score_text, score_rect)
        # --判斷游戲是否結(jié)束
        if pygame.time.get_ticks() >= 90000:
            break
        # --更新屏幕
        pygame.display.flip()
        clock.tick(cfg.FPS)
    # 游戲結(jié)束, 記錄最高分并顯示游戲結(jié)束畫面
    fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
    fp.write(str(highest_score))
    fp.close()
    return showEndGameInterface(screen, cfg, score, highest_score)
3. 效果展示

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

五、消消樂

1. 所需素材

圖片素材

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂
【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

音頻素材

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

2. 代碼

導(dǎo)入模塊

import pygame
import random
from pygame.locals import *

游戲音樂設(shè)置

class SoundPlay:
    game_bgm = "sound/GameSceneBGM.ogg"
    world_bgm = 'sound/WorldSceneBGM.ogg'
    eliminate = ('sound/eliminate1.ogg', 'sound/eliminate2.ogg', 'sound/eliminate3.ogg', 'sound/eliminate4.ogg',\
                 'sound/eliminate5.ogg')  # 消除聲音
    score_level = ('sound/good.ogg', 'sound/great.ogg', 'sound/amazing.ogg', 'sound/excellent.ogg',\
                   'sound/unbelievable.ogg')   # 得分聲音
    click = "sound/click.bubble.ogg"  # 點擊選中聲音
    board_sound = 'sound/board.ogg'   # 落板子聲音
    click_button = 'sound/click_common_button.ogg'  # 點擊按鈕聲音
    money_sound = 'sound/money.ogg'   # 點擊銀幣聲音
    ice_break = 'sound/ice_break.ogg'   # 冰消除聲音

    def __init__(self, filename, loops=0):
        self.sound = pygame.mixer.Sound(filename)
        self.sound.play(loops)

制作樹類

class Tree(pygame.sprite.Sprite):
    """樹類"""
    tree = 'pic2/tree.png'     # 樹
    fruit = 'pic2/fruit.png'   # 果子
    energy_num = 'pic2/energy_num.png'  # 精力
    money = 'pic2/money.png'   # 銀幣
    energy_buy = 'pic2/energy_buy.png'   # 購買精力
    x, y = 340, 510
    h = 90
    position = ([x, y], [x+50, y-25], [x+105, y-45], [x-5, y-h-5], [x+55, y-25-h+10], [x+105, y-45-h], \
                [x, y-h*2], [x+50+10, y-25-h*2-5], [x+105+25, y-45-h*2-14], [x+30, y-h*3-30])   # 果子坐標(biāo)組
    energy_num_position = (15, 70)  # 精力坐標(biāo)
    energy_buy_position = (250, 400)

    def __init__(self, icon, position):
        super().__init__()
        self.image = pygame.image.load(icon).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.bottomleft = position      # 左下角為坐標(biāo)

    def draw(self, screen):
        screen.blit(self.image, self.rect)


class ManagerTree:
    """管理樹類"""
    __screen_size = (900, 600)
    screen = pygame.display.set_mode(__screen_size, DOUBLEBUF, 32)
    fruit_list = []
    fruit_image = pygame.image.load(Tree.fruit).convert_alpha()
    fruit_width = fruit_image.get_width()
    fruit_height = fruit_image.get_height()
    type = 0  # 0樹界面,1加精力界面
    energy_full = False  # 精力已滿標(biāo)志 初始未滿
    money_empty = False  # 銀幣不足

    def load_text(self, text, position, txt_size=25, txt_color=(255, 255, 255)):
        my_font = pygame.font.SysFont(None, txt_size)
        text_screen = my_font.render(text, True, txt_color)
        self.screen.blit(text_screen, position)

    def draw_tree(self, energy_num, money_num):
        """畫tree"""
        Tree(Tree.tree, (0, 600)).draw(self.screen)      # 畫樹
        Tree(Tree.energy_num, Tree.energy_num_position).draw(self.screen)  # 畫精力
        # print("energy", energy_num)
        if energy_num > 30:
            self.load_text(str(30) + '/30', (22, 55), 21)
        else:
            self.load_text(str(energy_num)+'/30', (22, 55), 21)
        # print("money", money_num)
        Tree(Tree.money, (15, 135)).draw(self.screen)  # 畫銀幣
        self.load_text(str(money_num), (32, 124), 21)
        for i in range(0, 10):                            # 畫果子
            Tree(Tree.fruit, Tree.position[i]).draw(self.screen)
            self.load_text(str(i+1), (Tree.position[i][0]+15, Tree.position[i][1]-47))
        if self.type == 1:
            Tree(Tree.energy_buy, Tree.energy_buy_position).draw(self.screen)
            if self.energy_full:
                self.load_text("energy is full!", (430, 310), 30, (255, 0, 0))
                pygame.display.flip()
                pygame.time.delay(500)
                self.energy_full = False
            if self.money_empty:
                self.load_text("money is not enough!", (410, 310), 30, (255, 0, 0))
                pygame.display.flip()
                pygame.time.delay(500)
                self.money_empty = False

制作鼠標(biāo)點擊效果

    def mouse_select(self, button, level, energy_num, money_num):
        """鼠標(biāo)點擊"""
        if button.type == MOUSEBUTTONDOWN:
            mouse_down_x, mouse_down_y = button.pos
            print(button.pos)
            if level == 0:
                if self.type == 0:          # 樹界面
                    for i in range(0, 10):
                        if Tree.position[i][0] < mouse_down_x < Tree.position[i][0] + self.fruit_width \
                                and Tree.position[i][1] - self.fruit_height < mouse_down_y < Tree.position[i][1]:
                            if energy_num <= 0:
                                self.type = 1
                            else:
                                level = i + 1
                    if Tree.energy_num_position[0] < mouse_down_x < Tree.energy_num_position[0]+60 \
                            and Tree.energy_num_position[1]-60 < mouse_down_y < Tree.energy_num_position[1]:  # 精力60*60
                        SoundPlay(SoundPlay.click)
                        self.type = 1
                else:               # 加精力彈窗界面
                    if 408 < mouse_down_x < 600 and 263 < mouse_down_y < 313:    # 點加精力按鈕
                        SoundPlay(SoundPlay.click_button)
                        if money_num < 50:
                            self.money_empty = True
                        if energy_num >= 30:
                            self.energy_full = True
                        elif energy_num < 30 and money_num >= 50:
                            energy_num += 5
                            money_num -= 50
                    elif 619 < mouse_down_x < 638 and 158 < mouse_down_y < 177:   # 點叉號
                        self.type = 0
        if button.type == MOUSEBUTTONUP:
            pass
        return level, energy_num, money_num

制作出現(xiàn)元素

class Element(pygame.sprite.Sprite):
    """ 元素類 """
    # 圖標(biāo)元組,包括6個小動物,
    animal = ('pic2/fox.png', 'pic2/bear.png', 'pic2/chick.png', 'pic2/eagle.png', 'pic2/frog.png', 'pic2/cow.png')
    ice = 'pic2/ice.png'  # 冰層
    brick = 'pic2/brick.png'  # 磚
    frame = 'pic2/frame.png'   # 選中框
    bling = ("pic2/bling1.png", "pic2/bling2.png", "pic2/bling3.png", "pic2/bling4.png", "pic2/bling5.png",\
             "pic2/bling6.png", "pic2/bling7.png", "pic2/bling8.png", "pic2/bling9.png")   # 消除動畫

    ice_eli = ('pic2/ice0.png', 'pic2/ice1.png', 'pic2/ice2.png', 'pic2/ice3.png', 'pic2/ice4.png', 'pic2/ice5.png',\
               'pic2/ice6.png', 'pic2/ice7.png', 'pic2/ice8.png')    # 消除冰塊動畫

    # 得分圖片
    score_level = ('pic2/good.png', 'pic2/great.png', 'pic2/amazing.png', 'pic2/excellent.png', 'pic2/unbelievable.png')
    none_animal = 'pic2/noneanimal.png'             # 無可消除小動物
    stop = 'pic2/exit.png'       # 暫停鍵
    stop_position = (20, 530)

    def __init__(self, icon, position):
        super().__init__()
        self.image = pygame.image.load(icon).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.topleft = position         # 左上角坐標(biāo)
        self.speed = [0, 0]
        self.init_position = position

    def move(self, speed):
        self.speed = speed
        self.rect = self.rect.move(self.speed)
        if self.speed[0] != 0:    # 如果左右移動
            if abs(self.rect.left-self.init_position[0]) == self.rect[2]:
                self.init_position = self.rect.topleft
                self.speed = [0, 0]
        else:
            if abs(self.rect.top-self.init_position[1]) == self.rect[3]:
                self.init_position = self.rect.topleft
                self.speed = [0, 0]

    def draw(self, screen):
        screen.blit(self.image, self.rect)


class Board(pygame.sprite.Sprite):
    step_board = 'pic2/step.png'              # 剩余步數(shù)板子
    step = ('pic2/0.png', 'pic2/1.png', 'pic2/2.png', 'pic2/3.png', 'pic2/4.png', 'pic2/5.png',\
            'pic2/6.png', 'pic2/7.png', 'pic2/8.png', 'pic2/9.png', )
    task_board = 'pic2/task.png'              # 任務(wù)板子
    ok = 'pic2/ok.png'    # ok勾
    # 關(guān)數(shù)板子
    levelBoard = ('pic2/level0.png', 'pic2/level1.png', 'pic2/level2.png', 'pic2/level3.png', 'pic2/level4.png', 'pic2/level5.png',
                  'pic2/level6.png', 'pic2/level7.png', 'pic2/level8.png', 'pic2/level9.png', 'pic2/level10.png')
    # xxx = 'pic2/x.png'   # 叉掉
    test = 'pic2/test.png'
    success_board = 'pic2/successtest1.png'  # 過關(guān)成功板子
    fail_board = 'pic2/failBoard.png'  # 任務(wù)失敗
    step_add = 'pic2/step_add.png'  # 增加步數(shù)
    next = "pic2/next.png"  # 下一關(guān)按鈕
    replay = "pic2/replay.png"  # 重玩圖片
    stars = 'pic2/startest.png'  # 星星圖片
    money = 'pic2/money.png'  # 銀幣
    energy = 'pic2/energ.png'  # 精力
    button_position = [[300, 465], [500, 465]]
    starts_position = [[280+50, 340], [375+38, 340], [460+35, 340]]

    def __init__(self, icon, position):
        super().__init__()
        self.image = pygame.image.load(icon).convert_alpha()
        self.speed = [0, 45]
        self.rect = self.image.get_rect()
        self.rect.bottomleft = position                  # 左下角為坐標(biāo)值

    def move(self):
        self.rect = self.rect.move(self.speed)
        if self.rect.bottom >= 543:
            self.speed = [0, -45]
        if self.speed == [0, -45] and self.rect.bottom <= 450:
            self.speed = [0, 0]

    def draw(self, screen):
        screen.blit(self.image, self.rect)

數(shù)組

class Manager:
    """  數(shù)組類 """
    __screen_size = (900, 600)
    screen = pygame.display.set_mode(__screen_size, DOUBLEBUF, 32)
    __brick_size = 50
    __bg = pygame.image.load('pic2/bg.png').convert()
    stop_width = 63
    selected = [-1, -1]   # 現(xiàn)選中[row, col]
    exchange_sign = -1  # 未交換標(biāo)志
    last_sel = [-1, -1]  # 上一次選中[row, col]
    change_value_sign = False  # 是否交換值標(biāo)志,初始不交換
    death_sign = True  # 死圖標(biāo)志,初始不是死圖
    boom_sel = [-1, -1]   # 四連消特效小動物所在位置 row,col
    level = 0  # 當(dāng)前關(guān)卡數(shù)  初始第0關(guān)
    money = 100  # 金幣
    energy_num = 30  # 精力值
    num_sign = True
    type = 2  # 0代表游戲中; 1代表完成任務(wù),過關(guān); -1代表步數(shù)用完,任務(wù)未完成,過關(guān)失敗; 2代表未游戲狀態(tài),板子界面
    reset_mode = True     # 是否重新布局(每關(guān)布局)
    init_step = 15  # 每關(guān)規(guī)定步數(shù)
    step = init_step     # 代表游戲所剩余的步數(shù)
    score = 0        # 得數(shù)
    min = 20  # 分?jǐn)?shù)中間值1
    max = 50  # 分?jǐn)?shù)中間值2
    animal_num = [0, 0, 0, 0, 0, 0]   # 本關(guān)消除各小動物的個數(shù)
    ice_num = 0
    success_board = Board(Board.success_board, [200, 0])  # 過關(guān)成功板
    fail_board = Board(Board.fail_board, [200, 0])  # 任務(wù)失敗板
    height, width = 9, 9
    row, col = 5, 5
    ice_list = [[-1 for col in range(21)]for row in range(21)]   # -1不畫,1畫冰
    animal = [[-1 for col in range(21)]for row in range(21)]   # -2消除的,-1不畫,0-4小動物
    list_x, list_y = (__screen_size[0] - 11 * __brick_size) / 2, (__screen_size[1] - 11 * __brick_size) / 2  # 矩陣坐標(biāo)

    def __init__(self, width, height):
        self.height = height
        self.width = width
        self.list_x = (Manager.__screen_size[0] - self.width * Manager.__brick_size) / 2
        self.list_y = (Manager.__screen_size[1] - self.height * Manager.__brick_size) / 2
        self.row, self.col = Manager.xy_rc(self.list_x, self.list_y)
        self.list_x, self.list_y = Manager.rc_xy(self.row, self.col)
        self.ice_list = [[-1 for col in range(21)]for row in range(21)]
        self.animal = [[-1 for col in range(21)]for row in range(21)]
        self.reset_animal()

    def reset_animal(self):
        for row in range(self.row, self.row + self.height):
            for col in range(self.col, self.col + self.width):
                self.animal[row][col] = random.randint(0, 5)

    @staticmethod
    def rc_xy(row, col):
        """row col 轉(zhuǎn) x,y坐標(biāo)"""
        return int(Manager.list_x + (col-Manager.col)*Manager.__brick_size), int\
            (Manager.list_y+(row-Manager.row)*Manager.__brick_size)

    @staticmethod
    def xy_rc(x, y):
        """x,y坐標(biāo)轉(zhuǎn)row col"""
        return int((y-Manager.list_y)/Manager.__brick_size+Manager.row), int\
            ((x-Manager.list_x)/Manager.__brick_size+Manager.col)

    @staticmethod
    def draw_brick(x, y):
        brick = Element(Element.brick, (x, y))
        Manager.screen.blit(brick.image, brick.rect)

    def draw_task(self, task_animal_num, which_animal, \
                  board_position=(400, 90), animal_position=(430, 35), txt_position=(455, 60)):

制作人物畫板

        """畫任務(wù)板子"""
        txt_size = 24
        txt_color = (0, 0, 0)
        Board(Board.task_board, board_position).draw(self.screen)
        if which_animal == 6:
            task_animal = Element(Element.ice, animal_position)
        else:
            task_animal = Element(Element.animal[which_animal], animal_position)
        task_animal.image = pygame.transform.smoothscale(task_animal.image, (40, 40))
        task_animal.draw(self.screen)
        if which_animal == 6:
            if task_animal_num-self.ice_num <= 0:
                Board(Board.ok, (txt_position[0], txt_position[1]+15)).draw(self.screen)
            else:
                self.load_text(str(task_animal_num-self.ice_num), txt_position, txt_size, txt_color)
        else:
            if task_animal_num - self.animal_num[which_animal] <= 0:
                Board(Board.ok, (txt_position[0], txt_position[1]+15)).draw(self.screen)
            else:
                self.load_text(str(task_animal_num - self.animal_num[which_animal]), txt_position, txt_size, txt_color)
3. 效果展示(僅部分)

初始頁面

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

第一關(guān)畫面

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

失敗畫面

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

第十關(guān)畫面

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

尾語

感謝你觀看我的文章吶~本次航班到這里就結(jié)束啦 ??

希望本篇文章有對你帶來幫助 ??,有學(xué)習(xí)到一點知識~

躲起來的星星??也在努力發(fā)光,你也要努力加油(讓我們一起努力叭)。

【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂

最后,宣傳一下呀~??????更多源碼、資料、素材、解答、交流皆點擊下方名片獲取呀??????文章來源地址http://www.zghlxwxcb.cn/news/detail-436096.html

到了這里,關(guān)于【pygame游戲開發(fā)】這幾個經(jīng)典游戲,勾起了少年的快樂的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • Python版經(jīng)典小游戲憤怒的小鳥源代碼,基于pygame+pymunk

    Python版經(jīng)典小游戲憤怒的小鳥源代碼,基于pygame+pymunk

    Python版經(jīng)典小游戲憤怒的小鳥源代碼,基于pygame+pymunk 程序依賴:pygame 2.0.1, pymunk 5.5.0 直接運行main.py 完整代碼下載地址:Python版經(jīng)典小游戲憤怒的小鳥源代碼 tool.py 完整代碼下載地址:Python版經(jīng)典小游戲憤怒的小鳥源代碼

    2024年02月16日
    瀏覽(103)
  • 【Pygame實戰(zhàn)】懷舊經(jīng)典—這款給娃的棋類游戲,你還記得叫什么吧?(一定要收藏)

    【Pygame實戰(zhàn)】懷舊經(jīng)典—這款給娃的棋類游戲,你還記得叫什么吧?(一定要收藏)

    大家以前應(yīng)該都聽說過一個游戲:叫做 走四棋兒 這款游戲出來到現(xiàn)在時間挺長了,小時候的家鄉(xiāng)農(nóng)村條件有限,附近也沒有正式的玩具店能買 到玩具,因此小朋友們聚在一起玩耍時,其玩具大多都是就地取材的。 直接在家里的水泥地上用燒完的炭火灰畫出幾條線,擺上幾顆

    2024年02月05日
    瀏覽(850)
  • python游戲開發(fā)入門經(jīng)典教程,python游戲開發(fā)引擎

    python游戲開發(fā)入門經(jīng)典教程,python游戲開發(fā)引擎

    大家好,給大家分享一下python游戲開發(fā)入門經(jīng)典教程,很多人還不知道這一點。下面詳細(xì)解釋一下?,F(xiàn)在讓我們來看看! 消消樂小游戲相信大家都玩過,大人小孩都喜歡玩的一款小游戲,那么基于程序是如何實現(xiàn)的呢?今天帶大家,用python+pygame來實現(xiàn)一下這個花里胡哨的消

    2024年02月02日
    瀏覽(22)
  • Python經(jīng)典游戲:貪吃蛇

    Python經(jīng)典游戲:貪吃蛇

    Python108款,小游戲集合,總有一個是你想要的 中國象棋 像素鳥 五子棋 24點小游戲 貪吃蛇 掃雷 俄羅斯方塊 魂斗羅 消消樂 坦克大戰(zhàn) 外星人入侵 湯姆貓 斗地主 乒乓球 推箱子 植物大戰(zhàn)僵尸 圍棋 超級瑪麗 飛機大戰(zhàn) 迷宮 滑雪 吃豆人…等等 (需要的回復(fù)666或點擊最下方的歷史

    2024年04月22日
    瀏覽(33)
  • ??創(chuàng)意網(wǎng)頁:貪吃蛇游戲 - 創(chuàng)造一個經(jīng)典的小游戲

    ??創(chuàng)意網(wǎng)頁:貪吃蛇游戲 - 創(chuàng)造一個經(jīng)典的小游戲

    ? 博主: 命運之光 ? ?? 專欄: Python星辰秘典 ?? 專欄: web開發(fā)(簡單好用又好看) ?? 專欄: Java經(jīng)典程序設(shè)計 ?? 博主的其他文章: 點擊進入博主的主頁 前言: 歡迎踏入我的Web項目專欄,一段神奇而令人陶醉的數(shù)字世界! ?? 在這里,我將帶您穿越時空,揭開屬于

    2024年02月14日
    瀏覽(27)
  • 面試經(jīng)典150題——生命游戲

    面試經(jīng)典150題——生命游戲

    2.1 思路一——暴力求解 之所以先暴力求解,是因為我開始也沒什么更好的思路,所以就先寫一種解決方案,沒準(zhǔn)寫著寫著就來新的靈感了。暴力求解思路還是很簡單的,就是嘗試遍歷面板的每個格子,判斷其周圍八個位置的狀態(tài)(對于邊角需要特殊處理),根據(jù)邊角種存在

    2024年02月21日
    瀏覽(19)
  • 【面試經(jīng)典150 | 矩陣】生命游戲

    【面試經(jīng)典150 | 矩陣】生命游戲

    本專欄專注于分析與講解【面試經(jīng)典150】算法,兩到三天更新一篇文章,歡迎催更…… 專欄內(nèi)容以分析題目為主,并附帶一些對于本題涉及到的數(shù)據(jù)結(jié)構(gòu)等內(nèi)容進行回顧與總結(jié),文章結(jié)構(gòu)大致如下,部分內(nèi)容會有增刪: Tag:介紹本題牽涉到的知識點、數(shù)據(jù)結(jié)構(gòu); 題目來源:

    2024年02月07日
    瀏覽(25)
  • Python經(jīng)典游戲 喚醒你童年記憶

    Python經(jīng)典游戲 喚醒你童年記憶

    ??游戲規(guī)則:使用方向鍵控制蛇去吃球。每吃一次球,蛇身就長出一格。吃到自己或者出界游戲結(jié)束。 游戲演示: ??游戲規(guī)則:用箭頭導(dǎo)航控制黃色吃豆人吃掉所有白色食物,若被紅色的鬼魂抓住,游戲結(jié)束。 游戲演示: ??游戲規(guī)則:點擊屏幕發(fā)射炮彈。炮彈在它的路徑

    2024年02月03日
    瀏覽(24)
  • 用C語言實現(xiàn)經(jīng)典游戲——貪吃蛇

    用C語言實現(xiàn)經(jīng)典游戲——貪吃蛇

    目錄 1.游戲?qū)崿F(xiàn)思想 (1)定義蛇對象 (2)食物對象 (3)分?jǐn)?shù):? (4)初始化蛇 (5)初始化食物 (6)修改控制臺光標(biāo)位置 (7)畫出蛇和食物 (8)蛇的移動控制 (9)開始游戲? (10)蛇移動 (11)畫墻 (12)去除蛇尾 (13)去除光標(biāo) (14)顯示分?jǐn)?shù) (15)加速 2.游戲?qū)?/p>

    2024年02月11日
    瀏覽(27)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包