最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

中秋將至利用python畫一些月餅從天而降不用買了

 更新時(shí)間:2021年09月18日 15:43:14   作者:顧木子吖  
中秋沒兩天就要到了,今天小編就利用python畫個(gè)月餅的小游戲,文中內(nèi)容非常詳細(xì),感興趣的小伙伴一定要收藏起來送給遠(yuǎn)方的朋友呀

導(dǎo)語

好消息!下一個(gè)假期已經(jīng)在路上了,正在向我們招手呢!

大家只要再堅(jiān)持5天

就能迎來中秋小長假啦~

圖片

​“海上生明月,天涯共此時(shí)”

又是一年中秋至!快跟著小編來看看怎么寓教于樂吧~~

今天帶大家編寫一款應(yīng)時(shí)應(yīng)景的中秋小游戲!

天上掉月餅啦~天上掉月餅啦~天上掉月餅啦~

圖片

正文

​準(zhǔn)備好相應(yīng)的素材如下:

環(huán)境安裝:

Python3.6、pycharm2021、游戲模塊Pygame。

安裝:pip install  pygame

​初始化游戲加載素材:

def initGame():
 
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('中秋月餅小游戲')
 
    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)
 
    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))
        # --倒計(jì)時(shí)信息
        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)
        # --按鍵檢測(cè)
        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')
        # --隨機(jī)生成
        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)
        # --碰撞檢測(cè)
        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)

定義月餅、燈籠等掉落:

import pygame
import random
 
 
 
class Food(pygame.sprite.Sprite):
    def __init__(self, images_dict, selected_key, screensize, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.screensize = screensize
        self.image = images_dict[selected_key]
        self.mask = pygame.mask.from_surface(self.image)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.bottom = random.randint(20, screensize[0]-20), -10
        self.speed = random.randrange(5, 10)
        self.score = 1 if selected_key == 'gold' else 5
    '''更新食物位置'''
    def update(self):
        self.rect.bottom += self.speed
        if self.rect.top > self.screensize[1]:
            return True
        return False

定義接月餅的人物:

import pygame
 
 
class Hero(pygame.sprite.Sprite):
    def __init__(self, images, position=(375, 520), **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.images_right = images[:5]
        self.images_left = images[5:]
        self.images = self.images_right.copy()
        self.image = self.images[0]
        self.mask = pygame.mask.from_surface(self.image)
        self.rect = self.image.get_rect()
        self.rect.left, self.rect.top = position
        self.diretion = 'right'
        self.speed = 8
        self.switch_frame_count = 0
        self.switch_frame_freq = 1
        self.frame_index = 0
    '''左右移動(dòng)hero'''
    def move(self, screensize, direction):
        assert direction in ['left', 'right']
        if direction != self.diretion:
            self.images = self.images_left.copy() if direction == 'left' else self.images_right.copy()
            self.image = self.images[0]
            self.diretion = direction
            self.switch_frame_count = 0
        self.switch_frame_count += 1
        if self.switch_frame_count % self.switch_frame_freq == 0:
            self.switch_frame_count = 0
            self.frame_index = (self.frame_index + 1) % len(self.images)
            self.image = self.images[self.frame_index]
        if direction == 'left':
            self.rect.left = max(self.rect.left-self.speed, 0)
        else:
            self.rect.left = min(self.rect.left+self.speed, screensize[0])
    '''畫到屏幕上'''
    def draw(self, screen):
        screen.blit(self.image, self.rect)

游戲結(jié)束界面:設(shè)置的一分30秒結(jié)束接到多少就是多少分?jǐn)?shù)。

import sys
import pygame
 
 
'''游戲結(jié)束畫面'''
def showEndGameInterface(screen, cfg, score, highest_score):
    # 顯示的文本信息設(shè)置
    font_big = pygame.font.Font(cfg.FONT_PATH, 60)
    font_small = pygame.font.Font(cfg.FONT_PATH, 40)
    text_title = font_big.render(f"Time is up!", True, (255, 0, 0))
    text_title_rect = text_title.get_rect()
    text_title_rect.centerx = screen.get_rect().centerx
    text_title_rect.centery = screen.get_rect().centery - 100
    text_score = font_small.render(f"Score: {score}, Highest Score: {highest_score}", True, (255, 0, 0))
    text_score_rect = text_score.get_rect()
    text_score_rect.centerx = screen.get_rect().centerx
    text_score_rect.centery = screen.get_rect().centery - 10
    text_tip = font_small.render(f"Enter Q to quit game or Enter R to restart game", True, (255, 0, 0))
    text_tip_rect = text_tip.get_rect()
    text_tip_rect.centerx = screen.get_rect().centerx
    text_tip_rect.centery = screen.get_rect().centery + 60
    text_tip_count = 0
    text_tip_freq = 10
    text_tip_show_flag = True
    # 界面主循環(huán)
    clock = pygame.time.Clock()
    while True:
        screen.fill(0)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    return False
                elif event.key == pygame.K_r:
                    return True
        screen.blit(text_title, text_title_rect)
        screen.blit(text_score, text_score_rect)
        if text_tip_show_flag:
            screen.blit(text_tip, text_tip_rect)
        text_tip_count += 1
        if text_tip_count % text_tip_freq == 0:
            text_tip_count = 0
            text_tip_show_flag = not text_tip_show_flag
        pygame.display.flip()
        clock.tick(cfg.FPS)

游戲界面:

​​​

​​總結(jié)

好啦!今天的游戲更新跟中秋主題一次性寫完啦!嘿嘿~機(jī)智如我!​​​

圖片

到此這篇關(guān)于中秋將至利用python畫一些月餅從天而降不用買了的文章就介紹到這了,更多相關(guān)python 中秋 月餅 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • numpy下的flatten()函數(shù)用法詳解

    numpy下的flatten()函數(shù)用法詳解

    這篇文章主要介紹了numpy下的flatten()函數(shù)用法詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • 關(guān)于numpy.where()函數(shù) 返回值的解釋

    關(guān)于numpy.where()函數(shù) 返回值的解釋

    今天小編就為大家分享一篇關(guān)于numpy.where()函數(shù) 返回值的解釋,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 深入解析Python中BeautifulSoup4的基礎(chǔ)知識(shí)與實(shí)戰(zhàn)應(yīng)用

    深入解析Python中BeautifulSoup4的基礎(chǔ)知識(shí)與實(shí)戰(zhàn)應(yīng)用

    BeautifulSoup4正是一款功能強(qiáng)大的解析器,能夠輕松解析HTML和XML文檔,本文將介紹BeautifulSoup4的基礎(chǔ)知識(shí),并通過實(shí)際代碼示例進(jìn)行演示,感興趣的可以了解下
    2024-02-02
  • python解釋器安裝教程的方法步驟

    python解釋器安裝教程的方法步驟

    這篇文章主要介紹了python解釋器安裝教程的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-07-07
  • 如何使用python爬蟲爬取要登陸的網(wǎng)站

    如何使用python爬蟲爬取要登陸的網(wǎng)站

    這篇文章主要介紹了如何使用python爬蟲爬取要登陸的網(wǎng)站,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • python控制windows剪貼板,向剪貼板中寫入圖片的實(shí)例

    python控制windows剪貼板,向剪貼板中寫入圖片的實(shí)例

    今天小編就為大家分享一篇python控制windows剪貼板,向剪貼板中寫入圖片的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • 使用Python讀取和修改Excel文件(基于xlrd、xlwt和openpyxl模塊)

    使用Python讀取和修改Excel文件(基于xlrd、xlwt和openpyxl模塊)

    本文介紹一下使用Python對(duì)Excel文件的基本操作,包括使用xlrd模塊讀取excel文件,使用xlwt模塊將數(shù)據(jù)寫入excel文件,使用openpyxl模塊讀取寫入和修改excel文件,需要的朋友可以參考下
    2021-11-11
  • PyCharm出現(xiàn)卡頓問題的解決

    PyCharm出現(xiàn)卡頓問題的解決

    這篇文章主要介紹了PyCharm出現(xiàn)卡頓問題的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-02-02
  • Python實(shí)現(xiàn)修改文件內(nèi)容的方法分析

    Python實(shí)現(xiàn)修改文件內(nèi)容的方法分析

    這篇文章主要介紹了Python實(shí)現(xiàn)修改文件內(nèi)容的方法,結(jié)合實(shí)例形式分析了Python文件讀寫、字符串替換及shell方法調(diào)用等相關(guān)操作技巧,需要的朋友可以參考下
    2018-03-03
  • Python格式化字符串f-string的使用教程

    Python格式化字符串f-string的使用教程

    這篇文章主要為大家詳細(xì)介紹了Python中格式化字符串f-string的使用教程,文中通過示例為大家進(jìn)行了詳細(xì)的介紹,需要的可以參考一下
    2022-07-07

最新評(píng)論

永兴县| 芦溪县| 赤城县| 望谟县| 启东市| 金昌市| 嘉荫县| 灵山县| 乌鲁木齐县| 东平县| 尼木县| 万全县| 闻喜县| 新化县| 毕节市| 松桃| 林西县| 嫩江县| 商河县| 桂林市| 泾阳县| 儋州市| 澳门| 吉安县| 武宣县| 楚雄市| 勐海县| 巴东县| 内黄县| 晋中市| 灵台县| 西昌市| 抚州市| 静乐县| 遵义市| 湘阴县| 婺源县| 济南市| 左云县| 大关县| 青州市|