【Python童年游戏】满满的回忆杀—那些年玩过的童年游戏你还记得吗?那个才是你的菜?看到第一个我就泪奔了(致我们逝去的青春)

news2025/1/18 7:02:14

导语

滴一一学生卡🙌

结伴上车的学生仔子们

用笑声打破车厢的沉默

大人眼里的晚高峰

是给放学后快乐😀时光的加时

下车的学生匆匆起身带起

一阵熟悉的栀子香于💓

是关于校园的记忆

开始零零散散地闪现

放学后集合的秘密基地/跟着城市变了模样

超级马里奥里的隐藏地图😁(重点)

吃豆人里的闪躲奥秘 😁(重点)

却刻进了DNA里一曾经珍藏的交换日记

不记得被放在了哪里

你现在记得的是/相互鼓励的感动

还是小纸条里写的八卦❓

从肩上的书包到手里的电脑包

时间在改变生活的轨迹🚀

少年带着率真与坚定/甩开不谙世事

同在路上的朋友啊

愿你迎风像栀子花一样/💯继续灿烂地开!

所有文章完整的素材+源码都在👇👇

粉丝白嫖源码福利,请移步至CSDN社区或文末公众hao即可免费。

当我写完前言的时候,可能在长沙的小伙伴儿就知道这是哪儿的宣传语,偷偷给你们提醒,是

一家好喝的奶茶店哦~

今天去喝奶茶的时候,突然看到了这个宣传语我就拍下来啦,然后当做今天的内容素材,嘿嘿

今天小编教大家两款上面提到过的小游戏,直接用Python编程的语言来诠释它们——

1、超级马里奥里的隐藏地图(重点)  2、吃豆人里的闪躲奥秘 (重点)。

正文

小霸王,那是属于一代人的记忆,70、80、甚至90后都对这个“键盘”有着不一样的感情。

今今天小编教大家用代码编写两款小游戏给大家,大家喜欢的话记得三连哦~

一、环境准备中 

 1)运行环境

环境安装:python 3.8: 解释器、pycharm: 代码编辑器。需要安装的模块如下

2)的模块安装方式安装即可。自带的一些模块 直接安装Python就可以使用了。 

 相对应的安装包/安装教程/激活码/使用教程/学 习资料/工具插件 可以直接找我厚台获取 。 

 2)模块安装 

 第三方库的安装方式如下: 

 一般安装:pip install +模块名 

 镜像源安装:pip install -i https://pypi.douban.com/simple/+模块名

(还有很多国内镜像源,这里是豆瓣的用习惯 了,其他镜像源可以去看下之前文章都有的) 

 模块安装问题可以详细的找我给大家讲一下的哈,之前其实也有的文章写了几个点的。 

二、超级马里奥里的隐藏地图

“超级玛丽”有多少人还记得这款经典游戏?对于90、00后应该不大熟悉,但多多少少印象中见

那个戴帽子的大胡子穿着背带裤的马里奥🤣

如果你的童年也曾被魔性的 灯~灯灯~灯~灯灯~灯洗脑那就接着来怀旧一番吧~

1)运行程序:mario_level_1.py。

#!/usr/bin/env python
__author__ = '超级玛丽-源码基地'
 
"""
This is an attempt to recreate the first level of
Super Mario Bros for the NES.
"""
 
import sys
import pygame as pg
from data.main import main
import cProfile
 
 
if __name__=='__main__':
    main()
    pg.quit()
    sys.exit()

2) 配置音乐文字等setup.py。🎑

__author__ = 'Python源码基地'
 
"""
This module initializes the display and creates dictionaries of resources.
"""
 
import os
import pygame as pg
from . import tools
from .import constants as c
 
ORIGINAL_CAPTION = c.ORIGINAL_CAPTION
 
 
os.environ['SDL_VIDEO_CENTERED'] = '1'
pg.init()
pg.event.set_allowed([pg.KEYDOWN, pg.KEYUP, pg.QUIT])
pg.display.set_caption(c.ORIGINAL_CAPTION)
SCREEN = pg.display.set_mode(c.SCREEN_SIZE)
SCREEN_RECT = SCREEN.get_rect()
 
 
FONTS = tools.load_all_fonts(os.path.join("resources","fonts"))
MUSIC = tools.load_all_music(os.path.join("resources","music"))
GFX   = tools.load_all_gfx(os.path.join("resources","graphics"))
SFX   = tools.load_all_sfx(os.path.join("resources","sound"))

3)游戏音乐设置game_sound.py。🎑

__author__ = 'Python顾木子吖'
 
import pygame as pg
from . import setup
from . import constants as c
 
class Sound(object):
    """Handles all sound for the game"""
    def __init__(self, overhead_info):
        """Initialize the class"""
        self.sfx_dict = setup.SFX
        self.music_dict = setup.MUSIC
        self.overhead_info = overhead_info
        self.game_info = overhead_info.game_info
        self.set_music_mixer()
 
 
 
    def set_music_mixer(self):
        """Sets music for level"""
        if self.overhead_info.state == c.LEVEL:
            pg.mixer.music.load(self.music_dict['main_theme'])
            pg.mixer.music.play()
            self.state = c.NORMAL
        elif self.overhead_info.state == c.GAME_OVER:
            pg.mixer.music.load(self.music_dict['game_over'])
            pg.mixer.music.play()
            self.state = c.GAME_OVER
 
 
    def update(self, game_info, mario):
        """Updates sound object with game info"""
        self.game_info = game_info
        self.mario = mario
        self.handle_state()
 
    def  handle_state(self):
        """Handles the state of the soundn object"""
        if self.state == c.NORMAL:
            if self.mario.dead:
                self.play_music('death', c.MARIO_DEAD)
            elif self.mario.invincible \
                    and self.mario.losing_invincibility == False:
                self.play_music('invincible', c.MARIO_INVINCIBLE)
            elif self.mario.state == c.FLAGPOLE:
                self.play_music('flagpole', c.FLAGPOLE)
            elif self.overhead_info.time == 100:
                self.play_music('out_of_time', c.TIME_WARNING)
 
 
        elif self.state == c.FLAGPOLE:
            if self.mario.state == c.WALKING_TO_CASTLE:
                self.play_music('stage_clear', c.STAGE_CLEAR)
 
        elif self.state == c.STAGE_CLEAR:
            if self.mario.in_castle:
                self.sfx_dict['count_down'].play()
                self.state = c.FAST_COUNT_DOWN
 
        elif self.state == c.FAST_COUNT_DOWN:
            if self.overhead_info.time == 0:
                self.sfx_dict['count_down'].stop()
                self.state = c.WORLD_CLEAR
 
        elif self.state == c. TIME_WARNING:
            if pg.mixer.music.get_busy() == 0:
                self.play_music('main_theme_sped_up', c.SPED_UP_NORMAL)
            elif self.mario.dead:
                self.play_music('death', c.MARIO_DEAD)
 
        elif self.state == c.SPED_UP_NORMAL:
            if self.mario.dead:
                self.play_music('death', c.MARIO_DEAD)
            elif self.mario.state == c.FLAGPOLE:
                self.play_music('flagpole', c.FLAGPOLE)
 
        elif self.state == c.MARIO_INVINCIBLE:
            if (self.mario.current_time - self.mario.invincible_start_timer) > 11000:
                self.play_music('main_theme', c.NORMAL)
            elif self.mario.dead:
                self.play_music('death', c.MARIO_DEAD)
 
 
        elif self.state == c.WORLD_CLEAR:
            pass
        elif self.state == c.MARIO_DEAD:
            pass
        elif self.state == c.GAME_OVER:
            pass
 
    def play_music(self, key, state):
        """Plays new music"""
        pg.mixer.music.load(self.music_dict[key])
        pg.mixer.music.play()
        self.state = state
 
    def stop_music(self):
        """Stops playback"""
        pg.mixer.music.stop()

4)取得的分数🎑。

import pygame as pg
from .. import setup
from .. import constants as c
 
 
class Digit(pg.sprite.Sprite):
    """Individual digit for score"""
    def __init__(self, image):
        super(Digit, self).__init__()
        self.image = image
        self.rect = image.get_rect()
 
 
class Score(object):
    """Scores that appear, float up, and disappear"""
    def __init__(self, x, y, score, flag_pole=False):
        self.x = x
        self.y = y
        if flag_pole:
            self.y_vel = -4
        else:
            self.y_vel = -3
        self.sprite_sheet = setup.GFX['item_objects']
        self.create_image_dict()
        self.score_string = str(score)
        self.create_digit_list()
        self.flag_pole_score = flag_pole
 
 
    def create_image_dict(self):
        """Creates the dictionary for all the number 图片 needed"""
        self.image_dict = {}
 
        image0 = self.get_image(1, 168, 3, 8)
        image1 = self.get_image(5, 168, 3, 8)
        image2 = self.get_image(8, 168, 4, 8)
        image4 = self.get_image(12, 168, 4, 8)
        image5 = self.get_image(16, 168, 5, 8)
        image8 = self.get_image(20, 168, 4, 8)
        image9 = self.get_image(32, 168, 5, 8)
        image10 = self.get_image(37, 168, 6, 8)
        image11 = self.get_image(43, 168, 5, 8)
 
        self.image_dict['0'] = image0
        self.image_dict['1'] = image1
        self.image_dict['2'] = image2
        self.image_dict['4'] = image4
        self.image_dict['5'] = image5
        self.image_dict['8'] = image8
        self.image_dict['3'] = image9
        self.image_dict['7'] = image10
        self.image_dict['9'] = image11
 
 
    def get_image(self, x, y, width, height):
        """Extracts image from sprite sheet"""
        image = pg.Surface([width, height]).convert()
        rect = image.get_rect()
 
        image.blit(self.sprite_sheet, (0, 0), (x, y, width, height))
        image.set_colorkey(c.BLACK)
        image = pg.transform.scale(image,
                                   (int(rect.width*c.BRICK_SIZE_MULTIPLIER),
                                    int(rect.height*c.BRICK_SIZE_MULTIPLIER)))
        return image
 
 
    def create_digit_list(self):
        """Creates the group of 图片 based on score received"""
        self.digit_list = []
        self.digit_group = pg.sprite.Group()
 
        for digit in self.score_string:
            self.digit_list.append(Digit(self.image_dict[digit]))
 
        self.set_rects_for_images()
 
 
    def set_rects_for_images(self):
        """Set the rect attributes for each image in self.image_list"""
        for i, digit in enumerate(self.digit_list):
            digit.rect = digit.image.get_rect()
            digit.rect.x = self.x + (i * 10)
            digit.rect.y = self.y
 
 
    def update(self, score_list, level_info):
        """Updates score movement"""
        for number in self.digit_list:
            number.rect.y += self.y_vel
 
        if score_list:
            self.check_to_delete_floating_scores(score_list, level_info)
 
        if self.flag_pole_score:
            if self.digit_list[0].rect.y <= 120:
                self.y_vel = 0
 
 
    def draw(self, screen):
        """Draws score numbers onto screen"""
        for digit in self.digit_list:
            screen.blit(digit.image, digit.rect)
 
 
    def check_to_delete_floating_scores(self, score_list, level_info):
        """Check if scores need to be deleted"""
        for i, score in enumerate(score_list):
            if int(score.score_string) == 1000:
                if (score.y - score.digit_list[0].rect.y) > 130:
                    score_list.pop(i)
 
            else:
                if (score.y - score.digit_list[0].rect.y) > 75:
                    score_list.pop(i)

5)效果展示

游戏界面——

游戏运行——

​三、吃豆人里的闪躲奥秘

1)配置文件:cfg.py

import os
 
 
'''定义一些颜色'''
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
PURPLE = (255, 0, 255)
SKYBLUE = (0, 191, 255)
'''游戏素材路径'''
BGMPATH = os.path.join(os.getcwd(), 'resources/sounds/bg.mp3')
ICONPATH = os.path.join(os.getcwd(), 'resources/images/icon.png')
FONTPATH = os.path.join(os.getcwd(), 'resources/font/ALGER.TTF')
HEROPATH = os.path.join(os.getcwd(), 'resources/images/pacman.png')
BlinkyPATH = os.path.join(os.getcwd(), 'resources/images/Blinky.png')
ClydePATH = os.path.join(os.getcwd(), 'resources/images/Clyde.png')
InkyPATH = os.path.join(os.getcwd(), 'resources/images/Inky.png')
PinkyPATH = os.path.join(os.getcwd(), 'resources/images/Pinky.png')

2)定义一些精灵类:Sprites.py

import random
import pygame
 
 
'''墙类'''
class Wall(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.left = x
        self.rect.top = y
 
 
'''食物类'''
class Food(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, color, bg_color, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([width, height])
        self.image.fill(bg_color)
        self.image.set_colorkey(bg_color)
        pygame.draw.ellipse(self.image, color, [0, 0, width, height])
        self.rect = self.image.get_rect()
        self.rect.left = x
        self.rect.top = y
 
 
'''角色类'''
class Player(pygame.sprite.Sprite):
    def __init__(self, x, y, role_image_path):
        pygame.sprite.Sprite.__init__(self)
        self.role_name = role_image_path.split('/')[-1].split('.')[0]
        self.base_image = pygame.image.load(role_image_path).convert()
        self.image = self.base_image.copy()
        self.rect = self.image.get_rect()
        self.rect.left = x
        self.rect.top = y
        self.prev_x = x
        self.prev_y = y
        self.base_speed = [30, 30]
        self.speed = [0, 0]
        self.is_move = False
        self.tracks = []
        self.tracks_loc = [0, 0]
    '''改变速度方向'''
    def changeSpeed(self, direction):
        if direction[0] < 0:
            self.image = pygame.transform.flip(self.base_image, True, False)
        elif direction[0] > 0:
            self.image = self.base_image.copy()
        elif direction[1] < 0:
            self.image = pygame.transform.rotate(self.base_image, 90)
        elif direction[1] > 0:
            self.image = pygame.transform.rotate(self.base_image, -90)
        self.speed = [direction[0] * self.base_speed[0], direction[1] * self.base_speed[1]]
        return self.speed
    '''更新角色位置'''
    def update(self, wall_sprites, gate_sprites):
        if not self.is_move:
            return False
        x_prev = self.rect.left
        y_prev = self.rect.top
        self.rect.left += self.speed[0]
        self.rect.top += self.speed[1]
        is_collide = pygame.sprite.spritecollide(self, wall_sprites, False)
        if gate_sprites is not None:
            if not is_collide:
                is_collide = pygame.sprite.spritecollide(self, gate_sprites, False)
        if is_collide:
            self.rect.left = x_prev
            self.rect.top = y_prev
            return False
        return True
    '''生成随机的方向'''
    def randomDirection(self):
        return random.choice([[-0.5, 0], [0.5, 0], [0, 0.5], [0, -0.5]])

3)定义关卡:Levels.py

import pygame
from .Sprites import *
 
 
'''关卡数量'''
NUMLEVELS = 1
 
 
'''关卡一'''
class Level1():
    def __init__(self):
        self.info = 'level1'
    '''创建墙'''
    def setupWalls(self, wall_color):
        self.wall_sprites = pygame.sprite.Group()
        wall_positions = [
            [0, 0, 6, 600], [0, 0, 600, 6], [0, 600, 606, 6], [600, 0, 6, 606], [300, 0, 6, 66], [60, 60, 186, 6],
            [360, 60, 186, 6], [60, 120, 66, 6], [60, 120, 6, 126], [180, 120, 246, 6], [300, 120, 6, 66],
            [480, 120, 66, 6], [540, 120, 6, 126], [120, 180, 126, 6], [120, 180, 6, 126], [360, 180, 126, 6],
            [480, 180, 6, 126], [180, 240, 6, 126], [180, 360, 246, 6], [420, 240, 6, 126], [240, 240, 42, 6],
            [324, 240, 42, 6], [240, 240, 6, 66], [240, 300, 126, 6], [360, 240, 6, 66], [0, 300, 66, 6],
            [540, 300, 66, 6], [60, 360, 66, 6], [60, 360, 6, 186], [480, 360, 66, 6], [540, 360, 6, 186],
            [120, 420, 366, 6], [120, 420, 6, 66], [480, 420, 6, 66], [180, 480, 246, 6], [300, 480, 6, 66],
            [120, 540, 126, 6], [360, 540, 126, 6]
        ]
        for wall_position in wall_positions:
            wall = Wall(*wall_position, wall_color)
            self.wall_sprites.add(wall)
        return self.wall_sprites
    '''创建门'''
    def setupGate(self, gate_color):
        self.gate_sprites = pygame.sprite.Group()
        self.gate_sprites.add(Wall(282, 242, 42, 2, gate_color))
        return self.gate_sprites
    '''创建角色'''
    def setupPlayers(self, hero_image_path, ghost_images_path):
        self.hero_sprites = pygame.sprite.Group()
        self.ghost_sprites = pygame.sprite.Group()
        self.hero_sprites.add(Player(287, 439, hero_image_path))
        for each in ghost_images_path:
            role_name = each.split('/')[-1].split('.')[0]
            if role_name == 'Blinky':
                player = Player(287, 199, each)
                player.is_move = True
                player.tracks = [
                    [0, -0.5, 4], [0.5, 0, 9], [0, 0.5, 11], [0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 11], [0, 0.5, 3],
                    [0.5, 0, 15], [0, -0.5, 15], [0.5, 0, 3], [0, -0.5, 11], [-0.5, 0, 3], [0, -0.5, 11], [-0.5, 0, 3],
                    [0, -0.5, 3], [-0.5, 0, 7], [0, -0.5, 3], [0.5, 0, 15], [0, 0.5, 15], [-0.5, 0, 3], [0, 0.5, 3],
                    [-0.5, 0, 3], [0, -0.5, 7], [-0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 11], [0, -0.5, 7], [0.5, 0, 5]
                ]
                self.ghost_sprites.add(player)
            elif role_name == 'Clyde':
                player = Player(319, 259, each)
                player.is_move = True
                player.tracks = [
                    [-1, 0, 2], [0, -0.5, 4], [0.5, 0, 5], [0, 0.5, 7], [-0.5, 0, 11], [0, -0.5, 7],
                    [-0.5, 0, 3], [0, 0.5, 7], [-0.5, 0, 7], [0, 0.5, 15], [0.5, 0, 15], [0, -0.5, 3],
                    [-0.5, 0, 11], [0, -0.5, 7], [0.5, 0, 3], [0, -0.5, 11], [0.5, 0, 9]
                ]
                self.ghost_sprites.add(player)
            elif role_name == 'Inky':
                player = Player(255, 259, each)
                player.is_move = True
                player.tracks = [
                    [1, 0, 2], [0, -0.5, 4], [0.5, 0, 10], [0, 0.5, 7], [0.5, 0, 3], [0, -0.5, 3],
                    [0.5, 0, 3], [0, -0.5, 15], [-0.5, 0, 15], [0, 0.5, 3], [0.5, 0, 15], [0, 0.5, 11],
                    [-0.5, 0, 3], [0, -0.5, 7], [-0.5, 0, 11], [0, 0.5, 3], [-0.5, 0, 11], [0, 0.5, 7],
                    [-0.5, 0, 3], [0, -0.5, 3], [-0.5, 0, 3], [0, -0.5, 15], [0.5, 0, 15], [0, 0.5, 3],
                    [-0.5, 0, 15], [0, 0.5, 11], [0.5, 0, 3], [0, -0.5, 11], [0.5, 0, 11], [0, 0.5, 3], [0.5, 0, 1]
                ]
                self.ghost_sprites.add(player)
            elif role_name == 'Pinky':
                player = Player(287, 259, each)
                player.is_move = True
                player.tracks = [
                    [0, -1, 4], [0.5, 0, 9], [0, 0.5, 11], [-0.5, 0, 23], [0, 0.5, 7], [0.5, 0, 3],
                    [0, -0.5, 3], [0.5, 0, 19], [0, 0.5, 3], [0.5, 0, 3], [0, 0.5, 3], [0.5, 0, 3],
                    [0, -0.5, 15], [-0.5, 0, 7], [0, 0.5, 3], [-0.5, 0, 19], [0, -0.5, 11], [0.5, 0, 9]
                ]
                self.ghost_sprites.add(player)
        return self.hero_sprites, self.ghost_sprites
    '''创建食物'''
    def setupFood(self, food_color, bg_color):
        self.food_sprites = pygame.sprite.Group()
        for row in range(19):
            for col in range(19):
                if (row == 7 or row == 8) and (col == 8 or col == 9 or col == 10):
                    continue
                else:
                    food = Food(30 * col + 32, 30 * row + 32, 4, 4, food_color, bg_color)
                    is_collide = pygame.sprite.spritecollide(food, self.wall_sprites, False)
                    if is_collide:
                        continue
                    is_collide = pygame.sprite.spritecollide(food, self.hero_sprites, False)
                    if is_collide:
                        continue
                    self.food_sprites.add(food)
        return self.food_sprites

4)主程序Game.py

import sys
import cfg
import pygame
import modules.Levels as Levels
 
 
'''开始某一关游戏'''
def startLevelGame(level, screen, font):
    clock = pygame.time.Clock()
    SCORE = 0
    wall_sprites = level.setupWalls(cfg.SKYBLUE)
    gate_sprites = level.setupGate(cfg.WHITE)
    hero_sprites, ghost_sprites = level.setupPlayers(cfg.HEROPATH, [cfg.BlinkyPATH, cfg.ClydePATH, cfg.InkyPATH, cfg.PinkyPATH])
    food_sprites = level.setupFood(cfg.YELLOW, cfg.WHITE)
    is_clearance = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(-1)
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    for hero in hero_sprites:
                        hero.changeSpeed([-1, 0])
                        hero.is_move = True
                elif event.key == pygame.K_RIGHT:
                    for hero in hero_sprites:
                        hero.changeSpeed([1, 0])
                        hero.is_move = True
                elif event.key == pygame.K_UP:
                    for hero in hero_sprites:
                        hero.changeSpeed([0, -1])
                        hero.is_move = True
                elif event.key == pygame.K_DOWN:
                    for hero in hero_sprites:
                        hero.changeSpeed([0, 1])
                        hero.is_move = True
            if event.type == pygame.KEYUP:
                if (event.key == pygame.K_LEFT) or (event.key == pygame.K_RIGHT) or (event.key == pygame.K_UP) or (event.key == pygame.K_DOWN):
                    hero.is_move = False
        screen.fill(cfg.BLACK)
        for hero in hero_sprites:
            hero.update(wall_sprites, gate_sprites)
        hero_sprites.draw(screen)
        for hero in hero_sprites:
            food_eaten = pygame.sprite.spritecollide(hero, food_sprites, True)
        SCORE += len(food_eaten)
        wall_sprites.draw(screen)
        gate_sprites.draw(screen)
        food_sprites.draw(screen)
        for ghost in ghost_sprites:
            # 幽灵随机运动(效果不好且有BUG)
            '''
            res = ghost.update(wall_sprites, None)
            while not res:
                ghost.changeSpeed(ghost.randomDirection())
                res = ghost.update(wall_sprites, None)
            '''
            # 指定幽灵运动路径
            if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
                ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
                ghost.tracks_loc[1] += 1
            else:
                if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
                    ghost.tracks_loc[0] += 1
                elif ghost.role_name == 'Clyde':
                    ghost.tracks_loc[0] = 2
                else:
                    ghost.tracks_loc[0] = 0
                ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
                ghost.tracks_loc[1] = 0
            if ghost.tracks_loc[1] < ghost.tracks[ghost.tracks_loc[0]][2]:
                ghost.changeSpeed(ghost.tracks[ghost.tracks_loc[0]][0: 2])
            else:
                if ghost.tracks_loc[0] < len(ghost.tracks) - 1:
                    loc0 = ghost.tracks_loc[0] + 1
                elif ghost.role_name == 'Clyde':
                    loc0 = 2
                else:
                    loc0 = 0
                ghost.changeSpeed(ghost.tracks[loc0][0: 2])
            ghost.update(wall_sprites, None)
        ghost_sprites.draw(screen)
        score_text = font.render("Score: %s" % SCORE, True, cfg.RED)
        screen.blit(score_text, [10, 10])
        if len(food_sprites) == 0:
            is_clearance = True
            break
        if pygame.sprite.groupcollide(hero_sprites, ghost_sprites, False, False):
            is_clearance = False
            break
        pygame.display.flip()
        clock.tick(10)
    return is_clearance
 
 
'''显示文字'''
def showText(screen, font, is_clearance, flag=False):
    clock = pygame.time.Clock()
    msg = 'Game Over!' if not is_clearance else 'Congratulations, you won!'
    positions = [[235, 233], [65, 303], [170, 333]] if not is_clearance else [[145, 233], [65, 303], [170, 333]]
    surface = pygame.Surface((400, 200))
    surface.set_alpha(10)
    surface.fill((128, 128, 128))
    screen.blit(surface, (100, 200))
    texts = [font.render(msg, True, cfg.WHITE),
            font.render('Press ENTER to continue or play again.', True, cfg.WHITE),
            font.render('Press ESCAPE to quit.', True, cfg.WHITE)]
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    if is_clearance:
                        if not flag:
                            return
                        else:
                            main(initialize())
                    else:
                        main(initialize())
                elif event.key == pygame.K_ESCAPE:
                    sys.exit()
                    pygame.quit()
        for idx, (text, position) in enumerate(zip(texts, positions)):
            screen.blit(text, position)
        pygame.display.flip()
        clock.tick(10)
 
 
'''初始化'''
def initialize():
    pygame.init()
    icon_image = pygame.image.load(cfg.ICONPATH)
    pygame.display.set_icon(icon_image)
    screen = pygame.display.set_mode([606, 606])
    pygame.display.set_caption('吃豆豆小游戏')
    return screen
 
 
'''主函数'''
def main(screen):
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.play(-1, 0.0)
    pygame.font.init()
    font_small = pygame.font.Font(cfg.FONTPATH, 18)
    font_big = pygame.font.Font(cfg.FONTPATH, 24)
    for num_level in range(1, Levels.NUMLEVELS+1):
        level = getattr(Levels, f'Level{num_level}')()
        is_clearance = startLevelGame(level, screen, font_small)
        if num_level == Levels.NUMLEVELS:
            showText(screen, font_big, is_clearance, True)
        else:
            showText(screen, font_big, is_clearance)
 
 
'''run'''
if __name__ == '__main__':
    main(initialize())

5)效果展示

总结

如果有一台时光机,你最想回到什么时候?想必不少人的答案都会是,童年。童年的无忧无

虑,童年的单纯天真,那些笑与泪的日子,放学时,三五好友嬉笑打闹的走到学校门口小卖

店,买一包糖果,边吃边走回家的时光。回忆童年让我们从游戏开始吧~

✨完整的素材源码等:可以滴滴我吖!或者点击文末hao自取免费拿的哈~

 🔨推荐往期文章——

项目1.8  Wifi破解免费

Python编程零基础如何逆袭成为爬虫实战高手之《WIFI破解》(甩万能钥匙十条街)爆赞爆赞~

项目1.9  浪漫樱花表白代码合集

【Python表白代码】你喜欢什么场景下的告白?“我途径一场樱花的绽放 想分享给你”(永不落幕的樱花代码合集)

项目1.0  图像处理系统1.0版本

【OpenCV+Tkinter项目】同学,你要的OpenCV图像处理小系统已安排,终于有人把OpenCV那些必备的知识点讲透彻了~(太厉害了,已跪)

项目1.2  学习经验分享(14张思维导图)

【学习编程】献给迷茫中的你,教你如何快速入门编程,如何从编程小百到 IT 巨佬?零基础自学请收下这份学习指南(经验分享)

项目1.1   扫雷

 Pygame实战:据说这是史上最难扫雷游戏,没有之一,你们感受下......

项目1.2   魂斗罗

Pygame实战:多年后“魂斗罗”像素风归来 不止是经典与情怀@全体成员

🎄文章汇总——

汇总合集 Python—2022 |已有文章汇总 | 持续更新,直接看这篇就够了

(更多内容+源码都在✨文章汇总哦!!欢迎阅读喜欢的文章🎉~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/415209.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Half-UNet:用于医学图像分割的简化U-Net架构

Half-UNet简化了编码器和解码器&#xff0c;还使用了Ghost模块(GhostNet)。并重新设计的体系结构&#xff0c;把通道数进行统一。 论文动机 编码器的不同类型的架构图&#xff0c;编码器(A-C)的结构分别来源于U-Net的编码器、解码器和全的Unet结构。 下面是上图的一些结果指标…

4.2学习周报

文章目录前言文献阅读摘要介绍时间序列预测目前存在的问题时间序列预测方法分类未来方向时间序列预测总结前言 本周阅读文献《Forecast Methods for Time Series Data: A Survey》&#xff0c;本文主要对目前时间序列数据建模方法进行分类&#xff0c;主要分为了三类&#xff…

Linux->文件系统磁盘文件管理

目录 1 磁盘结构 2 逻辑抽象管理磁盘 2.1 逻辑抽象 2.2 管理磁盘 2.3 补充知识 3 软硬连接 1 磁盘结构 本篇的学习需要建立在大家在脑海中有一副磁盘的结构才能进行下去&#xff0c;所以我会以图解的方式为大家简单讲解一下&#xff0c;注&#xff1a;博主对这一部分并不是…

深度学习实战——卷积神经网络/CNN实践(LeNet、Resnet)

忆如完整项目/代码详见github&#xff1a;https://github.com/yiru1225&#xff08;转载标明出处 勿白嫖 star for projects thanks&#xff09; 系列文章目录 本系列博客重点在深度学习相关实践&#xff08;有问题欢迎在评论区讨论指出&#xff0c;或直接私信联系我&#xf…

详细介绍别人电脑访问到自己电脑运行的项目

文章目录 让别人远程访问你的代码网站项目或临时演示你的项目给客户的方式详解 引言一、创建一个你想要别人访问的项目二、明确你想要将这个网站或者项目存放的地方 终端分类服务器设备WEB服务器三、部署我们的网页 本地部署流程进入浏览器输入网址访问获取本机的IP地址&#…

多模态特征融合:图像、语音、文本如何转为特征向量并进行分类

多模态特征融合前言输入层&#xff0c;数据集转为特征向量图像语音什么是时域信号&#xff0c;什么是频域信号语音信号转换 - 1.傅立叶变换语音信号转换 - 2.梅尔频率倒谱系数文本词袋模型词嵌入模型输出层&#xff0c;多模态模型合并前言 学习多模态的话题可以从深度学习的分…

API接口安全—webservice、Swagger、WEBpack

API接口安全—webservice、Swagger、WEBpack1. API接口介绍1.1. 常用的API接口类1.1.1. API接口分类1.1.1.1. 类库型API1.1.1.2. 操作系统型API1.1.1.3. 远程应用型API1.1.1.4. WEB应用型API1.1.1.5. 总结1.1.2. API接口类型1.1.2.1. HTTP类接口1.1.2.2. RPC类接口1.1.2.3. web…

NLP与ChatGPT的碰撞:大模型和小模型联合发力

ChatGPT真的太火了&#xff01;作为NLP的终结者&#xff0c;ChatGPT又会与NLP发生怎么样的碰撞&#xff1f;大模型可以替代小模型吗&#xff1f;NLP又将何去何从&#xff1f;今天给大家推荐一本好书&#xff1a;《基于NLP的内容理解》&#xff01; 文章目录一、背景二、书籍介绍…

【原创】AIGC之ChatGPT工作原理

AIGC是什么 AIGC - AI Generated Content &#xff08;AI生成内容&#xff09;&#xff0c;对应我们的过去的主要是 UGC&#xff08;User Generated Content&#xff09;和 PGC&#xff08;Professional user Generated Content&#xff09;。 AIGC就是说所有输出内容是通过AI机…

2023年3月的10篇论文推荐

三月有很多的重大产品发布&#xff0c;包括刚刚发布的GPT4&#xff0c;还有Meta刚发布就被泄露的LLaMA&#xff0c;midjourney V5&#xff0c;还有ChatGPT的API&#xff08;非常便宜&#xff09;等等。 但是本文整理的是本月应该阅读的10篇论文&#xff0c;将包括多模态语言模…

Linux中shell内外命令讲解(下)

♥️作者&#xff1a;小刘在C站 ♥️个人主页&#xff1a;小刘主页 ♥️每天分享云计算网络运维课堂笔记&#xff0c;努力不一定有收获&#xff0c;但一定会有收获加油&#xff01;一起努力&#xff0c;共赴美好人生&#xff01; ♥️夕阳下&#xff0c;是最美的绽放&#xff0…

MySQL数据库:联合查询、子句查询、合并查询

一、联合查询 1.概念 简单理解就是将多张表合并到一起&#xff0c;然后进行数据查询&#xff0c;所有也叫多表联查。 如何将两张表合并到一起&#xff1f; 取两张表的笛卡儿积&#xff1a;将表1中的数据逐条与表2中的数据进行合并&#xff0c;最终形成的新的临时表&#xff0…

py征途4之无效思路

事件回顾&#xff1a; 近期班里组织了一个跑团&#xff0c;使用的是keep跑团助手&#xff08;小程序&#xff09;。每个人都有一个昵称&#xff0c;要对“每日跑量”进行统计&#xff0c;以明确到底有哪些人跑了步&#xff0c;哪些人没跑步。 为了解决这个问题&#xff0c;从3月…

springboot登录校验[JWT]

前言&#xff1a; &#x1f44f;作者简介&#xff1a;我是笑霸final&#xff0c;一名热爱技术的在校学生。 &#x1f4dd;个人主页&#xff1a;个人主页1 || 笑霸final的主页2 &#x1f4d5;系列专栏&#xff1a;后端专栏 &#x1f4e7;如果文章知识点有错误的地方&#xff0c;…

Spring Transaction 源码解读

Spring Transaction 规范的maven坐标如下&#xff1a; <dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>...</version></dependency>该包提供了spring事务规范和默认的jta(ja…

【SSM】SSM整合步骤和流程细化

整合SSM参考文献一、SSM整合前概述1. 各个框架在三层架构模式中所担任的角色2. 两个IOC容器的创建1&#xff09;整合时Spring中IOC容器的创建时间2&#xff09;Spring提供的监听器&#xff08;ContextLoaderListener&#xff09;二、SSM整合步骤参考文献 卤蛋的SSM整合完整流程…

华为nat配置实验:内网能够访问外网,内网服务器80端口映射出去

一 需求分析1.1 需求公司A在北京&#xff0c;公司B在上海&#xff0c;本次实验仅仅模拟局域网内出口路由器的配置&#xff0c;公司A业务流量较大&#xff0c;并且预算有限。公司B模拟外网的一个小型局域网&#xff0c;要求公司B的主机能够访问公司A的web服务器。1.2 分析采用na…

Linux中滴计划任务

计划任务计划任务计划任务分类at命令load averagecrontab命令配置文件通常包含三个部分cron服务配置文件cron服务的日志文件时间数值的特殊表示方法应用实例案例anacron服务计划任务 计划任务&#xff08;Cron Job&#xff09;是指在预定的时间自动执行一些指定的任务或脚本。…

Pytorch使用预训练好的卷积神经网络进行推理预测

本小节将会介绍如何利用已经预训练好的卷积神经网络模型对一张图像进行预测&#xff0c;并且通过可视化的方法&#xff0c;查看模型是如何得到其预测结果的。 我们直接看一个实例&#xff0c;利用已经预训练好的VGG16卷积神经网络对一张图像获取一些特定层的输出&#xff0c;并…

通过python理解光的偏振

文章目录基本原理椭圆偏振光基本原理 光是横波&#xff0c;可以写成E⃗A⃗cos(ωt−k⃗r⃗)\vec E \vec{A}cos(\omega t-\vec k\vec r)EAcos(ωt−kr)&#xff0c;振动方向与传播方向垂直&#xff0c;而在三维空间中&#xff0c;与光线垂直的乃是法平面。换言之&#xff0c;光…