30 small Python games, Xiaobai practiced, I can play all day [with source code]

Today I will bring you 30 small python games, you must collect them!

All source codes of 30 small Python games

Industry information: Add PPT templates, resume templates, and PDFs of industry classic books. Interview question bank: Classic and popular Dachang interview questions over the years, which are continuously updated and added. Learning materials: including Python, crawlers, data analysis, algorithms and other learning videos and documents.

Friends, if you need it, you can scan the CSDN official certification QR code below on WeChat to get it for free [guaranteed 100% free].

as long as you have hands

1. Eat gold coins

[If you have a hand, the series will not introduce the gameplay + source code attached]
insert image description here
Source code sharing:

import os
import cfg
import sys
import pygame
import random
from modules import *
 
 
'''游戏初始化'''
def initGame():
    # 初始化pygame, 设置展示窗口
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('catch coins —— 九歌')
    # 加载必要的游戏素材
    game_images = {}
    for key, value in cfg.IMAGE_PATHS.items():
        if isinstance(value, list):
            images = []
            for item in value: images.append(pygame.image.load(item))
            game_images[key] = images
        else:
            game_images[key] = pygame.image.load(value)
    game_sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        if key == 'bgm': continue
        game_sounds[key] = pygame.mixer.Sound(value)
    # 返回初始化数据
    return screen, game_images, game_sounds
 
 
'''主函数'''
def main():
    # 初始化
    screen, game_images, game_sounds = initGame()
    # 播放背景音乐
    pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
    pygame.mixer.music.play(-1, 0.0)
    # 字体加载
    font = pygame.font.Font(cfg.FONT_PATH, 40)
    # 定义hero
    hero = Hero(game_images['hero'], position=(375, 520))
    # 定义食物组
    food_sprites_group = pygame.sprite.Group()
    generate_food_freq = random.randint(10, 20)
    generate_food_count = 0
    # 当前分数/历史最高分
    score = 0
    highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
    # 游戏主循环
    clock = pygame.time.Clock()
    while True:
        # --填充背景
        screen.fill(0)
        screen.blit(game_images['background'], (0, 0))
        # --倒计时信息
        countdown_text = 'Count down: ' + str((90000 - pygame.time.get_ticks()) // 60000) + ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)
        countdown_text = font.render(countdown_text, True, (0, 0, 0))
        countdown_rect = countdown_text.get_rect()
        countdown_rect.topright = [cfg.SCREENSIZE[0]-30, 5]
        screen.blit(countdown_text, countdown_rect)
        # --按键检测
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        key_pressed = pygame.key.get_pressed()
        if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:
            hero.move(cfg.SCREENSIZE, 'left')
        if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:
            hero.move(cfg.SCREENSIZE, 'right')
        # --随机生成食物
        generate_food_count += 1
        if generate_food_count > generate_food_freq:
            generate_food_freq = random.randint(10, 20)
            generate_food_count = 0
            food = Food(game_images, random.choice(['gold',] * 10 + ['apple']), cfg.SCREENSIZE)
            food_sprites_group.add(food)
        # --更新食物
        for food in food_sprites_group:
            if food.update(): food_sprites_group.remove(food)
        # --碰撞检测
        for food in food_sprites_group:
            if pygame.sprite.collide_mask(food, hero):
                game_sounds['get'].play()
                food_sprites_group.remove(food)
                score += food.score
                if score > highest_score: highest_score = score
        # --画hero
        hero.draw(screen)
        # --画食物
        food_sprites_group.draw(screen)
        # --显示得分
        score_text = f'Score: {score}, Highest: {highest_score}'
        score_text = font.render(score_text, True, (0, 0, 0))
        score_rect = score_text.get_rect()
        score_rect.topleft = [5, 5]
        screen.blit(score_text, score_rect)
        # --判断游戏是否结束
        if pygame.time.get_ticks() >= 90000:
            break
        # --更新屏幕
        pygame.display.flip()
        clock.tick(cfg.FPS)
    # 游戏结束, 记录最高分并显示游戏结束画面
    fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, 'w')
    fp.write(str(highest_score))
    fp.close()
    return showEndGameInterface(screen, cfg, score, highest_score)
 
 
'''run'''
if __name__ == '__main__':
    while main():
        pass

2. Play table tennis

insert image description here

3. Skiing

insert image description here

4. Parallel Aircraft Battle

insert image description here

5. Whack-a-mole

insert image description here

simple

[Briefly introduce the gameplay + source code attached]

6. Little Dinosaur

How to play: Control up and down to take off and avoid
insert image description here

7. Xiaoxiaole

How to play: three connected can be eliminated
insert image description here

8. Tetris

How to play: Childhood classic, the normal mode is meaningless, when we were young we all played acceleration.
insert image description here

9. Greedy Snake

How to play: Childhood classics, ordinary magic is not interesting, and it was accelerated when I was young.
insert image description here

Ordinary

[Detailed introduction to gameplay + source code]

10. 24-point game

How to play: Through addition, subtraction, multiplication and division operations, elementary school students have no problem.
insert image description here

11. Balance beam

How to play: It is also a classic game when I was a child. Just control the left and right, and it will be a little more difficult later.
insert image description here
[There are also configuration files]

12. Alien Invasion

How to play: This reminds me of the bosses of Contra's first levels, which are somewhat similar, but the difficulty of Contra must be higher.
insert image description here

13. Greedy Bird

How to play: It's a bit similar to the Bomberman, it's not a big problem to control the movement.
insert image description here

14. Tic Tac Toe 888''

How to play: I bet everyone must have played this in class. Thinking about playing this with the same table back then, several books were wasted.
insert image description here

A little difficult

[Detailed gameplay + source code acquisition at the bottom]

15. Bomberman

Detailed explanation of how to play: Another classic game when I was a child, I was killed by myself many times when I was a child.
insert image description here

16. Defend the forest

Detailed explanation of the gameplay: similar to defending radish, small games like tower defense, the layout must be reasonable, consider the range attribute, etc.
insert image description here

17. Backgammon

Detailed explanation of how to play: When I was young, I loved to play very much. First out is a sure way to win. Later, I learned that there will be a rule of banning hands. Moon, star, comet and so on.
insert image description here

18. Eat Peas

Detailed explanation of how to play: test hand speed, operation and position, I don't like to play this kind of running around.
insert image description here

19. Tank Battle

Detailed explanation of how to play: This is a classic among the classics. I like to play the two-player mode, and there are some modified modes in the back. This is one of the few games that I think is not outdated now.
insert image description here

20. Super Mario

Detailed explanation of how to play: classic among classics, it was difficult to play when I was young, so there is no need to introduce the operation.
insert image description here

21. Fruit Ninja

Detailed explanation of how to play: The game of cutting fruit is all the rage. I don’t know why it always blows up with a knife. It’s a very decompressing game.
insert image description here

extremely difficult

[Complete strategy + source code acquisition to see the bottom]

22. Airplane Wars

Raiders: The game starting from here is really difficult. Compared with the childhood game, this plane battle is still a bit worse.
insert image description here

23、2048

Raiders Daquan: It was once all the rage, the more difficult it is to go to the back, when compositing, it must be placed in the corner with a large number.
insert image description here

24. Sokoban

Raiders: The game that was available on the mobile phone before, the more difficult it is to push to the later levels, I seem to be unable to continue playing after more than 20 levels.
insert image description here

25. Tower defense

Raiders Daquan: It is another tower defense game, which is a bit interesting, but the speed is too fast to react.
insert image description here

26. Plants vs Zombies

Raiders: The most classic Plants vs. Zombies, the operation needs no introduction, but you can play it yourself.
insert image description here

27. Minesweeper

Detailed explanation of the gameplay: Minesweeper is quite interesting, and skill play also tests reasoning
insert image description here

ultimate challenge

【too difficult. . See the bottom of the article for source code collection]

28. Puzzle

Game experience: Three ultimate challenges, if you can complete one, you are good. Puzzles are the most annoying for me, too difficult.
insert image description here

29. Walk the Maze

Game experience: I didn’t go out anyway, can everyone go out?
insert image description here

30. The strongest game

Game experience: It's too difficult to control. .
insert image description here
That's all for today's chat, everyone remember to like and collect, share and forward

Guess you like

Origin blog.csdn.net/libaiup/article/details/130502715