脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 14 个Python小游戏 源码分享

14 个Python小游戏 源码分享

2022-01-10 00:16五包辣条! Python

今天给大家带来14个py小游戏如:吃金币、打乒乓、滑雪、并夕夕版飞机大战、打地鼠、小恐龙、消消乐、俄罗斯方块、贪吃蛇、24点小游戏、平衡木、外星人入侵、贪心鸟、井字棋888‘’,文章都带了源码,感兴趣的小伙伴感快收

1、吃金币

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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、打乒乓

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import sys
import cfg
import pygame
from modules import *
 
 
'''定义按钮'''
def button(screen, position, text, button_size=(200, 50)):
    left, top = position
    bwidth, bheight = button_size
    pygame.draw.line(screen, (150, 150, 150), (left, top), (left+bwidth, top), 5)
    pygame.draw.line(screen, (150, 150, 150), (left, top-2), (left, top+bheight), 5)
    pygame.draw.line(screen, (50, 50, 50), (left, top+bheight), (left+bwidth, top+bheight), 5)
    pygame.draw.line(screen, (50, 50, 50), (left+bwidth, top+bheight), (left+bwidth, top), 5)
    pygame.draw.rect(screen, (100, 100, 100), (left, top, bwidth, bheight))
    font = pygame.font.font(cfg.fontpath, 30)
    text_render = font.render(text, 1, (255, 235, 205))
    return screen.blit(text_render, (left+50, top+10))
 
 
'''
function:
    开始界面
input:
    --screen: 游戏界面
return:
    --game_mode: 1(单人模式)/2(双人模式)
'''
def startinterface(screen):
    clock = pygame.time.clock()
    while true:
        screen.fill((41, 36, 33))
        button_1 = button(screen, (150, 175), '1 player')
        button_2 = button(screen, (150, 275), '2 player')
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit()
            if event.type == pygame.mousebuttondown:
                if button_1.collidepoint(pygame.mouse.get_pos()):
                    return 1
                elif button_2.collidepoint(pygame.mouse.get_pos()):
                    return 2
        clock.tick(10)
        pygame.display.update()
 
 
'''结束界面'''
def endinterface(screen, score_left, score_right):
    clock = pygame.time.clock()
    font1 = pygame.font.font(cfg.fontpath, 30)
    font2 = pygame.font.font(cfg.fontpath, 20)
    msg = 'player on left won!' if score_left > score_right else 'player on right won!'
    texts = [font1.render(msg, true, cfg.white),
            font2.render('press escape to quit.', true, cfg.white),
            font2.render('press enter to continue or play again.', true, cfg.white)]
    positions = [[120, 200], [155, 270], [80, 300]]
    while true:
        screen.fill((41, 36, 33))
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit()
            if event.type == pygame.keydown:
                if event.key == pygame.k_return:
                    return
                elif event.key == pygame.k_escape:
                    sys.exit()
                    pygame.quit()
        for text, pos in zip(texts, positions):
            screen.blit(text, pos)
        clock.tick(10)
        pygame.display.update()
 
 
'''运行游戏demo'''
def rundemo(screen):
    # 加载游戏素材
    hit_sound = pygame.mixer.sound(cfg.hitsoundpath)
    goal_sound = pygame.mixer.sound(cfg.goalsoundpath)
    pygame.mixer.music.load(cfg.bgmpath)
    pygame.mixer.music.play(-1, 0.0)
    font = pygame.font.font(cfg.fontpath, 50)
    # 开始界面
    game_mode = startinterface(screen)
    # 游戏主循环
    # --左边球拍(ws控制, 仅双人模式时可控制)
    score_left = 0
    racket_left = racket(cfg.racketpicpath, 'left', cfg)
    # --右边球拍(↑↓控制)
    score_right = 0
    racket_right = racket(cfg.racketpicpath, 'right', cfg)
    # --球
    ball = ball(cfg.ballpicpath, cfg)
    clock = pygame.time.clock()
    while true:
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit(-1)
        screen.fill((41, 36, 33))
        # 玩家操作
        pressed_keys = pygame.key.get_pressed()
        if pressed_keys[pygame.k_up]:
            racket_right.move('up')
        elif pressed_keys[pygame.k_down]:
            racket_right.move('down')
        if game_mode == 2:
            if pressed_keys[pygame.k_w]:
                racket_left.move('up')
            elif pressed_keys[pygame.k_s]:
                racket_left.move('down')
        else:
            racket_left.automove(ball)
        # 球运动
        scores = ball.move(ball, racket_left, racket_right, hit_sound, goal_sound)
        score_left += scores[0]
        score_right += scores[1]
        # 显示
        # --分隔线
        pygame.draw.rect(screen, cfg.white, (247, 0, 6, 500))
        # --球
        ball.draw(screen)
        # --拍
        racket_left.draw(screen)
        racket_right.draw(screen)
        # --得分
        screen.blit(font.render(str(score_left), false, cfg.white), (150, 10))
        screen.blit(font.render(str(score_right), false, cfg.white), (300, 10))
        if score_left == 11 or score_right == 11:
            return score_left, score_right
        clock.tick(100)
        pygame.display.update()
 
 
'''主函数'''
def main():
    # 初始化
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode((cfg.width, cfg.height))
    pygame.display.set_caption('pingpong —— 九歌')
    # 开始游戏
    while true:
        score_left, score_right = rundemo(screen)
        endinterface(screen, score_left, score_right)
 
 
'''run'''
if __name__ == '__main__':
    main()

3、滑雪

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
import sys
import cfg
import pygame
import random
 
 
'''滑雪者类'''
class skierclass(pygame.sprite.sprite):
    def __init__(self):
        pygame.sprite.sprite.__init__(self)
        # 滑雪者的朝向(-2到2)
        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为向前'''
    def turn(self, num):
        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
    '''移动滑雪者'''
    def move(self):
        self.rect.centerx += self.speed[0]
        self.rect.centerx = max(20, self.rect.centerx)
        self.rect.centerx = min(620, self.rect.centerx)
    '''设置为摔倒状态'''
    def setfall(self):
        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])
 
 
'''
function:
    障碍物类
input:
    img_path: 障碍物图片路径
    location: 障碍物位置
    attribute: 障碍物类别属性
'''
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
    '''移动'''
    def move(self, num):
        self.rect.centery = self.location[1] - num
 
 
'''创建障碍物'''
def createobstacles(s, e, num=10):
    obstacles = pygame.sprite.group()
    locations = []
    for i in range(num):
        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)
    return obstacles
 
 
'''合并障碍物'''
def addobstacles(obstacles0, obstacles1):
    obstacles = pygame.sprite.group()
    for obstacle in obstacles0:
        obstacles.add(obstacle)
    for obstacle in obstacles1:
        obstacles.add(obstacle)
    return obstacles
 
 
'''显示游戏开始界面'''
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)
    while true:
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.keydown:
                return
        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()
 
 
'''主程序'''
def main():
    # 游戏初始化
    pygame.init()
    pygame.mixer.init()
    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)
    # 实例化游戏精灵
    # --滑雪者
    skier = skierclass()
    # --创建障碍物
    obstacles0 = createobstacles(20, 29)
    obstacles1 = createobstacles(10, 19)
    obstaclesflag = 0
    obstacles = addobstacles(obstacles0, obstacles1)
    # 游戏clock
    clock = pygame.time.clock()
    # 记录滑雪的距离
    distance = 0
    # 记录当前的分数
    score = 0
    # 记录当前的速度
    speed = [0, 6]
    # 游戏主循环
    while true:
        # --事件捕获
        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)
        # --更新当前游戏帧的数据
        skier.move()
        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)
 
 
'''run'''
if __name__ == '__main__':
    main();

4、并夕夕版飞机大战

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import sys
import cfg
import pygame
from modules import *
 
 
'''游戏界面'''
def gaminginterface(num_player, screen):
    # 初始化
    pygame.mixer.music.load(cfg.soundpaths['cool space music'])
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    explosion_sound = pygame.mixer.sound(cfg.soundpaths['boom'])
    fire_sound = pygame.mixer.sound(cfg.soundpaths['shot'])
    font = pygame.font.font(cfg.fontpath, 20)
    # 游戏背景图
    bg_imgs = [cfg.imagepaths['bg_big'], cfg.imagepaths['seamless_space'], cfg.imagepaths['space3']]
    bg_move_dis = 0
    bg_1 = pygame.image.load(bg_imgs[0]).convert()
    bg_2 = pygame.image.load(bg_imgs[1]).convert()
    bg_3 = pygame.image.load(bg_imgs[2]).convert()
    # 玩家, 子弹和小行星精灵组
    player_group = pygame.sprite.group()
    bullet_group = pygame.sprite.group()
    asteroid_group = pygame.sprite.group()
    # 产生小行星的时间间隔
    asteroid_ticks = 90
    for i in range(num_player):
        player_group.add(ship(i+1, cfg))
    clock = pygame.time.clock()
    # 分数
    score_1, score_2 = 0, 0
    # 游戏主循环
    while true:
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit()
        # --玩家一: ↑↓←→控制, j射击; 玩家二: wsad控制, 空格射击
        pressed_keys = pygame.key.get_pressed()
        for idx, player in enumerate(player_group):
            direction = none
            if idx == 0:
                if pressed_keys[pygame.k_up]:
                    direction = 'up'
                elif pressed_keys[pygame.k_down]:
                    direction = 'down'
                elif pressed_keys[pygame.k_left]:
                    direction = 'left'
                elif pressed_keys[pygame.k_right]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.k_j]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            elif idx == 1:
                if pressed_keys[pygame.k_w]:
                    direction = 'up'
                elif pressed_keys[pygame.k_s]:
                    direction = 'down'
                elif pressed_keys[pygame.k_a]:
                    direction = 'left'
                elif pressed_keys[pygame.k_d]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.k_space]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            if player.cooling_time > 0:
                player.cooling_time -= 1
        if (score_1 + score_2) < 500:
            background = bg_1
        elif (score_1 + score_2) < 1500:
            background = bg_2
        else:
            background = bg_3
        # --向下移动背景图实现飞船向上移动的效果
        screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
        screen.blit(background, (0, bg_move_dis))
        bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
        # --生成小行星
        if asteroid_ticks == 0:
            asteroid_ticks = 90
            asteroid_group.add(asteroid(cfg))
        else:
            asteroid_ticks -= 1
        # --画飞船
        for player in player_group:
            if pygame.sprite.spritecollide(player, asteroid_group, true, none):
                player.explode_step = 1
                explosion_sound.play()
            elif player.explode_step > 0:
                if player.explode_step > 3:
                    player_group.remove(player)
                    if len(player_group) == 0:
                        return
                else:
                    player.explode(screen)
            else:
                player.draw(screen)
        # --画子弹
        for bullet in bullet_group:
            bullet.move()
            if pygame.sprite.spritecollide(bullet, asteroid_group, true, none):
                bullet_group.remove(bullet)
                if bullet.player_idx == 1:
                    score_1 += 1
                else:
                    score_2 += 1
            else:
                bullet.draw(screen)
        # --画小行星
        for asteroid in asteroid_group:
            asteroid.move()
            asteroid.rotate()
            asteroid.draw(screen)
        # --显示分数
        score_1_text = '玩家一得分: %s' % score_1
        score_2_text = '玩家二得分: %s' % score_2
        text_1 = font.render(score_1_text, true, (0, 0, 255))
        text_2 = font.render(score_2_text, true, (255, 0, 0))
        screen.blit(text_1, (2, 5))
        screen.blit(text_2, (2, 35))
        # --屏幕刷新
        pygame.display.update()
        clock.tick(60)
 
 
'''主函数'''
def main():
    pygame.init()
    pygame.font.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(cfg.screensize)
    pygame.display.set_caption('飞机大战 —— 九歌')
    num_player = startinterface(screen, cfg)
    if num_player == 1:
        while true:
            gaminginterface(num_player=1, screen=screen)
            endinterface(screen, cfg)
    else:
        while true:
            gaminginterface(num_player=2, screen=screen)
            endinterface(screen, cfg)
 
 
'''run'''
if __name__ == '__main__':
    main()

5、打地鼠

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import cfg
import sys
import pygame
import random
from modules import *
 
 
'''游戏初始化'''
def initgame():
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(cfg.screensize)
    pygame.display.set_caption('打地鼠 —— 九歌')
    return screen
 
 
'''主函数'''
def main():
    # 初始化
    screen = initgame()
    # 加载背景音乐和其他音效
    pygame.mixer.music.load(cfg.bgm_path)
    pygame.mixer.music.play(-1)
    audios = {
        '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()
    # 分数
    your_score = 0
    flag = false
    # 初始时间
    init_time = pygame.time.get_ticks()
    # 游戏主循环
    while true:
        # --游戏时间为60s
        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.reset()
            mole.setposition(hole_pos)
            pygame.time.set_timer(change_hole_event, 650)
            flag = true
        elif time_remain == 20 and flag:
            hole_pos = random.choice(cfg.hole_positions)
            mole.reset()
            mole.setposition(hole_pos)
            pygame.time.set_timer(change_hole_event, 500)
            flag = false
        # --倒计时音效
        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()
        clock.tick(60)
    # 读取最佳分数(try块避免第一次游戏无.rec文件)
    try:
        best_score = int(open(cfg.record_path).read())
    except:
        best_score = 0
    # 若当前分数大于最佳分数则更新最佳分数
    if your_score > best_score:
        f = open(cfg.record_path, 'w')
        f.write(str(your_score))
        f.close()
    # 结束界面
    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)
    return is_restart
 
 
'''run'''
if __name__ == '__main__':
    while true:
        is_restart = main()
        if not is_restart:
            break

6、小恐龙

玩法:上下控制起跳躲避

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import cfg
import sys
import random
import pygame
from modules import *
 
 
'''main'''
def main(highest_score):
    # 游戏初始化
    pygame.init()
    screen = pygame.display.set_mode(cfg.screensize)
    pygame.display.set_caption('九歌')
    # 导入所有声音文件
    sounds = {}
    for key, value in cfg.audio_paths.items():
        sounds[key] = pygame.mixer.sound(value)
    # 游戏开始界面
    gamestartinterface(screen, sounds, cfg)
    # 定义一些游戏中必要的元素和变量
    score = 0
    score_board = scoreboard(cfg.image_paths['numbers'], position=(534, 15), bg_color=cfg.background_color)
    highest_score = highest_score
    highest_score_board = scoreboard(cfg.image_paths['numbers'], position=(435, 15), bg_color=cfg.background_color, is_highest=true)
    dino = dinosaur(cfg.image_paths['dino'])
    ground = ground(cfg.image_paths['ground'], position=(0, cfg.screensize[1]))
    cloud_sprites_group = pygame.sprite.group()
    cactus_sprites_group = pygame.sprite.group()
    ptera_sprites_group = pygame.sprite.group()
    add_obstacle_timer = 0
    score_timer = 0
    # 游戏主循环
    clock = pygame.time.clock()
    while true:
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.keydown:
                if event.key == pygame.k_space or event.key == pygame.k_up:
                    dino.jump(sounds)
                elif event.key == pygame.k_down:
                    dino.duck()
            elif event.type == pygame.keyup and event.key == pygame.k_down:
                dino.unduck()
        screen.fill(cfg.background_color)
        # --随机添加云
        if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10:
            cloud_sprites_group.add(cloud(cfg.image_paths['cloud'], position=(cfg.screensize[0], random.randrange(30, 75))))
        # --随机添加仙人掌/飞龙
        add_obstacle_timer += 1
        if add_obstacle_timer > random.randrange(50, 150):
            add_obstacle_timer = 0
            random_value = random.randrange(0, 10)
            if random_value >= 5 and random_value <= 7:
                cactus_sprites_group.add(cactus(cfg.image_paths['cacti']))
            else:
                position_ys = [cfg.screensize[1]*0.82, cfg.screensize[1]*0.75, cfg.screensize[1]*0.60, cfg.screensize[1]*0.20]
                ptera_sprites_group.add(ptera(cfg.image_paths['ptera'], position=(600, random.choice(position_ys))))
        # --更新游戏元素
        dino.update()
        ground.update()
        cloud_sprites_group.update()
        cactus_sprites_group.update()
        ptera_sprites_group.update()
        score_timer += 1
        if score_timer > (cfg.fps//12):
            score_timer = 0
            score += 1
            score = min(score, 99999)
            if score > highest_score:
                highest_score = score
            if score % 100 == 0:
                sounds['point'].play()
            if score % 1000 == 0:
                ground.speed -= 1
                for item in cloud_sprites_group:
                    item.speed -= 1
                for item in cactus_sprites_group:
                    item.speed -= 1
                for item in ptera_sprites_group:
                    item.speed -= 1
        # --碰撞检测
        for item in cactus_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        for item in ptera_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        # --将游戏元素画到屏幕上
        dino.draw(screen)
        ground.draw(screen)
        cloud_sprites_group.draw(screen)
        cactus_sprites_group.draw(screen)
        ptera_sprites_group.draw(screen)
        score_board.set(score)
        highest_score_board.set(highest_score)
        score_board.draw(screen)
        highest_score_board.draw(screen)
        # --更新屏幕
        pygame.display.update()
        clock.tick(cfg.fps)
        # --游戏是否结束
        if dino.is_dead:
            break
    # 游戏结束界面
    return gameendinterface(screen, cfg), highest_score
 
 
'''run'''
if __name__ == '__main__':
    highest_score = 0
    while true:
        flag, highest_score = main(highest_score)
        if not flag: break

7、消消乐

玩法:三个相连就能消除

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import os
import sys
import cfg
import pygame
from modules import *
 
 
'''游戏主程序'''
def main():
    pygame.init()
    screen = pygame.display.set_mode(cfg.screensize)
    pygame.display.set_caption('gemgem —— 九歌')
    # 加载背景音乐
    pygame.mixer.init()
    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 = {}
    sounds['mismatch'] = pygame.mixer.sound(os.path.join(cfg.rootdir, 'resources/audios/badswap.wav'))
    sounds['match'] = []
    for i in range(6):
        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)
    # 图片加载
    gem_imgs = []
    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)
    while true:
        score = game.start()
        flag = false
        # 一轮游戏结束后玩家选择重玩或者退出
        while true:
            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
            if flag:
                break
            screen.fill((135, 206, 235))
            text0 = 'final score: %s' % score
            text1 = 'press <r> to restart the game.'
            text2 = 'press <esc> to quit the game.'
            y = 150
            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)
                else:
                    rect.left, rect.top = (126.5, y)
                y += 100
                screen.blit(text_render, rect)
            pygame.display.update()
        game.reset()
 
 
'''run'''
if __name__ == '__main__':
    main()

8、俄罗斯方块

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

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import os
import sys
import random
from modules import *
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)
        # 是否暂停ing
        self.is_paused = false
        # 是否开始ing
        self.is_started = false
        self.initui()
    '''界面初始化'''
    def initui(self):
        # icon
        self.setwindowicon(qicon(os.path.join(os.getcwd(), 'resources/icon.jpg')))
        # 块大小
        self.grid_size = 22
        # 游戏帧率
        self.fps = 200
        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.start()
        self.center()
        self.setwindowtitle('tetris —— 九歌')
        self.show()
        self.setfixedsize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())
    '''游戏界面移动到屏幕中间'''
    def center(self):
        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()
        self.update()
    '''开始'''
    def start(self):
        if self.is_started:
            return
        self.is_started = true
        self.inner_board.createnewtetris()
        self.timer.start(self.fps, self)
    '''暂停/不暂停'''
    def pause(self):
        if not self.is_started:
            return
        self.is_paused = not self.is_paused
        if self.is_paused:
            self.timer.stop()
            self.external_board.score_signal.emit('paused')
        else:
            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()
        else:
            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)
            return
        key = event.key()
        # p键暂停
        if key == qt.key_p:
            self.pause()
            return
        if self.is_paused:
            return
        # 向左
        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()
        else:
            super(tetrisgame, self).keypressevent(event)
        self.updatewindow()
 
 
'''run'''
if __name__ == '__main__':
    app = qapplication([])
    tetris = tetrisgame()
    sys.exit(app.exec_())

9、贪吃蛇

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

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import cfg
import sys
import pygame
from modules import *
 
 
'''主函数'''
def main(cfg):
    # 游戏初始化
    pygame.init()
    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)
    # 游戏主循环
    snake = snake(cfg)
    apple = apple(cfg, snake.coords)
    score = 0
    while true:
        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)
            score += 1
        # --判断游戏是否结束
        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)
 
 
'''run'''
if __name__ == '__main__':
    while true:
        if not main(cfg):
            break

10、24点小游戏

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

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import os
import sys
import pygame
from cfg import *
from modules import *
from fractions import fraction
 
 
'''检查控件是否被点击'''
def checkclicked(group, mouse_pos, group_type='number'):
    selected = []
    # 数字卡片/运算符卡片
    if group_type == grouptypes[0] or group_type == grouptypes[1]:
        max_selected = 2 if group_type == grouptypes[0] else 1
        num_selected = 0
        for each in group:
            num_selected += int(each.is_selected)
        for each in group:
            if each.rect.collidepoint(mouse_pos):
                if each.is_selected:
                    each.is_selected = not each.is_selected
                    num_selected -= 1
                    each.select_order = none
                else:
                    if num_selected < max_selected:
                        each.is_selected = not each.is_selected
                        num_selected += 1
                        each.select_order = str(num_selected)
            if each.is_selected:
                selected.append(each.attribute)
    # 按钮卡片
    elif group_type == grouptypes[2]:
        for each in group:
            if each.rect.collidepoint(mouse_pos):
                each.is_selected = true
                selected.append(each.attribute)
    # 抛出异常
    else:
        raise valueerror('checkclicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *grouptypes))
    return selected
 
 
'''获取数字精灵组'''
def getnumberspritesgroup(numbers):
    number_sprites_group = pygame.sprite.group()
    for idx, number in enumerate(numbers):
        args = (*numbercard_positions[idx], str(number), numberfont, numberfont_colors, numbercard_colors, str(number))
        number_sprites_group.add(card(*args))
    return number_sprites_group
 
 
'''获取运算符精灵组'''
def getoperatorspritesgroup(operators):
    operator_sprites_group = pygame.sprite.group()
    for idx, operator in enumerate(operators):
        args = (*operatorcard_positions[idx], str(operator), operatorfont, opreatorfont_colors, operatorcard_colors, str(operator))
        operator_sprites_group.add(card(*args))
    return operator_sprites_group
 
 
'''获取按钮精灵组'''
def getbuttonspritesgroup(buttons):
    button_sprites_group = pygame.sprite.group()
    for idx, button in enumerate(buttons):
        args = (*buttoncard_positions[idx], str(button), buttonfont, buttonfont_colors, buttoncard_colors, str(button))
        button_sprites_group.add(button(*args))
    return button_sprites_group
 
 
'''计算'''
def calculate(number1, number2, operator):
    operator_map = {'+': '+', '-': '-', '×': '*', '÷': '/'}
    try:
        result = str(eval(number1+operator_map[operator]+number2))
        return result if '.' not in result else str(fraction(number1+operator_map[operator]+number2))
    except:
        return none
 
 
'''在屏幕上显示信息'''
def showinfo(text, screen):
    rect = pygame.rect(200, 180, 400, 200)
    pygame.draw.rect(screen, papayawhip, rect)
    font = pygame.font.font(fontpath, 40)
    text_render = font.render(text, true, black)
    font_size = font.size(text)
    screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2))
 
 
'''主函数'''
def main():
    # 初始化, 导入必要的游戏素材
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(screensize)
    pygame.display.set_caption('24 point —— 九歌')
    win_sound = pygame.mixer.sound(audiowinpath)
    lose_sound = pygame.mixer.sound(audiolosepath)
    warn_sound = pygame.mixer.sound(audiowarnpath)
    pygame.mixer.music.load(bgmpath)
    pygame.mixer.music.play(-1, 0.0)
    # 24点游戏生成器
    game24_gen = game24generator()
    game24_gen.generate()
    # 精灵组
    # --数字
    number_sprites_group = getnumberspritesgroup(game24_gen.numbers_now)
    # --运算符
    operator_sprites_group = getoperatorspritesgroup(opreators)
    # --按钮
    button_sprites_group = getbuttonspritesgroup(buttons)
    # 游戏主循环
    clock = pygame.time.clock()
    selected_numbers = []
    selected_operators = []
    selected_buttons = []
    is_win = false
    while true:
        for event in pygame.event.get():
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit(-1)
            elif event.type == pygame.mousebuttonup:
                mouse_pos = pygame.mouse.get_pos()
                selected_numbers = checkclicked(number_sprites_group, mouse_pos, 'number')
                selected_operators = checkclicked(operator_sprites_group, mouse_pos, 'opreator')
                selected_buttons = checkclicked(button_sprites_group, mouse_pos, 'button')
        screen.fill(azure)
        # 更新数字
        if len(selected_numbers) == 2 and len(selected_operators) == 1:
            noselected_numbers = []
            for each in number_sprites_group:
                if each.is_selected:
                    if each.select_order == '1':
                        selected_number1 = each.attribute
                    elif each.select_order == '2':
                        selected_number2 = each.attribute
                    else:
                        raise valueerror('unknow select_order %s, expect 1 or 2...' % each.select_order)
                else:
                    noselected_numbers.append(each.attribute)
                each.is_selected = false
            for each in operator_sprites_group:
                each.is_selected = false
            result = calculate(selected_number1, selected_number2, *selected_operators)
            if result is not none:
                game24_gen.numbers_now = noselected_numbers + [result]
                is_win = game24_gen.check()
                if is_win:
                    win_sound.play()
                if not is_win and len(game24_gen.numbers_now) == 1:
                    lose_sound.play()
            else:
                warn_sound.play()
            selected_numbers = []
            selected_operators = []
            number_sprites_group = getnumberspritesgroup(game24_gen.numbers_now)
        # 精灵都画到screen上
        for each in number_sprites_group:
            each.draw(screen, pygame.mouse.get_pos())
        for each in operator_sprites_group:
            each.draw(screen, pygame.mouse.get_pos())
        for each in button_sprites_group:
            if selected_buttons and selected_buttons[0] in ['reset', 'next']:
                is_win = false
            if selected_buttons and each.attribute == selected_buttons[0]:
                each.is_selected = false
                number_sprites_group = each.do(game24_gen, getnumberspritesgroup, number_sprites_group, button_sprites_group)
                selected_buttons = []
            each.draw(screen, pygame.mouse.get_pos())
        # 游戏胜利
        if is_win:
            showinfo('congratulations', screen)
        # 游戏失败
        if not is_win and len(game24_gen.numbers_now) == 1:
            showinfo('game over', screen)
        pygame.display.flip()
        clock.tick(30)
 
 
'''run'''
if __name__ == '__main__':
    main()

11、平衡木

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

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
import cfg
from modules import breakoutclone
 
 
'''主函数'''
def main():
    game = breakoutclone(cfg)
    game.run()
 
 
'''run'''
if __name__ == '__main__':
    main()

12、外星人入侵

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

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import sys
import cfg
import random
import pygame
from modules import *
 
 
'''开始游戏'''
def startgame(screen):
    clock = pygame.time.clock()
    # 加载字体
    font = pygame.font.sysfont('arial', 18)
    if not os.path.isfile('score'):
        f = open('score', 'w')
        f.write('0')
        f.close()
    with open('score', 'r') as f:
        highest_score = int(f.read().strip())
    # 敌方
    enemies_group = pygame.sprite.group()
    for i in range(55):
        if i < 11:
            enemy = enemysprite('small', i, cfg.white, cfg.white)
        elif i < 33:
            enemy = enemysprite('medium', i, cfg.white, cfg.white)
        else:
            enemy = enemysprite('large', i, cfg.white, cfg.white)
        enemy.rect.x = 85 + (i % 11) * 50
        enemy.rect.y = 120 + (i // 11) * 45
        enemies_group.add(enemy)
    boomed_enemies_group = pygame.sprite.group()
    en_bullets_group = pygame.sprite.group()
    ufo = ufosprite(color=cfg.red)
    # 我方
    myaircraft = aircraftsprite(color=cfg.green, bullet_color=cfg.white)
    my_bullets_group = pygame.sprite.group()
    # 用于控制敌方位置更新
    # --移动一行
    enemy_move_count = 24
    enemy_move_interval = 24
    enemy_move_flag = false
    # --改变移动方向(改变方向的同时集体下降一次)
    enemy_change_direction_count = 0
    enemy_change_direction_interval = 60
    enemy_need_down = false
    enemy_move_right = true
    enemy_need_move_row = 6
    enemy_max_row = 5
    # 用于控制敌方发射子弹
    enemy_shot_interval = 100
    enemy_shot_count = 0
    enemy_shot_flag = false
    # 游戏进行中
    running = true
    is_win = false
    # 主循环
    while running:
        screen.fill(cfg.black)
        for event in pygame.event.get():
            # --点右上角的x或者按esc键退出游戏
            if event.type == pygame.quit:
                pygame.quit()
                sys.exit()
            if event.type == pygame.keydown:
                if event.key == pygame.k_escape:
                    pygame.quit()
                    sys.exit()
            # --射击
            if event.type == pygame.mousebuttondown:
                my_bullet = myaircraft.shot()
                if my_bullet:
                    my_bullets_group.add(my_bullet)
        # --我方子弹与敌方/ufo碰撞检测
        for enemy in enemies_group:
            if pygame.sprite.spritecollide(enemy, my_bullets_group, true, none):
                boomed_enemies_group.add(enemy)
                enemies_group.remove(enemy)
                myaircraft.score += enemy.reward
        if pygame.sprite.spritecollide(ufo, my_bullets_group, true, none):
            ufo.is_dead = true
            myaircraft.score += ufo.reward
        # --更新并画敌方
        # ----敌方子弹
        enemy_shot_count += 1
        if enemy_shot_count > enemy_shot_interval:
            enemy_shot_flag = true
            enemies_survive_list = [enemy.number for enemy in enemies_group]
            shot_number = random.choice(enemies_survive_list)
            enemy_shot_count = 0
        # ----敌方移动
        enemy_move_count += 1
        if enemy_move_count > enemy_move_interval:
            enemy_move_count = 0
            enemy_move_flag = true
            enemy_need_move_row -= 1
            if enemy_need_move_row == 0:
                enemy_need_move_row = enemy_max_row
            enemy_change_direction_count += 1
            if enemy_change_direction_count > enemy_change_direction_interval:
                enemy_change_direction_count = 1
                enemy_move_right = not enemy_move_right
                enemy_need_down = true
                # ----每次下降提高移动和射击速度
                enemy_move_interval = max(15, enemy_move_interval-3)
                enemy_shot_interval = max(50, enemy_move_interval-10)
        # ----遍历更新
        for enemy in enemies_group:
            if enemy_shot_flag:
                if enemy.number == shot_number:
                    en_bullet = enemy.shot()
                    en_bullets_group.add(en_bullet)
            if enemy_move_flag:
                if enemy.number in range((enemy_need_move_row-1)*11, enemy_need_move_row*11):
                    if enemy_move_right:
                        enemy.update('right', cfg.screensize[1])
                    else:
                        enemy.update('left', cfg.screensize[1])
            else:
                enemy.update(none, cfg.screensize[1])
            if enemy_need_down:
                if enemy.update('down', cfg.screensize[1]):
                    running = false
                    is_win = false
                enemy.change_count -= 1
            enemy.draw(screen)
        enemy_move_flag = false
        enemy_need_down = false
        enemy_shot_flag = false
        # ----敌方爆炸特效
        for boomed_enemy in boomed_enemies_group:
            if boomed_enemy.boom(screen):
                boomed_enemies_group.remove(boomed_enemy)
                del boomed_enemy
        # --敌方子弹与我方飞船碰撞检测
        if not myaircraft.one_dead:
            if pygame.sprite.spritecollide(myaircraft, en_bullets_group, true, none):
                myaircraft.one_dead = true
        if myaircraft.one_dead:
            if myaircraft.boom(screen):
                myaircraft.resetboom()
                myaircraft.num_life -= 1
                if myaircraft.num_life < 1:
                    running = false
                    is_win = false
        else:
            # ----更新飞船
            myaircraft.update(cfg.screensize[0])
            # ----画飞船
            myaircraft.draw(screen)
        if (not ufo.has_boomed) and (ufo.is_dead):
            if ufo.boom(screen):
                ufo.has_boomed = true
        else:
            # ----更新ufo
            ufo.update(cfg.screensize[0])
            # ----画ufo
            ufo.draw(screen)
        # --画我方飞船子弹
        for bullet in my_bullets_group:
            if bullet.update():
                my_bullets_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        # --画敌方子弹
        for bullet in en_bullets_group:
            if bullet.update(cfg.screensize[1]):
                en_bullets_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        if myaircraft.score > highest_score:
            highest_score = myaircraft.score
        # --得分每增加2000我方飞船增加一条生命
        if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old_score):
            myaircraft.old_score = myaircraft.score
            myaircraft.num_life = min(myaircraft.num_life + 1, myaircraft.max_num_life)
        # --敌人都死光了的话就胜利了
        if len(enemies_group) < 1:
            is_win = true
            running = false
        # --显示文字
        # ----当前得分
        showtext(screen, 'score: ', cfg.white, font, 200, 8)
        showtext(screen, str(myaircraft.score), cfg.white, font, 200, 24)
        # ----敌人数量
        showtext(screen, 'enemy: ', cfg.white, font, 370, 8)
        showtext(screen, str(len(enemies_group)), cfg.white, font, 370, 24)
        # ----历史最高分
        showtext(screen, 'highest: ', cfg.white, font, 540, 8)
        showtext(screen, str(highest_score), cfg.white, font, 540, 24)
        # ----fps
        showtext(screen, 'fps: ' + str(int(clock.get_fps())), cfg.red, font, 8, 8)
        # --显示剩余生命值
        showlife(screen, myaircraft.num_life, cfg.green)
        pygame.display.update()
        clock.tick(cfg.fps)
    with open('score', 'w') as f:
        f.write(str(highest_score))
    return is_win
 
 
'''主函数'''
def main():
    # 初始化
    pygame.init()
    pygame.display.set_caption('外星人入侵 —— 九歌')
    screen = pygame.display.set_mode(cfg.screensize)
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.bgmpath)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    while true:
        is_win = startgame(screen)
        endinterface(screen, cfg.black, is_win)
 
 
'''run'''
if __name__ == '__main__':
    main()

13、贪心鸟

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

14 个Python小游戏 源码分享

14、井字棋888‘'

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

14 个Python小游戏 源码分享

源码分享:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from tkinter import *
import tkinter.messagebox as msg
 
root = tk()
root.title('tic-tac-toe---project gurukul')
# labels
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
mark = ''
 
# counting the no. of click
count = 0
 
panels = ["panel"] * 10
 
 
def win(panels, sign):
    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))
 
 
def checker(digit):
    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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button1.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button2.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button3.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button4.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button5.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button6.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button7.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button8.config(text=mark)
        count = count + 1
        sign = mark
 
        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:
            mark = 'x'
            panels[digit] = mark
        elif count % 2 != 0:
            mark = 'o'
            panels[digit] = mark
 
        button9.config(text=mark)
        count = count + 1
        sign = mark
 
        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")
        root.destroy()
 
 
####define buttons
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)
 
root.mainloop()

到此这篇关于14 个python小游戏 源码分享的文章就介绍到这了,更多相关14 个python小游戏内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/AI19970205/article/details/120223542

延伸 · 阅读

精彩推荐