百木园-与人分享,
就是让自己快乐。

用Python制作小游戏,上班摸鱼能玩一天【内附源码】

1、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()

 

2、保卫森林

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

 
 

 

 

3、平衡木

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

 

 

源码分享:

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

4、外星人入侵

玩法:这让我想起了魂斗罗那第几关的boss,有点类似,不过魂斗罗那个难度肯定高点。

 

 

 

源码分享:

 
import os
import sys
import cfg
import random
import pygame
from modules import *
 
 
\'\'\'开始游戏\'\'\'
def startGame(screen):
    clock = pygame.time.Clock()
    # 加载字体
    font = pygame.font.SysFont(\'arial\', 18)
    if not os.path.isfile(\'score\'):
        f = open(\'score\', \'w\')
        f.write(\'0\')
        f.close()
    with open(\'score\', \'r\') as f:
        highest_score = int(f.read().strip())
    # 敌方
    enemies_group = pygame.sprite.Group()
    for i in range(55):
        if i < 11:
            enemy = enemySprite(\'small\', i, cfg.WHITE, cfg.WHITE)
        elif i < 33:
            enemy = enemySprite(\'medium\', i, cfg.WHITE, cfg.WHITE)
        else:
            enemy = enemySprite(\'large\', i, cfg.WHITE, cfg.WHITE)
        enemy.rect.x = 85 + (i % 11) * 50
        enemy.rect.y = 120 + (i // 11) * 45
        enemies_group.add(enemy)
    boomed_enemies_group = pygame.sprite.Group()
    en_bullets_group = pygame.sprite.Group()
    ufo = ufoSprite(color=cfg.RED)
    # 我方
    myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)
    my_bullets_group = pygame.sprite.Group()
    # 用于控制敌方位置更新
    # --移动一行
    enemy_move_count = 24
    enemy_move_interval = 24
    enemy_move_flag = False
    # --改变移动方向(改变方向的同时集体下降一次)
    enemy_change_direction_count = 0
    enemy_change_direction_interval = 60
    enemy_need_down = False
    enemy_move_right = True
    enemy_need_move_row = 6
    enemy_max_row = 5
    # 用于控制敌方发射子弹
    enemy_shot_interval = 100
    enemy_shot_count = 0
    enemy_shot_flag = False
    # 游戏进行中
    running = True
    is_win = False
    # 主循环
    while running:
        screen.fill(cfg.BLACK)
        for event in pygame.event.get():
            # --点右上角的X或者按Esc键退出游戏
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            # --射击
            if event.type == pygame.MOUSEBUTTONDOWN:
                my_bullet = myaircraft.shot()
                if my_bullet:
                    my_bullets_group.add(my_bullet)
        # --我方子弹与敌方/UFO碰撞检测
        for enemy in enemies_group:
            if pygame.sprite.spritecollide(enemy, my_bullets_group, True, None):
                boomed_enemies_group.add(enemy)
                enemies_group.remove(enemy)
                myaircraft.score += enemy.reward
        if pygame.sprite.spritecollide(ufo, my_bullets_group, True, None):
            ufo.is_dead = True
            myaircraft.score += ufo.reward
        # --更新并画敌方
        # ----敌方子弹
        enemy_shot_count += 1
        if enemy_shot_count > enemy_shot_interval:
            enemy_shot_flag = True
            enemies_survive_list = [enemy.number for enemy in enemies_group]
            shot_number = random.choice(enemies_survive_list)
            enemy_shot_count = 0
        # ----敌方移动
        enemy_move_count += 1
        if enemy_move_count > enemy_move_interval:
            enemy_move_count = 0
            enemy_move_flag = True
            enemy_need_move_row -= 1
            if enemy_need_move_row == 0:
                enemy_need_move_row = enemy_max_row
            enemy_change_direction_count += 1
            if enemy_change_direction_count > enemy_change_direction_interval:
                enemy_change_direction_count = 1
                enemy_move_right = not enemy_move_right
                enemy_need_down = True
                # ----每次下降提高移动和射击速度
                enemy_move_interval = max(15, enemy_move_interval-3)
                enemy_shot_interval = max(50, enemy_move_interval-10)
        # ----遍历更新
        for enemy in enemies_group:
            if enemy_shot_flag:
                if enemy.number == shot_number:
                    en_bullet = enemy.shot()
                    en_bullets_group.add(en_bullet)
            if enemy_move_flag:
                if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):
                    if enemy_move_right:
                        enemy.update(\'right\', cfg.SCREENSIZE[1])
                    else:
                        enemy.update(\'left\', cfg.SCREENSIZE[1])
            else:
                enemy.update(None, cfg.SCREENSIZE[1])
            if enemy_need_down:
                if enemy.update(\'down\', cfg.SCREENSIZE[1]):
                    running = False
                    is_win = False
                enemy.change_count -= 1
            enemy.draw(screen)
        enemy_move_flag = False
        enemy_need_down = False
        enemy_shot_flag = False
        # ----敌方爆炸特效
        for boomed_enemy in boomed_enemies_group:
            if boomed_enemy.boom(screen):
                boomed_enemies_group.remove(boomed_enemy)
                del boomed_enemy
        # --敌方子弹与我方飞船碰撞检测
        if not myaircraft.one_dead:
            if pygame.sprite.spritecollide(myaircraft, en_bullets_group, True, None):
                myaircraft.one_dead = True
        if myaircraft.one_dead:
            if myaircraft.boom(screen):
                myaircraft.resetBoom()
                myaircraft.num_life -= 1
                if myaircraft.num_life < 1:
                    running = False
                    is_win = False
        else:
            # ----更新飞船
            myaircraft.update(cfg.SCREENSIZE[0])
            # ----画飞船
            myaircraft.draw(screen)
        if (not ufo.has_boomed) and (ufo.is_dead):
            if ufo.boom(screen):
                ufo.has_boomed = True
        else:
            # ----更新UFO
            ufo.update(cfg.SCREENSIZE[0])
            # ----画UFO
            ufo.draw(screen)
        # --画我方飞船子弹
        for bullet in my_bullets_group:
            if bullet.update():
                my_bullets_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        # --画敌方子弹
        for bullet in en_bullets_group:
            if bullet.update(cfg.SCREENSIZE[1]):
                en_bullets_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        if myaircraft.score > highest_score:
            highest_score = myaircraft.score
        # --得分每增加2000我方飞船增加一条生命
        if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old_score):
            myaircraft.old_score = myaircraft.score
            myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)
        # --敌人都死光了的话就胜利了
        if len(enemies_group) < 1:
            is_win = True
            running = False
        # --显示文字
        # ----当前得分
        showText(screen, \'SCORE: \', cfg.WHITE, font, 200, 8)
        showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)
        # ----敌人数量
        showText(screen, \'ENEMY: \', cfg.WHITE, font, 370, 8)
        showText(screen, str(len(enemies_group)), cfg.WHITE, font, 370, 24)
        # ----历史最高分
        showText(screen, \'HIGHEST: \', cfg.WHITE, font, 540, 8)
        showText(screen, str(highest_score), cfg.WHITE, font, 540, 24)
        # ----FPS
        showText(screen, \'FPS: \' + str(int(clock.get_fps())), cfg.RED, font, 8, 8)
        # --显示剩余生命值
        showLife(screen, myaircraft.num_life, cfg.GREEN)
        pygame.display.update()
        clock.tick(cfg.FPS)
    with open(\'score\', \'w\') as f:
        f.write(str(highest_score))
    return is_win
 
 
\'\'\'主函数\'\'\'
def main():
    # 初始化
    pygame.init()
    pygame.display.set_caption(\'外星人入侵 —— 九歌\')
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    while True:
        is_win = startGame(screen)
        endInterface(screen, cfg.BLACK, is_win)
  Python学习群:748989764
 
\'\'\'run\'\'\'
if __name__ == \'__main__\':
    main()

5、炸弹人

玩法详解:小时候的又一经典游戏,小时候很多次都被自己炸死了。

 

 

 

6、五子棋

玩法详解:小时候很爱玩,先出是有必胜方法的,后面才知道会有禁手这个规则,就比较复杂了,大家可以学一下先出必胜的开局,有浦月、流星、丘月、游星、慧星等等。

 

 

7、坦克大战

玩法详解:这是经典中的经典,我喜欢玩双人模式,后面有一些改版的模式,这是我觉得少数几个现在玩都不过时的游戏。

 

 

8、超级玛丽

玩法详解:经典中的经典,小时候玩觉得可难了,操作不必介绍了吧。

 

9、水果忍者

玩法详解:切水果风靡一时的游戏,不知道为啥总是切刀炸掉,挺解压的游戏。

 

 

10、推箱子

攻略大全:以前的那个手机上都有的游戏,越推到后面的关卡越难,我好像是玩到二十多关就玩不下去了。

 

11、最强游戏

游戏体验:可太难控制了。

 

 


来源:https://www.cnblogs.com/tuixiulaozhou/p/16759672.html
本站部分图文来源于网络,如有侵权请联系删除。

未经允许不得转载:百木园 » 用Python制作小游戏,上班摸鱼能玩一天【内附源码】

相关推荐

  • 暂无文章