编程小游戏制作植物僵尸,编程小游戏教程视频

这篇具有很好参考价值的文章主要介绍了编程小游戏制作植物僵尸,编程小游戏教程视频。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

大家好,给大家分享一下编程小游戏植物大战僵尸,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

大家好,今天给大家带来30个 Python 小游戏,喜欢记得点赞、一定要收藏!

文章目录
    • 有手就行
      • 1、吃金币
      • 2、打乒乓
      • 3、滑雪
      • 4、并夕夕版飞机大战
      • 5、打地鼠
    • 简简单单
      • 6、小恐龙
      • 7、消消乐
      • 8、俄罗斯方块
      • 9、贪吃蛇
    • 普普通通
      • 10、24点小游戏
      • 11、平衡木
      • 12、外星人入侵
      • 13、贪心鸟
      • 14、井字棋888
    • 有点困难
      • 15、炸弹人
      • 16、保卫森林
      • 17、五子棋
      • 18、吃豆豆
      • 19、坦克大战
      • 20、超级玛丽
      • 21、水果忍者
    • 极度困难
      • 22、飞机大战
      • 23、2048
      • 24、推箱子
      • 25、塔防
      • 26、植物大战僵尸
      • 27、扫雷
    • 终极挑战
      • 28、拼图
      • 29、走迷宫
      • 30、最强游戏

有手就行

1、吃金币

【有手就行系列不介绍玩法了+附源码】

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('catch coins —— 九歌')

    for key, value in cfg.IMAGE_PATHS.items():

        if isinstance(value, list):

            for item in value: images.append(pygame.image.load(item))

            game_images[key] = images

            game_images[key] = pygame.image.load(value)

    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

    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(game_images['hero'], position=(375, 520))

    food_sprites_group = pygame.sprite.Group()

    generate_food_freq = random.randint(10, 20)

    generate_food_count = 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()

        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.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:

        pygame.display.flip()

        clock.tick(cfg.FPS)

    # 游戏结束, 记录最高分并显示游戏结束画面

    fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')

    fp.write(str(highest_score))

    return showEndGameInterface(screen, cfg, score, highest_score)

if __name__ == '__main__':
2、打乒乓

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

def Button(screen, position, text, button_size=(200, 50)):

    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))

    --game_mode: 1(单人模式)/2(双人模式)

def startInterface(screen):

    clock = pygame.time.Clock()

        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

        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]]

        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)

        pygame.display.update()

    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控制, 仅双人模式时可控制)

    racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)

    racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)

    ball = Ball(cfg.BALLPICPATH, cfg)

    clock = pygame.time.Clock()

        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')

            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

        pygame.display.update()

    screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))

    pygame.display.set_caption('pingpong —— 九歌')

        score_left, score_right = runDemo(screen)

        endInterface(screen, score_left, score_right)

if __name__ == '__main__':
3、滑雪

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

class SkierClass(pygame.sprite.Sprite):

        pygame.sprite.Sprite.__init__(self)

        self.direction = 0

        self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]

        self.image = pygame.image.load(self.imagepaths[self.direction])

        self.rect = self.image.get_rect()

        self.rect.center = [320, 100]

        self.speed = [self.direction, 6-abs(self.direction)*2]

    '''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''

        self.direction += num

        self.direction = max(-2, self.direction)

        self.direction = min(2, self.direction)

        center = self.rect.center

        self.image = pygame.image.load(self.imagepaths[self.direction])

        self.rect = self.image.get_rect()

        self.rect.center = center

        self.speed = [self.direction, 6-abs(self.direction)*2]

        return self.speed

        self.rect.centerx += self.speed[0]

        self.rect.centerx = max(20, self.rect.centerx)

        self.rect.centerx = min(620, self.rect.centerx)

        self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])

    def setForward(self):

        self.direction = 0

        self.image = pygame.image.load(self.imagepaths[self.direction])

class ObstacleClass(pygame.sprite.Sprite):

    def __init__(self, img_path, location, attribute):

        pygame.sprite.Sprite.__init__(self)

        self.img_path = img_path

        self.image = pygame.image.load(self.img_path)

        self.location = location

        self.rect = self.image.get_rect()

        self.rect.center = self.location

        self.attribute = attribute

        self.passed = False

        self.rect.centery = self.location[1] - num

def createObstacles(s, e, num=10):

    obstacles = pygame.sprite.Group()

        row = random.randint(s, e)

        col = random.randint(0, 9)

        location  = [col*64+20, row*64+20]

        if location not in locations:

            locations.append(location)

            attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))

            img_path = cfg.OBSTACLE_PATHS[attribute]

            obstacle = ObstacleClass(img_path, location, attribute)

            obstacles.add(obstacle)

def AddObstacles(obstacles0, obstacles1):

    obstacles = pygame.sprite.Group()

    for obstacle in obstacles0:

        obstacles.add(obstacle)

    for obstacle in obstacles1:

        obstacles.add(obstacle)

def ShowStartInterface(screen, screensize):

    screen.fill((255, 255, 255))

    tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)

    cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)

    title = tfont.render(u'滑雪游戏', True, (255, 0, 0))

    content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))

    trect = title.get_rect()

    trect.midtop = (screensize[0]/2, screensize[1]/5)

    crect = content.get_rect()

    crect.midtop = (screensize[0]/2, screensize[1]/2)

    screen.blit(title, trect)

    screen.blit(content, crect)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

        pygame.display.update()

def showScore(screen, score, pos=(10, 10)):

    font = pygame.font.Font(cfg.FONTPATH, 30)

    score_text = font.render("Score: %s" % score, True, (0, 0, 0))

    screen.blit(score_text, pos)

def updateFrame(screen, obstacles, skier, score):

    screen.fill((255, 255, 255))

    obstacles.draw(screen)

    screen.blit(skier.image, skier.rect)

    showScore(screen, score)

    pygame.display.update()

    pygame.mixer.music.load(cfg.BGMPATH)

    pygame.mixer.music.set_volume(0.4)

    pygame.mixer.music.play(-1)

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('滑雪游戏 —— 九歌')

    ShowStartInterface(screen, cfg.SCREENSIZE)

    obstacles0 = createObstacles(20, 29)

    obstacles1 = createObstacles(10, 19)

    obstacles = AddObstacles(obstacles0, obstacles1)

    clock = pygame.time.Clock()

        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_LEFT or event.key == pygame.K_a:

                    speed = skier.turn(-1)

                elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:

                    speed = skier.turn(1)

        distance += speed[1]

        if distance >= 640 and obstaclesflag == 0:

            obstaclesflag = 1

            obstacles0 = createObstacles(20, 29)

            obstacles = AddObstacles(obstacles0, obstacles1)

        if distance >= 1280 and obstaclesflag == 1:

            obstaclesflag = 0

            distance -= 1280

            for obstacle in obstacles0:

                obstacle.location[1] = obstacle.location[1] - 1280

            obstacles1 = createObstacles(10, 19)

            obstacles = AddObstacles(obstacles0, obstacles1)

        for obstacle in obstacles:

            obstacle.move(distance)

        hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)

        if hitted_obstacles:

            if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:

                score -= 50

                skier.setFall()

                updateFrame(screen, obstacles, skier, score)

                pygame.time.delay(1000)

                skier.setForward()

                speed = [0, 6]

                hitted_obstacles[0].passed = True

            elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:

                score += 10

                obstacles.remove(hitted_obstacles[0])

        updateFrame(screen, obstacles, skier, score)

        clock.tick(cfg.FPS)

if __name__ == '__main__':
4、并夕夕版飞机大战

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

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_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()

    for i in range(num_player):

        player_group.add(Ship(i+1, cfg))

    clock = pygame.time.Clock()

    score_1, score_2 = 0, 0

        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 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

            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))

            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

                    player.explode(screen)

                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

                    score_2 += 1

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

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('飞机大战 —— 九歌')

    num_player = StartInterface(screen, cfg)

            GamingInterface(num_player=1, screen=screen)

            EndInterface(screen, cfg)

            GamingInterface(num_player=2, screen=screen)

            EndInterface(screen, cfg)

if __name__ == '__main__':
5、打地鼠

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('打地鼠 —— 九歌')

    pygame.mixer.music.load(cfg.BGM_PATH)

    pygame.mixer.music.play(-1)

        '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()

    init_time = pygame.time.get_ticks()

        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.setPosition(hole_pos)

            pygame.time.set_timer(change_hole_event, 650)

        elif time_remain == 20 and flag:

            hole_pos = random.choice(cfg.HOLE_POSITIONS)

            mole.setPosition(hole_pos)

            pygame.time.set_timer(change_hole_event, 500)

        if time_remain == 10:

            audios['count_down'].play()

        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

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

    # 读取最佳分数(try块避免第一次游戏无.rec文件)

        best_score = int(open(cfg.RECORD_PATH).read())

    if your_score > best_score:

        f = open(cfg.RECORD_PATH, 'w')

        f.write(str(your_score))

    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)

if __name__ == '__main__':

        is_restart = main()

        if not is_restart:

简简单单

【简单介绍一下玩法+附源码】

6、小恐龙

玩法:上下控制起跳躲避

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('九歌')

    for key, value in cfg.AUDIO_PATHS.items():

        sounds[key] = pygame.mixer.Sound(value)

    GameStartInterface(screen, sounds, cfg)

    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

    clock = pygame.time.Clock()

        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']))

                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))))

        cloud_sprites_group.update()

        cactus_sprites_group.update()

        ptera_sprites_group.update()

        if score_timer > (cfg.FPS//12):

            score_timer = 0

            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)

    return GameEndInterface(screen, cfg), highest_score

if __name__ == '__main__':

        flag, highest_score = main(highest_score)

        if not flag: break
7、消消乐

玩法:三个相连就能消除

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('Gemgem —— 九歌')

    pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))

    pygame.mixer.music.set_volume(0.6)

    pygame.mixer.music.play(-1)

    sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))

        sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))

    font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)

    for i in range(1, 8):

        gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))

    game = gemGame(screen, sounds, font, gem_imgs, cfg)

        score = game.start()

        # 一轮游戏结束后玩家选择重玩或者退出

            for event in pygame.event.get():

                if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):

                    pygame.quit()

                    sys.exit()

                elif event.type == pygame.KEYUP and event.key == pygame.K_r:

                    flag = True

            screen.fill((135, 206, 235))

            text0 = 'Final score: %s' % score

            text1 = 'Press <R> to restart the game.'

            text2 = 'Press <Esc> to quit the game.'

            for idx, text in enumerate([text0, text1, text2]):

                text_render = font.render(text, 1, (85, 65, 0))

                rect = text_render.get_rect()

                if idx == 0:

                    rect.left, rect.top = (212, y)

                elif idx == 1:

                    rect.left, rect.top = (122.5, y)

                    rect.left, rect.top = (126.5, y)

                screen.blit(text_render, rect)

            pygame.display.update()

if __name__ == '__main__':
8、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

from PyQt5.QtGui import *

from PyQt5.QtCore import *

from PyQt5.QtWidgets import *

class TetrisGame(QMainWindow):

    def __init__(self, parent=None):

        super(TetrisGame, self).__init__(parent)

        self.is_paused = False

        self.is_started = False

        self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg')))

        self.grid_size = 22

        self.timer = QBasicTimer()

        self.setFocusPolicy(Qt.StrongFocus)

        layout_horizontal = QHBoxLayout()

        self.inner_board = InnerBoard()

        self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)

        layout_horizontal.addWidget(self.external_board)

        self.side_panel = SidePanel(self, self.grid_size, self.inner_board)

        layout_horizontal.addWidget(self.side_panel)

        self.status_bar = self.statusBar()

        self.external_board.score_signal[str].connect(self.status_bar.showMessage)

        self.setWindowTitle('Tetris —— 九歌')

        self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())

        screen = QDesktopWidget().screenGeometry()

        size = self.geometry()

        self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)

    def updateWindow(self):

        self.external_board.updateData()

        self.side_panel.updateData()

        if self.is_started:

        self.is_started = True

        self.inner_board.createNewTetris()

        self.timer.start(self.fps, self)

        if not self.is_started:

        self.is_paused = not self.is_paused

        if self.is_paused:

            self.timer.stop()

            self.external_board.score_signal.emit('Paused')

            self.timer.start(self.fps, self)

        self.updateWindow()

    def timerEvent(self, event):

        if event.timerId() == self.timer.timerId():

            removed_lines = self.inner_board.moveDown()

            self.external_board.score += removed_lines

            self.updateWindow()

            super(TetrisGame, self).timerEvent(event)

    def keyPressEvent(self, event):

        if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:

            super(TetrisGame, self).keyPressEvent(event)

        key = event.key()

        if key == Qt.Key_P:

        if self.is_paused:

        elif key == Qt.Key_Left:

            self.inner_board.moveLeft()

        elif key == Qt.Key_Right:

            self.inner_board.moveRight()

        elif key == Qt.Key_Up:

            self.inner_board.rotateAnticlockwise()

        elif key == Qt.Key_Space:

            self.external_board.score += self.inner_board.dropDown()

            super(TetrisGame, self).keyPressEvent(event)

        self.updateWindow()

if __name__ == '__main__':

    app = QApplication([])

    tetris = TetrisGame()

    sys.exit(app.exec_())
9、贪吃蛇

玩法:童年经典,普通魔术也没啥意思,小时候玩的也是加速的python爱心代码。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('Greedy Snake —— 九歌')

    clock = pygame.time.Clock()

    pygame.mixer.music.load(cfg.BGMPATH)

    pygame.mixer.music.play(-1)

    apple = Apple(cfg, snake.coords)

        screen.fill(cfg.BLACK)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

                if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:

                    snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])

        if snake.update(apple):

            apple = Apple(cfg, snake.coords)

        if snake.isgameover: break

        drawGameGrid(cfg, screen)

        snake.draw(screen)

        apple.draw(screen)

        showScore(cfg, score, screen)

        pygame.display.update()

        clock.tick(cfg.FPS)

    return endInterface(screen, cfg)

if __name__ == '__main__':

        if not main(cfg):

普普通通

【玩法详细介绍+源码】

10、24点小游戏

玩法:通过加减乘除操作,小学生都没问题的。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

from fractions import Fraction

def checkClicked(group, mouse_pos, group_type='NUMBER'):

    if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]:

        max_selected = 2 if group_type == GROUPTYPES[0] else 1

        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

                    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)

        raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES))

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 = {'+': '+', '-': '-', '×': '*', '÷': '/'}

        result = str(eval(number1+operator_map[operator]+number2))

        return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))

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))

    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)

    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 = []

        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)

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

                warn_sound.play()

            selected_numbers = []

            selected_operators = []

            number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)

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

            showInfo('Congratulations', screen)

        if not is_win and len(game24_gen.numbers_now) == 1:

            showInfo('Game Over', screen)

        pygame.display.flip()

if __name__ == '__main__':
11、平衡木

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

from modules import breakoutClone

    game = breakoutClone(cfg)

if __name__ == '__main__':

还有配置文件

12、外星人入侵

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    clock = pygame.time.Clock()

    font = pygame.font.SysFont('arial', 18)

    if not os.path.isfile('score'):

        f = open('score', 'w')

    with open('score', 'r') as f:

        highest_score = int(f.read().strip())

    enemies_group = pygame.sprite.Group()

            enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)

            enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)

            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_shot_interval = 100

    enemy_shot_flag = False

        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])

                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

            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

            ufo.update(cfg.SCREENSIZE[0])

            ufo.draw(screen)

        for bullet in my_bullets_group:

            if bullet.update():

                my_bullets_group.remove(bullet)

                del bullet

                bullet.draw(screen)

        for bullet in en_bullets_group:

            if bullet.update(cfg.SCREENSIZE[1]):

                en_bullets_group.remove(bullet)

                del bullet

                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)

        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))

    pygame.display.set_caption('外星人入侵 —— 九歌')

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.mixer.music.load(cfg.BGMPATH)

    pygame.mixer.music.set_volume(0.4)

    pygame.mixer.music.play(-1)

        is_win = startGame(screen)

        endInterface(screen, cfg.BLACK, is_win)

if __name__ == '__main__':
13、贪心鸟

玩法:有点类似那个炸弹人,控制好走位问题不大。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

14、井字棋888

玩法:我打赌大家在课堂上肯定玩过这个,想想当年和同桌玩这个废了好几本本子。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享

import tkinter.messagebox as msg

root.title('TIC-TAC-TOE---Project Gurukul')

Label(root, text="player1 : X", font="times 15").grid(row=0, column=1)

Label(root, text="player2 : O", font="times 15").grid(row=0, column=2)

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# for player1 sign = X and for player2 sign= Y

# counting the no. of click

    return ((panels[1] == panels[2] == panels[3] == sign)

            or (panels[1] == panels[4] == panels[7] == sign)

            or (panels[1] == panels[5] == panels[9] == sign)

            or (panels[2] == panels[5] == panels[8] == sign)

            or (panels[3] == panels[6] == panels[9] == sign)

            or (panels[3] == panels[5] == panels[7] == sign)

            or (panels[4] == panels[5] == panels[6] == sign)

            or (panels[7] == panels[8] == panels[9] == sign))

    global count, mark, digits

    # Check which button clicked

    if digit == 1 and digit in digits:

        digits.remove(digit)

        ##player1 will play if the value of count is even and for odd player2 will play

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button1.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 2 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button2.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 3 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button3.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 4 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button4.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 5 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button5.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 6 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button6.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 7 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button7.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 8 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button8.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 9 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button9.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    ###if count is greater then 8 then the match has been tied

    if (count > 8 and win(panels, 'X') == False and win(panels, 'O') == False):

        msg.showinfo("Result", "Match Tied")

button1 = Button(root, width=15, font=('Times 16 bold'), height=7, command=lambda: checker(1))

button1.grid(row=1, column=1)

button2 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(2))

button2.grid(row=1, column=2)

button3 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(3))

button3.grid(row=1, column=3)

button4 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(4))

button4.grid(row=2, column=1)

button5 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(5))

button5.grid(row=2, column=2)

button6 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(6))

button6.grid(row=2, column=3)

button7 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(7))

button7.grid(row=3, column=1)

button8 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(8))

button8.grid(row=3, column=2)

button9 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(9))

button9.grid(row=3, column=3)

有点困难

【玩法详解+源码获取看底部】

15、炸弹人

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

16、保卫森林

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

17、五子棋

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

18、吃豆豆

玩法详解:考验手速和操作和走位,我不喜欢玩这类跑来跑去的。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

19、坦克大战

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

20、超级玛丽

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

21、水果忍者

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

极度困难

【攻略大全+源码获取看底部】

22、飞机大战

攻略大全:从这里开始的游戏,真正算的上有难度了,这个飞机大战跟童年玩的比起来还是差一点。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

23、2048

攻略大全:也是曾经风靡一时的,越到后面越难,合成的时候一定要大数放在角落。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

24、推箱子

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

25、塔防

攻略大全:又是一种塔防类的游戏,有点意思,就是速度太快了,反应不过来。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

26、植物大战僵尸

攻略大全:最经典的植物大战僵尸,操作不用介绍了,不过可以自己玩玩看。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

27、扫雷

玩法详解:扫雷还是挺有意思的,技能玩又考验推理

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

终极挑战

【太难了。。源码领取看文章底部】

28、拼图

游戏体验:三个终极挑战,能完成一个就算你厉害,拼图是我最烦的,太难了。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

29、走迷宫

游戏体验:我反正没走出去,大家能走出去吗

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

30、最强游戏

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能文章来源地址https://www.toymoban.com/news/detail-836947.html

大家好,今天给大家带来30个 Python 小游戏,喜欢记得点赞、一定要收藏!

文章目录
    • 有手就行
      • 1、吃金币
      • 2、打乒乓
      • 3、滑雪
      • 4、并夕夕版飞机大战
      • 5、打地鼠
    • 简简单单
      • 6、小恐龙
      • 7、消消乐
      • 8、俄罗斯方块
      • 9、贪吃蛇
    • 普普通通
      • 10、24点小游戏
      • 11、平衡木
      • 12、外星人入侵
      • 13、贪心鸟
      • 14、井字棋888
    • 有点困难
      • 15、炸弹人
      • 16、保卫森林
      • 17、五子棋
      • 18、吃豆豆
      • 19、坦克大战
      • 20、超级玛丽
      • 21、水果忍者
    • 极度困难
      • 22、飞机大战
      • 23、2048
      • 24、推箱子
      • 25、塔防
      • 26、植物大战僵尸
      • 27、扫雷
    • 终极挑战
      • 28、拼图
      • 29、走迷宫
      • 30、最强游戏

有手就行

1、吃金币

【有手就行系列不介绍玩法了+附源码】

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('catch coins —— 九歌')

    for key, value in cfg.IMAGE_PATHS.items():

        if isinstance(value, list):

            for item in value: images.append(pygame.image.load(item))

            game_images[key] = images

            game_images[key] = pygame.image.load(value)

    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

    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(game_images['hero'], position=(375, 520))

    food_sprites_group = pygame.sprite.Group()

    generate_food_freq = random.randint(10, 20)

    generate_food_count = 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()

        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.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:

        pygame.display.flip()

        clock.tick(cfg.FPS)

    # 游戏结束, 记录最高分并显示游戏结束画面

    fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')

    fp.write(str(highest_score))

    return showEndGameInterface(screen, cfg, score, highest_score)

if __name__ == '__main__':
2、打乒乓

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

def Button(screen, position, text, button_size=(200, 50)):

    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))

    --game_mode: 1(单人模式)/2(双人模式)

def startInterface(screen):

    clock = pygame.time.Clock()

        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

        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]]

        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)

        pygame.display.update()

    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控制, 仅双人模式时可控制)

    racket_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)

    racket_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)

    ball = Ball(cfg.BALLPICPATH, cfg)

    clock = pygame.time.Clock()

        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')

            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

        pygame.display.update()

    screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))

    pygame.display.set_caption('pingpong —— 九歌')

        score_left, score_right = runDemo(screen)

        endInterface(screen, score_left, score_right)

if __name__ == '__main__':
3、滑雪

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

class SkierClass(pygame.sprite.Sprite):

        pygame.sprite.Sprite.__init__(self)

        self.direction = 0

        self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]

        self.image = pygame.image.load(self.imagepaths[self.direction])

        self.rect = self.image.get_rect()

        self.rect.center = [320, 100]

        self.speed = [self.direction, 6-abs(self.direction)*2]

    '''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''

        self.direction += num

        self.direction = max(-2, self.direction)

        self.direction = min(2, self.direction)

        center = self.rect.center

        self.image = pygame.image.load(self.imagepaths[self.direction])

        self.rect = self.image.get_rect()

        self.rect.center = center

        self.speed = [self.direction, 6-abs(self.direction)*2]

        return self.speed

        self.rect.centerx += self.speed[0]

        self.rect.centerx = max(20, self.rect.centerx)

        self.rect.centerx = min(620, self.rect.centerx)

        self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])

    def setForward(self):

        self.direction = 0

        self.image = pygame.image.load(self.imagepaths[self.direction])

class ObstacleClass(pygame.sprite.Sprite):

    def __init__(self, img_path, location, attribute):

        pygame.sprite.Sprite.__init__(self)

        self.img_path = img_path

        self.image = pygame.image.load(self.img_path)

        self.location = location

        self.rect = self.image.get_rect()

        self.rect.center = self.location

        self.attribute = attribute

        self.passed = False

        self.rect.centery = self.location[1] - num

def createObstacles(s, e, num=10):

    obstacles = pygame.sprite.Group()

        row = random.randint(s, e)

        col = random.randint(0, 9)

        location  = [col*64+20, row*64+20]

        if location not in locations:

            locations.append(location)

            attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))

            img_path = cfg.OBSTACLE_PATHS[attribute]

            obstacle = ObstacleClass(img_path, location, attribute)

            obstacles.add(obstacle)

def AddObstacles(obstacles0, obstacles1):

    obstacles = pygame.sprite.Group()

    for obstacle in obstacles0:

        obstacles.add(obstacle)

    for obstacle in obstacles1:

        obstacles.add(obstacle)

def ShowStartInterface(screen, screensize):

    screen.fill((255, 255, 255))

    tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)

    cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)

    title = tfont.render(u'滑雪游戏', True, (255, 0, 0))

    content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))

    trect = title.get_rect()

    trect.midtop = (screensize[0]/2, screensize[1]/5)

    crect = content.get_rect()

    crect.midtop = (screensize[0]/2, screensize[1]/2)

    screen.blit(title, trect)

    screen.blit(content, crect)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

        pygame.display.update()

def showScore(screen, score, pos=(10, 10)):

    font = pygame.font.Font(cfg.FONTPATH, 30)

    score_text = font.render("Score: %s" % score, True, (0, 0, 0))

    screen.blit(score_text, pos)

def updateFrame(screen, obstacles, skier, score):

    screen.fill((255, 255, 255))

    obstacles.draw(screen)

    screen.blit(skier.image, skier.rect)

    showScore(screen, score)

    pygame.display.update()

    pygame.mixer.music.load(cfg.BGMPATH)

    pygame.mixer.music.set_volume(0.4)

    pygame.mixer.music.play(-1)

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('滑雪游戏 —— 九歌')

    ShowStartInterface(screen, cfg.SCREENSIZE)

    obstacles0 = createObstacles(20, 29)

    obstacles1 = createObstacles(10, 19)

    obstacles = AddObstacles(obstacles0, obstacles1)

    clock = pygame.time.Clock()

        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_LEFT or event.key == pygame.K_a:

                    speed = skier.turn(-1)

                elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:

                    speed = skier.turn(1)

        distance += speed[1]

        if distance >= 640 and obstaclesflag == 0:

            obstaclesflag = 1

            obstacles0 = createObstacles(20, 29)

            obstacles = AddObstacles(obstacles0, obstacles1)

        if distance >= 1280 and obstaclesflag == 1:

            obstaclesflag = 0

            distance -= 1280

            for obstacle in obstacles0:

                obstacle.location[1] = obstacle.location[1] - 1280

            obstacles1 = createObstacles(10, 19)

            obstacles = AddObstacles(obstacles0, obstacles1)

        for obstacle in obstacles:

            obstacle.move(distance)

        hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)

        if hitted_obstacles:

            if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:

                score -= 50

                skier.setFall()

                updateFrame(screen, obstacles, skier, score)

                pygame.time.delay(1000)

                skier.setForward()

                speed = [0, 6]

                hitted_obstacles[0].passed = True

            elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:

                score += 10

                obstacles.remove(hitted_obstacles[0])

        updateFrame(screen, obstacles, skier, score)

        clock.tick(cfg.FPS)

if __name__ == '__main__':
4、并夕夕版飞机大战

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

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_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()

    for i in range(num_player):

        player_group.add(Ship(i+1, cfg))

    clock = pygame.time.Clock()

    score_1, score_2 = 0, 0

        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 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

            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))

            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

                    player.explode(screen)

                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

                    score_2 += 1

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

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('飞机大战 —— 九歌')

    num_player = StartInterface(screen, cfg)

            GamingInterface(num_player=1, screen=screen)

            EndInterface(screen, cfg)

            GamingInterface(num_player=2, screen=screen)

            EndInterface(screen, cfg)

if __name__ == '__main__':
5、打地鼠

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('打地鼠 —— 九歌')

    pygame.mixer.music.load(cfg.BGM_PATH)

    pygame.mixer.music.play(-1)

        '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()

    init_time = pygame.time.get_ticks()

        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.setPosition(hole_pos)

            pygame.time.set_timer(change_hole_event, 650)

        elif time_remain == 20 and flag:

            hole_pos = random.choice(cfg.HOLE_POSITIONS)

            mole.setPosition(hole_pos)

            pygame.time.set_timer(change_hole_event, 500)

        if time_remain == 10:

            audios['count_down'].play()

        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

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

    # 读取最佳分数(try块避免第一次游戏无.rec文件)

        best_score = int(open(cfg.RECORD_PATH).read())

    if your_score > best_score:

        f = open(cfg.RECORD_PATH, 'w')

        f.write(str(your_score))

    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)

if __name__ == '__main__':

        is_restart = main()

        if not is_restart:

简简单单

【简单介绍一下玩法+附源码】

6、小恐龙

玩法:上下控制起跳躲避

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('九歌')

    for key, value in cfg.AUDIO_PATHS.items():

        sounds[key] = pygame.mixer.Sound(value)

    GameStartInterface(screen, sounds, cfg)

    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

    clock = pygame.time.Clock()

        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']))

                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))))

        cloud_sprites_group.update()

        cactus_sprites_group.update()

        ptera_sprites_group.update()

        if score_timer > (cfg.FPS//12):

            score_timer = 0

            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)

    return GameEndInterface(screen, cfg), highest_score

if __name__ == '__main__':

        flag, highest_score = main(highest_score)

        if not flag: break
7、消消乐

玩法:三个相连就能消除

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('Gemgem —— 九歌')

    pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))

    pygame.mixer.music.set_volume(0.6)

    pygame.mixer.music.play(-1)

    sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))

        sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))

    font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)

    for i in range(1, 8):

        gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))

    game = gemGame(screen, sounds, font, gem_imgs, cfg)

        score = game.start()

        # 一轮游戏结束后玩家选择重玩或者退出

            for event in pygame.event.get():

                if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):

                    pygame.quit()

                    sys.exit()

                elif event.type == pygame.KEYUP and event.key == pygame.K_r:

                    flag = True

            screen.fill((135, 206, 235))

            text0 = 'Final score: %s' % score

            text1 = 'Press <R> to restart the game.'

            text2 = 'Press <Esc> to quit the game.'

            for idx, text in enumerate([text0, text1, text2]):

                text_render = font.render(text, 1, (85, 65, 0))

                rect = text_render.get_rect()

                if idx == 0:

                    rect.left, rect.top = (212, y)

                elif idx == 1:

                    rect.left, rect.top = (122.5, y)

                    rect.left, rect.top = (126.5, y)

                screen.blit(text_render, rect)

            pygame.display.update()

if __name__ == '__main__':
8、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

from PyQt5.QtGui import *

from PyQt5.QtCore import *

from PyQt5.QtWidgets import *

class TetrisGame(QMainWindow):

    def __init__(self, parent=None):

        super(TetrisGame, self).__init__(parent)

        self.is_paused = False

        self.is_started = False

        self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg')))

        self.grid_size = 22

        self.timer = QBasicTimer()

        self.setFocusPolicy(Qt.StrongFocus)

        layout_horizontal = QHBoxLayout()

        self.inner_board = InnerBoard()

        self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)

        layout_horizontal.addWidget(self.external_board)

        self.side_panel = SidePanel(self, self.grid_size, self.inner_board)

        layout_horizontal.addWidget(self.side_panel)

        self.status_bar = self.statusBar()

        self.external_board.score_signal[str].connect(self.status_bar.showMessage)

        self.setWindowTitle('Tetris —— 九歌')

        self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())

        screen = QDesktopWidget().screenGeometry()

        size = self.geometry()

        self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)

    def updateWindow(self):

        self.external_board.updateData()

        self.side_panel.updateData()

        if self.is_started:

        self.is_started = True

        self.inner_board.createNewTetris()

        self.timer.start(self.fps, self)

        if not self.is_started:

        self.is_paused = not self.is_paused

        if self.is_paused:

            self.timer.stop()

            self.external_board.score_signal.emit('Paused')

            self.timer.start(self.fps, self)

        self.updateWindow()

    def timerEvent(self, event):

        if event.timerId() == self.timer.timerId():

            removed_lines = self.inner_board.moveDown()

            self.external_board.score += removed_lines

            self.updateWindow()

            super(TetrisGame, self).timerEvent(event)

    def keyPressEvent(self, event):

        if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:

            super(TetrisGame, self).keyPressEvent(event)

        key = event.key()

        if key == Qt.Key_P:

        if self.is_paused:

        elif key == Qt.Key_Left:

            self.inner_board.moveLeft()

        elif key == Qt.Key_Right:

            self.inner_board.moveRight()

        elif key == Qt.Key_Up:

            self.inner_board.rotateAnticlockwise()

        elif key == Qt.Key_Space:

            self.external_board.score += self.inner_board.dropDown()

            super(TetrisGame, self).keyPressEvent(event)

        self.updateWindow()

if __name__ == '__main__':

    app = QApplication([])

    tetris = TetrisGame()

    sys.exit(app.exec_())
9、贪吃蛇

玩法:童年经典,普通魔术也没啥意思,小时候玩的也是加速的python爱心代码。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.display.set_caption('Greedy Snake —— 九歌')

    clock = pygame.time.Clock()

    pygame.mixer.music.load(cfg.BGMPATH)

    pygame.mixer.music.play(-1)

    apple = Apple(cfg, snake.coords)

        screen.fill(cfg.BLACK)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                pygame.quit()

                sys.exit()

            elif event.type == pygame.KEYDOWN:

                if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:

                    snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])

        if snake.update(apple):

            apple = Apple(cfg, snake.coords)

        if snake.isgameover: break

        drawGameGrid(cfg, screen)

        snake.draw(screen)

        apple.draw(screen)

        showScore(cfg, score, screen)

        pygame.display.update()

        clock.tick(cfg.FPS)

    return endInterface(screen, cfg)

if __name__ == '__main__':

        if not main(cfg):

普普通通

【玩法详细介绍+源码】

10、24点小游戏

玩法:通过加减乘除操作,小学生都没问题的。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

from fractions import Fraction

def checkClicked(group, mouse_pos, group_type='NUMBER'):

    if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]:

        max_selected = 2 if group_type == GROUPTYPES[0] else 1

        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

                    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)

        raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES))

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 = {'+': '+', '-': '-', '×': '*', '÷': '/'}

        result = str(eval(number1+operator_map[operator]+number2))

        return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))

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))

    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)

    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 = []

        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)

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

                warn_sound.play()

            selected_numbers = []

            selected_operators = []

            number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)

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

            showInfo('Congratulations', screen)

        if not is_win and len(game24_gen.numbers_now) == 1:

            showInfo('Game Over', screen)

        pygame.display.flip()

if __name__ == '__main__':
11、平衡木

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

from modules import breakoutClone

    game = breakoutClone(cfg)

if __name__ == '__main__':

还有配置文件

12、外星人入侵

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享:

    clock = pygame.time.Clock()

    font = pygame.font.SysFont('arial', 18)

    if not os.path.isfile('score'):

        f = open('score', 'w')

    with open('score', 'r') as f:

        highest_score = int(f.read().strip())

    enemies_group = pygame.sprite.Group()

            enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)

            enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)

            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_shot_interval = 100

    enemy_shot_flag = False

        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])

                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

            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

            ufo.update(cfg.SCREENSIZE[0])

            ufo.draw(screen)

        for bullet in my_bullets_group:

            if bullet.update():

                my_bullets_group.remove(bullet)

                del bullet

                bullet.draw(screen)

        for bullet in en_bullets_group:

            if bullet.update(cfg.SCREENSIZE[1]):

                en_bullets_group.remove(bullet)

                del bullet

                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)

        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))

    pygame.display.set_caption('外星人入侵 —— 九歌')

    screen = pygame.display.set_mode(cfg.SCREENSIZE)

    pygame.mixer.music.load(cfg.BGMPATH)

    pygame.mixer.music.set_volume(0.4)

    pygame.mixer.music.play(-1)

        is_win = startGame(screen)

        endInterface(screen, cfg.BLACK, is_win)

if __name__ == '__main__':
13、贪心鸟

玩法:有点类似那个炸弹人,控制好走位问题不大。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

14、井字棋888

玩法:我打赌大家在课堂上肯定玩过这个,想想当年和同桌玩这个废了好几本本子。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

源码分享

import tkinter.messagebox as msg

root.title('TIC-TAC-TOE---Project Gurukul')

Label(root, text="player1 : X", font="times 15").grid(row=0, column=1)

Label(root, text="player2 : O", font="times 15").grid(row=0, column=2)

digits = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# for player1 sign = X and for player2 sign= Y

# counting the no. of click

    return ((panels[1] == panels[2] == panels[3] == sign)

            or (panels[1] == panels[4] == panels[7] == sign)

            or (panels[1] == panels[5] == panels[9] == sign)

            or (panels[2] == panels[5] == panels[8] == sign)

            or (panels[3] == panels[6] == panels[9] == sign)

            or (panels[3] == panels[5] == panels[7] == sign)

            or (panels[4] == panels[5] == panels[6] == sign)

            or (panels[7] == panels[8] == panels[9] == sign))

    global count, mark, digits

    # Check which button clicked

    if digit == 1 and digit in digits:

        digits.remove(digit)

        ##player1 will play if the value of count is even and for odd player2 will play

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button1.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 2 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button2.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 3 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button3.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 4 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button4.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 5 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button5.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 6 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button6.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 7 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button7.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 8 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button8.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    if digit == 9 and digit in digits:

        digits.remove(digit)

        if count % 2 == 0:

            panels[digit] = mark

        elif count % 2 != 0:

            panels[digit] = mark

        button9.config(text=mark)

        count = count + 1

        if (win(panels, sign) and sign == 'X'):

            msg.showinfo("Result", "Player1 wins")

            root.destroy()

        elif (win(panels, sign) and sign == 'O'):

            msg.showinfo("Result", "Player2 wins")

            root.destroy()

    ###if count is greater then 8 then the match has been tied

    if (count > 8 and win(panels, 'X') == False and win(panels, 'O') == False):

        msg.showinfo("Result", "Match Tied")

button1 = Button(root, width=15, font=('Times 16 bold'), height=7, command=lambda: checker(1))

button1.grid(row=1, column=1)

button2 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(2))

button2.grid(row=1, column=2)

button3 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(3))

button3.grid(row=1, column=3)

button4 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(4))

button4.grid(row=2, column=1)

button5 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(5))

button5.grid(row=2, column=2)

button6 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(6))

button6.grid(row=2, column=3)

button7 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(7))

button7.grid(row=3, column=1)

button8 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(8))

button8.grid(row=3, column=2)

button9 = Button(root, width=15, height=7, font=('Times 16 bold'), command=lambda: checker(9))

button9.grid(row=3, column=3)

有点困难

【玩法详解+源码获取看底部】

15、炸弹人

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

16、保卫森林

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

17、五子棋

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

18、吃豆豆

玩法详解:考验手速和操作和走位,我不喜欢玩这类跑来跑去的。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

19、坦克大战

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

20、超级玛丽

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

21、水果忍者

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

极度困难

【攻略大全+源码获取看底部】

22、飞机大战

攻略大全:从这里开始的游戏,真正算的上有难度了,这个飞机大战跟童年玩的比起来还是差一点。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

23、2048

攻略大全:也是曾经风靡一时的,越到后面越难,合成的时候一定要大数放在角落。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

24、推箱子

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

25、塔防

攻略大全:又是一种塔防类的游戏,有点意思,就是速度太快了,反应不过来。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

26、植物大战僵尸

攻略大全:最经典的植物大战僵尸,操作不用介绍了,不过可以自己玩玩看。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

27、扫雷

玩法详解:扫雷还是挺有意思的,技能玩又考验推理

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

终极挑战

【太难了。。源码领取看文章底部】

28、拼图

游戏体验:三个终极挑战,能完成一个就算你厉害,拼图是我最烦的,太难了。

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

29、走迷宫

游戏体验:我反正没走出去,大家能走出去吗

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

30、最强游戏

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

编程小游戏制作植物僵尸,编程小游戏教程视频,pygame,python,开发语言,人工智能

到了这里,关于编程小游戏制作植物僵尸,编程小游戏教程视频的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 用核桃编程编出来一款游戏,核桃编程小游戏制作

    大家好,本文将围绕核桃编程python简单小游戏代码大全展开说明,核桃编程python简单小游戏代码是一个很多人都想弄明白的事情,想搞清楚用核桃编程编出来一款游戏需要先了解以下几个事情。 for是一个扮腊循环,语法:厅乱滑陪凯 for i in iterable: 语句 注意:冒号后有

    2024年02月11日
    浏览(41)
  • 【超详细教学】Python制作迷宫小游戏教程

    我将为你提供一个简单的迷宫小游戏的Python代码,并解释每个部分的作用,可以为你在工作之余可以堂堂正正的摸会小鱼。 运用工具: Python、Pygame、PyCharm 点击领取Python工具助学资料 在这个迷宫游戏中,我们需要先确定迷宫的大小。我们可以通过定义一个常量来表示迷宫的

    2024年02月11日
    浏览(39)
  • python简单小游戏代码教程,python编程小游戏代码

    大家好,本文将围绕一些简单好玩的python编程游戏展开说明,python编写的入门简单小游戏是一个很多人都想弄明白的事情,想搞清楚python简单小游戏代码教程需要先了解以下几个事情。 Source code download: 本文相关源码 大家好,我是辣条。 今天给大家带来30个py小游戏,一定要

    2024年02月03日
    浏览(69)
  • python简单小游戏代码教程,python编程小游戏简单的

    大家好,小编来为大家解答以下问题,一些简单好玩的python编程游戏,python编写的入门简单小游戏,今天让我们一起来看看吧! 哈喽铁子们 表弟最近在学Python,总是跟我抱怨很枯燥无味,其实,他有没有认真想过,可能是自己学习姿势不对? 比方说,可以通过打游戏来学编

    2024年04月23日
    浏览(41)
  • python简单小游戏代码教程,python小游戏编程100例

    大家好,小编为大家解答一些简单好玩的python编程游戏的问题。很多人还不知道python编写的入门简单小游戏,现在让我们一起来看看吧! Source code download: 本文相关源码 哈喽铁子们 表弟最近在学Python,总是跟我抱怨很枯燥无味,其实,他有没有认真想过,可能是自己学习姿势

    2024年01月22日
    浏览(48)
  • 【python游戏制作】僵尸来袭 ~ 快来一起创造植物叭~

    哈喽!大家好,我是魔王呐~ 看到下面这一段话,大家是不是会想起你在某种时候玩过的一款游戏呐~ 我拥有着绚烂的外表,但这美丽只在瞬间绽放。烟花散尽之后你会多一个朋友,但是我的身影已经消失在你的视线之外。                         

    2024年01月23日
    浏览(38)
  • chatgpt赋能python:Python简单小游戏制作教程——让你学会编写游戏代码

    Python是一种高级编程语言,越来越受欢迎,因为它易于学习和使用,而且灵活性非常高。在这篇文章中,我们将教你如何用Python编写一个简单的小游戏。让我们开始吧! 在编写代码之前,你需要安装以下工具: Python编程语言 Pygame游戏框架 步骤一:设置游戏场景 首先,你需

    2024年02月11日
    浏览(55)
  • final-期末大作业-制作AR射箭小游戏(Unity AR配置详细教程)

    链接: github仓库 bilibili视频 大作业要求: 制作一款特定技术应用小游戏,并提交技术报告。 内容(请参考以下技术主题,但不限于这些主题): 运用手机拍若干全景图,贴到天空盒或球型天空,做一个简单校园漫游功能。 粒子系统效果制作,必须带一个控制组件,控制粒子

    2024年02月06日
    浏览(51)
  • 【CE入门教程】使用Cheat Engine(CE)修改游戏“植物大战僵尸”之植物篇

    目录  1.单卡片无CD 1.1 思路一 1.2 思路二 2.全卡片无CD 3.豌豆射手射速修改(修改植物射速) 4.实现豌豆射手发射“玉米加农炮”(思路) 上一期教程中,我们学习了修改植物大战僵尸的阳光数量、向日葵生产阳光速率以及实现“太阳雨”PS:上篇链接:(38条消息) 【CE入门教

    2023年04月16日
    浏览(57)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包