下篇丨月薪3w还能天天摸鱼?再整10个Python小游戏【附源码】

个人主页:互联网阿星
格言:选择有时候会大于努力,但你不努力就没得选
简介:大家好我是互联网阿星,和我一起合理使用Python,努力做时间的主人
如果觉得博主的文章还不错,请点赞+收藏⭐️+留言支持一下博主

下篇丨月薪3w还能天天摸鱼?再整10个Python小游戏【附源码】_第1张图片
行业资料:PPT模板、简历模板、行业经典书籍PDF
面试题库:历年经典、热乎的大厂面试真题,持续更新…
学习资料:Python、爬虫、数据分析、算法等学习视频和文档
Tips:以上资料+全套游戏源码阿星已备好>>戳我,空投直达


Python小游戏·目录

  • 前言
  • 10套Python小游戏
    • 小游戏1:飞机大战
    • 小游戏2:吃金币游戏
    • 小游戏3:24点小游戏
    • 小游戏4:打乒乓(单/双人)
    • 小游戏5:小恐龙跳一跳
    • 小游戏6:控制平衡木
    • 小游戏7:超级炸弹人
    • 小游戏8:保卫森林塔防
    • 小游戏9:吃饭睡觉打豆豆
    • 小游戏10:水果忍者切水果
  • 小结


前言

昨天,阿星给大家带来18个Python小游戏,有老铁觉得游戏难度有点大了吖。今天,阿星就整上10套轻松休闲的Python小游戏,这波必须得⭐️收藏起来

小游戏的全套源码戳我,空投直达拿来就能玩爽歪歪

话不多说,今日份的Python小游戏,ta来了

10套Python小游戏

小游戏1:飞机大战

玩法:支持单双人模式,控制飞机躲避障碍物

源码分享

 
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()
    # 产生小行星的时间间隔
    asteroid_ticks = 90
    for i in range(num_player):
        player_group.add(Ship(i+1, cfg))
    clock = pygame.time.Clock()
    # 分数
    score_1, score_2 = 0, 0
    # 游戏主循环
    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
        # --向下移动背景图实现飞船向上移动的效果
        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)
        # --显示分数
        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)
 
 
'''主函数'''
def main():
    pygame.init()
    pygame.font.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('飞机大战 —— 九歌')
    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)
 
 
'''run'''
if __name__ == '__main__':
    main()

还有游戏图片素材等,全套游戏源码已备好戳我,空投直达

小游戏2:吃金币游戏

玩法:在倒计时结束前,控制底部小人物吃到金币,和阿星的比一下,看你能玩到多少分

源码分享

import os
import cfg
import sys
import pygame
import random
from modules import *
 
 
'''游戏初始化'''
def initGame():
    # 初始化pygame, 设置展示窗口
    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)
    # 返回初始化数据
    return screen, game_images, game_sounds
 
 
'''主函数'''
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
    # 当前分数/历史最高分
    score = 0
    highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
    # 游戏主循环
    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)
        # --判断游戏是否结束
        if pygame.time.get_ticks() >= 90000:
            break
        # --更新屏幕
        pygame.display.flip()
        clock.tick(cfg.FPS)
    # 游戏结束, 记录最高分并显示游戏结束画面
    fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
    fp.write(str(highest_score))
    fp.close()
    return showEndGameInterface(screen, cfg, score, highest_score)
 
 
'''run'''
if __name__ == '__main__':
    while main():
        pass

还有游戏图片素材等,全套游戏源码已备好戳我,空投直达

小游戏3:24点小游戏

玩法:将给出的数字通过加减乘除凑成24点

源码分享

 
import os
import sys
import pygame
from cfg import *
from modules import *
from fractions import Fraction
 
 
'''检查控件是否被点击'''
def checkClicked(group, mouse_pos, group_type='NUMBER'):
    selected = []
    # 数字卡片/运算符卡片
    if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]:
        max_selected = 2 if group_type == GROUPTYPES[0] else 1
        num_selected = 0
        for each in group:
            num_selected += int(each.is_selected)
        for each in group:
            if each.rect.collidepoint(mouse_pos):
                if each.is_selected:
                    each.is_selected = not each.is_selected
                    num_selected -= 1
                    each.select_order = None
                else:
                    if num_selected < max_selected:
                        each.is_selected = not each.is_selected
                        num_selected += 1
                        each.select_order = str(num_selected)
            if each.is_selected:
                selected.append(each.attribute)
    # 按钮卡片
    elif group_type == GROUPTYPES[2]:
        for each in group:
            if each.rect.collidepoint(mouse_pos):
                each.is_selected = True
                selected.append(each.attribute)
    # 抛出异常
    else:
        raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES))
    return selected
 
 
'''获取数字精灵组'''
def getNumberSpritesGroup(numbers):
    number_sprites_group = pygame.sprite.Group()
    for idx, number in enumerate(numbers):
        args = (*NUMBERCARD_POSITIONS[idx], str(number), NUMBERFONT, NUMBERFONT_COLORS, NUMBERCARD_COLORS, str(number))
        number_sprites_group.add(Card(*args))
    return number_sprites_group
 
 
'''获取运算符精灵组'''
def getOperatorSpritesGroup(operators):
    operator_sprites_group = pygame.sprite.Group()
    for idx, operator in enumerate(operators):
        args = (*OPERATORCARD_POSITIONS[idx], str(operator), OPERATORFONT, OPREATORFONT_COLORS, OPERATORCARD_COLORS, str(operator))
        operator_sprites_group.add(Card(*args))
    return operator_sprites_group
 
 
'''获取按钮精灵组'''
def getButtonSpritesGroup(buttons):
    button_sprites_group = pygame.sprite.Group()
    for idx, button in enumerate(buttons):
        args = (*BUTTONCARD_POSITIONS[idx], str(button), BUTTONFONT, BUTTONFONT_COLORS, BUTTONCARD_COLORS, str(button))
        button_sprites_group.add(Button(*args))
    return button_sprites_group
 
 
'''计算'''
def calculate(number1, number2, operator):
    operator_map = {'+': '+', '-': '-', '×': '*', '÷': '/'}
    try:
        result = str(eval(number1+operator_map[operator]+number2))
        return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))
    except:
        return None
 
 
'''在屏幕上显示信息'''
def showInfo(text, screen):
    rect = pygame.Rect(200, 180, 400, 200)
    pygame.draw.rect(screen, PAPAYAWHIP, rect)
    font = pygame.font.Font(FONTPATH, 40)
    text_render = font.render(text, True, BLACK)
    font_size = font.size(text)
    screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2))
 
 
'''主函数'''
def main():
    # 初始化, 导入必要的游戏素材
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(SCREENSIZE)
    pygame.display.set_caption('24 point —— 九歌')
    win_sound = pygame.mixer.Sound(AUDIOWINPATH)
    lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
    warn_sound = pygame.mixer.Sound(AUDIOWARNPATH)
    pygame.mixer.music.load(BGMPATH)
    pygame.mixer.music.play(-1, 0.0)
    # 24点游戏生成器
    game24_gen = game24Generator()
    game24_gen.generate()
    # 精灵组
    # --数字
    number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
    # --运算符
    operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
    # --按钮
    button_sprites_group = getButtonSpritesGroup(BUTTONS)
    # 游戏主循环
    clock = pygame.time.Clock()
    selected_numbers = []
    selected_operators = []
    selected_buttons = []
    is_win = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(-1)
            elif event.type == pygame.MOUSEBUTTONUP:
                mouse_pos = pygame.mouse.get_pos()
                selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER')
                selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR')
                selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON')
        screen.fill(AZURE)
        # 更新数字
        if len(selected_numbers) == 2 and len(selected_operators) == 1:
            noselected_numbers = []
            for each in number_sprites_group:
                if each.is_selected:
                    if each.select_order == '1':
                        selected_number1 = each.attribute
                    elif each.select_order == '2':
                        selected_number2 = each.attribute
                    else:
                        raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order)
                else:
                    noselected_numbers.append(each.attribute)
                each.is_selected = False
            for each in operator_sprites_group:
                each.is_selected = False
            result = calculate(selected_number1, selected_number2, *selected_operators)
            if result is not None:
                game24_gen.numbers_now = noselected_numbers + [result]
                is_win = game24_gen.check()
                if is_win:
                    win_sound.play()
                if not is_win and len(game24_gen.numbers_now) == 1:
                    lose_sound.play()
            else:
                warn_sound.play()
            selected_numbers = []
            selected_operators = []
            number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
        # 精灵都画到screen上
        for each in number_sprites_group:
            each.draw(screen, pygame.mouse.get_pos())
        for each in operator_sprites_group:
            each.draw(screen, pygame.mouse.get_pos())
        for each in button_sprites_group:
            if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']:
                is_win = False
            if selected_buttons and each.attribute == selected_buttons[0]:
                each.is_selected = False
                number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group)
                selected_buttons = []
            each.draw(screen, pygame.mouse.get_pos())
        # 游戏胜利
        if is_win:
            showInfo('Congratulations', screen)
        # 游戏失败
        if not is_win and len(game24_gen.numbers_now) == 1:
            showInfo('Game Over', screen)
        pygame.display.flip()
        clock.tick(30)
 
 
'''run'''
if __name__ == '__main__':
    main()

还有游戏图片素材等,全套游戏源码已备好戳我,空投直达

小游戏4:打乒乓(单/双人)

玩法:控制滑块接住乒乓球
下篇丨月薪3w还能天天摸鱼?再整10个Python小游戏【附源码】_第2张图片
源码分享

 
import sys
import cfg
import pygame
from modules import *
 
 
'''定义按钮'''
def Button(screen, position, text, button_size=(200, 50)):
    left, top = position
    bwidth, bheight = button_size
    pygame.draw.line(screen, (150, 150, 150), (left, top), (left+bwidth, top), 5)
    pygame.draw.line(screen, (150, 150, 150), (left, top-2), (left, top+bheight), 5)
    pygame.draw.line(screen, (50, 50, 50), (left, top+bheight), (left+bwidth, top+bheight), 5)
    pygame.draw.line(screen, (50, 50, 50), (left+bwidth, top+bheight), (left+bwidth, top), 5)
    pygame.draw.rect(screen, (100, 100, 100), (left, top, bwidth, bheight))
    font = pygame.font.Font(cfg.FONTPATH, 30)
    text_render = font.render(text, 1, (255, 235, 205))
    return screen.blit(text_render, (left+50, top+10))
 
 
'''
Function:
    开始界面
Input:
    --screen: 游戏界面
Return:
    --game_mode: 1(单人模式)/2(双人模式)
'''
def startInterface(screen):
    clock = pygame.time.Clock()
    while True:
        screen.fill((41, 36, 33))
        button_1 = Button(screen, (150, 175), '1 Player')
        button_2 = Button(screen, (150, 275), '2 Player')
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if button_1.collidepoint(pygame.mouse.get_pos()):
                    return 1
                elif button_2.collidepoint(pygame.mouse.get_pos()):
                    return 2
        clock.tick(10)
        pygame.display.update()
 
 
'''结束界面'''
def endInterface(screen, score_left, score_right):
    clock = pygame.time.Clock()
    font1 = pygame.font.Font(cfg.FONTPATH, 30)
    font2 = pygame.font.Font(cfg.FONTPATH, 20)
    msg = 'Player on left won!' if score_left > score_right else 'Player on right won!'
    texts = [font1.render(msg, True, cfg.WHITE),
            font2.render('Press ESCAPE to quit.', True, cfg.WHITE),
            font2.render('Press ENTER to continue or play again.', True, cfg.WHITE)]
    positions = [[120, 200], [155, 270], [80, 300]]
    while True:
        screen.fill((41, 36, 33))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RETURN:
                    return
                elif event.key == pygame.K_ESCAPE:
                    sys.exit()
                    pygame.quit()
        for text, pos in zip(texts, positions):
            screen.blit(text, pos)
        clock.tick(10)
        pygame.display.update()
 
 
'''运行游戏Demo'''
def runDemo(screen):
    # 加载游戏素材
    hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
    goal_sound = pygame.mixer.Sound(cfg.GOALSOUNDPATH)
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.play(-1, 0.0)
    font = pygame.font.Font(cfg.FONTPATH, 50)
    # 开始界面
    game_mode = startInterface(screen)
    # 游戏主循环
    # --左边球拍(ws控制, 仅双人模式时可控制)
    score_left = 0
    racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)
    # --右边球拍(↑↓控制)
    score_right = 0
    racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)
    # --球
    ball = Ball(cfg.BALLPICPATH, cfg)
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(-1)
        screen.fill((41, 36, 33))
        # 玩家操作
        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.K_UP]:
            racket_right.move('UP')
        elif pressed_keys[pygame.K_DOWN]:
            racket_right.move('DOWN')
        if game_mode == 2:
            if pressed_keys[pygame.K_w]:
                racket_left.move('UP')
            elif pressed_keys[pygame.K_s]:
                racket_left.move('DOWN')
        else:
            racket_left.automove(ball)
        # 球运动
        scores = ball.move(ball, racket_left, racket_right, hit_sound, goal_sound)
        score_left += scores[0]
        score_right += scores[1]
        # 显示
        # --分隔线
        pygame.draw.rect(screen, cfg.WHITE, (247, 0, 6, 500))
        # --球
        ball.draw(screen)
        # --拍
        racket_left.draw(screen)
        racket_right.draw(screen)
        # --得分
        screen.blit(font.render(str(score_left), False, cfg.WHITE), (150, 10))
        screen.blit(font.render(str(score_right), False, cfg.WHITE), (300, 10))
        if score_left == 11 or score_right == 11:
            return score_left, score_right
        clock.tick(100)
        pygame.display.update()
 
 
'''主函数'''
def main():
    # 初始化
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))
    pygame.display.set_caption('pingpong —— 九歌')
    # 开始游戏
    while True:
        score_left, score_right = runDemo(screen)
        endInterface(screen, score_left, score_right)
 
 
'''run'''
if __name__ == '__main__':
    main()

还有游戏图片素材等,全套游戏源码已备好戳我,空投直达

小游戏5:小恐龙跳一跳

玩法:控制小恐龙上下起跳躲避,速度挺快看你能撑多少秒

源码分享

 
import cfg
import sys
import random
import pygame
from modules import *
 
 
'''main'''
def main(highest_score):
    # 游戏初始化
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('九歌')
    # 导入所有声音文件
    sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        sounds[key] = pygame.mixer.Sound(value)
    # 游戏开始界面
    GameStartInterface(screen, sounds, cfg)
    # 定义一些游戏中必要的元素和变量
    score = 0
    score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR)
    highest_score = highest_score
    highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True)
    dino = Dinosaur(cfg.IMAGE_PATHS['dino'])
    ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1]))
    cloud_sprites_group = pygame.sprite.Group()
    cactus_sprites_group = pygame.sprite.Group()
    ptera_sprites_group = pygame.sprite.Group()
    add_obstacle_timer = 0
    score_timer = 0
    # 游戏主循环
    clock = pygame.time.Clock()
    while True:
        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_SPACE or event.key == pygame.K_UP:
                    dino.jump(sounds)
                elif event.key == pygame.K_DOWN:
                    dino.duck()
            elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
                dino.unduck()
        screen.fill(cfg.BACKGROUND_COLOR)
        # --随机添加云
        if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10:
            cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75))))
        # --随机添加仙人掌/飞龙
        add_obstacle_timer += 1
        if add_obstacle_timer > random.randrange(50, 150):
            add_obstacle_timer = 0
            random_value = random.randrange(0, 10)
            if random_value >= 5 and random_value <= 7:
                cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti']))
            else:
                position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20]
                ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys))))
        # --更新游戏元素
        dino.update()
        ground.update()
        cloud_sprites_group.update()
        cactus_sprites_group.update()
        ptera_sprites_group.update()
        score_timer += 1
        if score_timer > (cfg.FPS//12):
            score_timer = 0
            score += 1
            score = min(score, 99999)
            if score > highest_score:
                highest_score = score
            if score % 100 == 0:
                sounds['point'].play()
            if score % 1000 == 0:
                ground.speed -= 1
                for item in cloud_sprites_group:
                    item.speed -= 1
                for item in cactus_sprites_group:
                    item.speed -= 1
                for item in ptera_sprites_group:
                    item.speed -= 1
        # --碰撞检测
        for item in cactus_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        for item in ptera_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        # --将游戏元素画到屏幕上
        dino.draw(screen)
        ground.draw(screen)
        cloud_sprites_group.draw(screen)
        cactus_sprites_group.draw(screen)
        ptera_sprites_group.draw(screen)
        score_board.set(score)
        highest_score_board.set(highest_score)
        score_board.draw(screen)
        highest_score_board.draw(screen)
        # --更新屏幕
        pygame.display.update()
        clock.tick(cfg.FPS)
        # --游戏是否结束
        if dino.is_dead:
            break
    # 游戏结束界面
    return GameEndInterface(screen, cfg), highest_score
 
 
'''run'''
if __name__ == '__main__':
    highest_score = 0
    while True:
        flag, highest_score = main(highest_score)
        if not flag: break

还有游戏图片素材等,全套游戏源码已备好戳我,空投直达

小游戏6:控制平衡木

玩法:小时候的经典游戏,控制左右就行,到后面才有一点点难度

源码分享

 
import cfg
from modules import breakoutClone
 
 
'''主函数'''
def main():
    game = breakoutClone(cfg)
    game.run()
 
 
'''run'''
if __name__ == '__main__':
    main()

还有配置文件戳我,空投直达

小游戏7:超级炸弹人

体验:小时候的又一经典游戏,小时候很多次都被自己炸死了


游戏源码(含配置文件、图片素材等)拿来就能玩戳我,空投直达

小游戏8:保卫森林塔防

玩法:类似保卫萝卜,塔防类的小游戏,布局一定要合理,考虑射程属性等等

下篇丨月薪3w还能天天摸鱼?再整10个Python小游戏【附源码】_第3张图片
整套游戏源码已备好,拿来就能玩戳我,空投直达

小游戏9:吃饭睡觉打豆豆

体验:考验手速和操作和走位,打开这个游戏,阿星仿佛感觉到我的鼠标在颤抖

下篇丨月薪3w还能天天摸鱼?再整10个Python小游戏【附源码】_第4张图片
源码已备好,拿来就能玩戳我,空投直达

小游戏10:水果忍者切水果

体验:切水果风靡一时的游戏,不知道为啥总是切到炸弹挺解压的游戏


爽歪歪整套源码已备好,拿来就能玩戳我,空投直达


小结


学习资料:含Python、爬虫、数据分析、算法等学习视频和文档
行业资料:添加即可领取PPT模板、简历模板、行业经典书籍PDF
面试题库:历年经典,热乎的大厂面试真题,持续更新中…
阿星的资料已备好,戳文末名片领…


以上学习资料+全套源码+玩法详解‍戳名片领

下篇丨月薪3w还能天天摸鱼?再整10个Python小游戏【附源码】_第5张图片

你可能感兴趣的:(python,pygame,pycharm,游戏程序,python小游戏)