当前位置:   article > 正文

可以自己实现的Python小游戏,共十四个可收藏可直接拿走~_python 做的游戏

python 做的游戏

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

1、吃金币

源码分享:

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

  • 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

2、打乒乓

源码分享:

import sys
import cfg
import pygame
from modules import \*
 
 
'''定义按钮'''
def Button(screen, position, text, button\_size=(200, 50)):
    left, top = position
    bwidth, bheight = button\_size
    pygame.draw.line(screen, (150, 150, 150), (left, top), (left+bwidth, top), 5)
    pygame.draw.line(screen, (150, 150, 150), (left, top-2), (left, top+bheight), 5)
    pygame.draw.line(screen, (50, 50, 50), (left, top+bheight), (left+bwidth, top+bheight), 5)
    pygame.draw.line(screen, (50, 50, 50), (left+bwidth, top+bheight), (left+bwidth, top), 5)
    pygame.draw.rect(screen, (100, 100, 100), (left, top, bwidth, bheight))
    font = pygame.font.Font(cfg.FONTPATH, 30)
    text\_render = font.render(text, 1, (255, 235, 205))
    return screen.blit(text\_render, (left+50, top+10))
 
 
'''
Function:
    开始界面
Input:
    --screen: 游戏界面
Return:
    --game\_mode: 1(单人模式)/2(双人模式)
'''
def startInterface(screen):
    clock = pygame.time.Clock()
    while True:
        screen.fill((41, 36, 33))
        button\_1 = Button(screen, (150, 175), '1 Player')
        button\_2 = Button(screen, (150, 275), '2 Player')
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if button\_1.collidepoint(pygame.mouse.get\_pos()):
                    return 1
                elif button\_2.collidepoint(pygame.mouse.get\_pos()):
                    return 2
        clock.tick(10)
        pygame.display.update()
 
 
'''结束界面'''
def endInterface(screen, score\_left, score\_right):
    clock = pygame.time.Clock()
    font1 = pygame.font.Font(cfg.FONTPATH, 30)
    font2 = pygame.font.Font(cfg.FONTPATH, 20)
    msg = 'Player on left won!' if score\_left > score\_right else 'Player on right won!'
    texts = \[font1.render(msg, True, cfg.WHITE),
            font2.render('Press ESCAPE to quit.', True, cfg.WHITE),
            font2.render('Press ENTER to continue or play again.', True, cfg.WHITE)\]
    positions = \[\[120, 200\], \[155, 270\], \[80, 300\]\]
    while True:
        screen.fill((41, 36, 33))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K\_RETURN:
                    return
                elif event.key == pygame.K\_ESCAPE:
                    sys.exit()
                    pygame.quit()
        for text, pos in zip(texts, positions):
            screen.blit(text, pos)
        clock.tick(10)
        pygame.display.update()
 
 
'''运行游戏Demo'''
def runDemo(screen):
    # 加载游戏素材
    hit\_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
    goal\_sound = pygame.mixer.Sound(cfg.GOALSOUNDPATH)
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.play(-1, 0.0)
    font = pygame.font.Font(cfg.FONTPATH, 50)
    # 开始界面
    game\_mode = startInterface(screen)
    # 游戏主循环
    # --左边球拍(ws控制, 仅双人模式时可控制)
    score\_left = 0
    racket\_left = Racket(cfg.RACKETPICPATH, 'LEFT', cfg)
    # --右边球拍(↑↓控制)
    score\_right = 0
    racket\_right = Racket(cfg.RACKETPICPATH, 'RIGHT', cfg)
    # --球
    ball = Ball(cfg.BALLPICPATH, cfg)
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(-1)
        screen.fill((41, 36, 33))
        # 玩家操作
        pressed\_keys = pygame.key.get\_pressed()
        if pressed\_keys\[pygame.K\_UP\]:
            racket\_right.move('UP')
        elif pressed\_keys\[pygame.K\_DOWN\]:
            racket\_right.move('DOWN')
        if game\_mode == 2:
            if pressed\_keys\[pygame.K\_w\]:
                racket\_left.move('UP')
            elif pressed\_keys\[pygame.K\_s\]:
                racket\_left.move('DOWN')
        else:
            racket\_left.automove(ball)
        # 球运动
        scores = ball.move(ball, racket\_left, racket\_right, hit\_sound, goal\_sound)
        score\_left += scores\[0\]
        score\_right += scores\[1\]
        # 显示
        # --分隔线
        pygame.draw.rect(screen, cfg.WHITE, (247, 0, 6, 500))
        # --球
        ball.draw(screen)
        # --拍
        racket\_left.draw(screen)
        racket\_right.draw(screen)
        # --得分
        screen.blit(font.render(str(score\_left), False, cfg.WHITE), (150, 10))
        screen.blit(font.render(str(score\_right), False, cfg.WHITE), (300, 10))
        if score\_left == 11 or score\_right == 11:
            return score\_left, score\_right
        clock.tick(100)
        pygame.display.update()
 
 
'''主函数'''
def main():
    # 初始化
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set\_mode((cfg.WIDTH, cfg.HEIGHT))
    pygame.display.set\_caption('pingpong —— 九歌')
    # 开始游戏
    while True:
        score\_left, score\_right = runDemo(screen)
        endInterface(screen, score\_left, score\_right)
 
 
'''run'''
if \_\_name\_\_ == '\_\_main\_\_':
    main()

  • 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

3、滑雪

源码分享:

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

  • 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

4、并夕夕版飞机大战

源码分享:

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

  • 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

5、打地鼠

源码分享:

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

  • 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

6、小恐龙


**玩法:**上下控制起跳躲避

源码分享:

 
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



  • 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

7、消消乐


**玩法:**三个相连就能消除

源码分享:

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



  • 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

8、俄罗斯方块


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

源码分享:

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



  • 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

9、贪吃蛇


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

源码分享:

 
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



  • 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

10、24点小游戏


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

源码分享:

 
import os
import sys
import pygame
from cfg import \*
from modules import \*
from fractions import Fraction
 
 
'''检查控件是否被点击'''
def checkClicked(group, mouse\_pos, group\_type='NUMBER'):
    selected = \[\]
    # 数字卡片/运算符卡片
    if group\_type == GROUPTYPES\[0\] or group\_type == GROUPTYPES\[1\]:
        max\_selected = 2 if group\_type == GROUPTYPES\[0\] else 1
        num\_selected = 0
        for each in group:
            num\_selected += int(each.is\_selected)
        for each in group:
            if each.rect.collidepoint(mouse\_pos):
                if each.is\_selected:
                    each.is\_selected = not each.is\_selected
                    num\_selected -= 1
                    each.select\_order = None
                else:
                    if num\_selected < max\_selected:
                        each.is\_selected = not each.is\_selected
                        num\_selected += 1
                        each.select\_order = str(num\_selected)
            if each.is\_selected:
                selected.append(each.attribute)
    # 按钮卡片
    elif group\_type == GROUPTYPES\[2\]:
        for each in group:
            if each.rect.collidepoint(mouse\_pos):
                each.is\_selected = True
                selected.append(each.attribute)
    # 抛出异常
    else:
        raise ValueError('checkClicked.group\_type unsupport %s, expect %s, %s or %s...' % (group\_type, \*GROUPTYPES))
    return selected
 
 
'''获取数字精灵组'''
def getNumberSpritesGroup(numbers):
    number\_sprites\_group = pygame.sprite.Group()
    for idx, number in enumerate(numbers):
        args = (\*NUMBERCARD\_POSITIONS\[idx\], str(number), NUMBERFONT, NUMBERFONT\_COLORS, NUMBERCARD\_COLORS, str(number))
        number\_sprites\_group.add(Card(\*args))
    return number\_sprites\_group
 
 
'''获取运算符精灵组'''
def getOperatorSpritesGroup(operators):
    operator\_sprites\_group = pygame.sprite.Group()
    for idx, operator in enumerate(operators):
        args = (\*OPERATORCARD\_POSITIONS\[idx\], str(operator), OPERATORFONT, OPREATORFONT\_COLORS, OPERATORCARD\_COLORS, str(operator))
        operator\_sprites\_group.add(Card(\*args))
    return operator\_sprites\_group
 
 
'''获取按钮精灵组'''
def getButtonSpritesGroup(buttons):
    button\_sprites\_group = pygame.sprite.Group()
    for idx, button in enumerate(buttons):
        args = (\*BUTTONCARD\_POSITIONS\[idx\], str(button), BUTTONFONT, BUTTONFONT\_COLORS, BUTTONCARD\_COLORS, str(button))
        button\_sprites\_group.add(Button(\*args))
    return button\_sprites\_group
 
 
'''计算'''
def calculate(number1, number2, operator):
    operator\_map = {'+': '+', '-': '-', '×': '\*', '÷': '/'}
    try:
        result = str(eval(number1+operator\_map\[operator\]+number2))
        return result if '.' not in result else str(Fraction(number1+operator\_map\[operator\]+number2))
    except:
        return None
 
 
'''在屏幕上显示信息'''
def showInfo(text, screen):
    rect = pygame.Rect(200, 180, 400, 200)
    pygame.draw.rect(screen, PAPAYAWHIP, rect)
    font = pygame.font.Font(FONTPATH, 40)
    text\_render = font.render(text, True, BLACK)
    font\_size = font.size(text)
    screen.blit(text\_render, (rect.x+(rect.width-font\_size\[0\])/2, rect.y+(rect.height-font\_size\[1\])/2))
 
 
'''主函数'''
def main():
    # 初始化, 导入必要的游戏素材
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set\_mode(SCREENSIZE)
    pygame.display.set\_caption('24 point —— 九歌')
    win\_sound = pygame.mixer.Sound(AUDIOWINPATH)
    lose\_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
    warn\_sound = pygame.mixer.Sound(AUDIOWARNPATH)
    pygame.mixer.music.load(BGMPATH)
    pygame.mixer.music.play(-1, 0.0)
    # 24点游戏生成器
    game24\_gen = game24Generator()
    game24\_gen.generate()
    # 精灵组
    # --数字
    number\_sprites\_group = getNumberSpritesGroup(game24\_gen.numbers\_now)
    # --运算符
    operator\_sprites\_group = getOperatorSpritesGroup(OPREATORS)
    # --按钮
    button\_sprites\_group = getButtonSpritesGroup(BUTTONS)
    # 游戏主循环
    clock = pygame.time.Clock()
    selected\_numbers = \[\]
    selected\_operators = \[\]
    selected\_buttons = \[\]
    is\_win = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(-1)
            elif event.type == pygame.MOUSEBUTTONUP:
                mouse\_pos = pygame.mouse.get\_pos()
                selected\_numbers = checkClicked(number\_sprites\_group, mouse\_pos, 'NUMBER')
                selected\_operators = checkClicked(operator\_sprites\_group, mouse\_pos, 'OPREATOR')
                selected\_buttons = checkClicked(button\_sprites\_group, mouse\_pos, 'BUTTON')
        screen.fill(AZURE)
        # 更新数字
        if len(selected\_numbers) == 2 and len(selected\_operators) == 1:
            noselected\_numbers = \[\]
            for each in number\_sprites\_group:
                if each.is\_selected:
                    if each.select\_order == '1':
                        selected\_number1 = each.attribute
                    elif each.select\_order == '2':
                        selected\_number2 = each.attribute
                    else:
                        raise ValueError('Unknow select\_order %s, expect 1 or 2...' % each.select\_order)
                else:
                    noselected\_numbers.append(each.attribute)
                each.is\_selected = False
            for each in operator\_sprites\_group:
                each.is\_selected = False
            result = calculate(selected\_number1, selected\_number2, \*selected\_operators)
            if result is not None:
                game24\_gen.numbers\_now = noselected\_numbers + \[result\]
                is\_win = game24\_gen.check()
                if is\_win:
                    win\_sound.play()
                if not is\_win and len(game24\_gen.numbers\_now) == 1:
                    lose\_sound.play()
            else:
                warn\_sound.play()
            selected\_numbers = \[\]
            selected\_operators = \[\]
            number\_sprites\_group = getNumberSpritesGroup(game24\_gen.numbers\_now)
        # 精灵都画到screen上
        for each in number\_sprites\_group:
            each.draw(screen, pygame.mouse.get\_pos())
        for each in operator\_sprites\_group:
            each.draw(screen, pygame.mouse.get\_pos())
        for each in button\_sprites\_group:
            if selected\_buttons and selected\_buttons\[0\] in \['RESET', 'NEXT'\]:
                is\_win = False
            if selected\_buttons and each.attribute == selected\_buttons\[0\]:
                each.is\_selected = False
                number\_sprites\_group = each.do(game24\_gen, getNumberSpritesGroup, number\_sprites\_group, button\_sprites\_group)
                selected\_buttons = \[\]
            each.draw(screen, pygame.mouse.get\_pos())
        # 游戏胜利
        if is\_win:
            showInfo('Congratulations', screen)
        # 游戏失败
        if not is\_win and len(game24\_gen.numbers\_now) == 1:
            showInfo('Game Over', screen)
        pygame.display.flip()
        clock.tick(30)
 
 
'''run'''
if \_\_name\_\_ == '\_\_main\_\_':
    main()



  • 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

11、平衡木


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

源码分享:

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



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

12、外星人入侵


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

源码分享:

 
import os
import sys
import cfg
import random
import pygame
from modules import \*
 
 
'''开始游戏'''
def startGame(screen):
    clock = pygame.time.Clock()
    # 加载字体
    font = pygame.font.SysFont('arial', 18)
    if not os.path.isfile('score'):
        f = open('score', 'w')
        f.write('0')
        f.close()
    with open('score', 'r') as f:
        highest\_score = int(f.read().strip())
    # 敌方
    enemies\_group = pygame.sprite.Group()
    for i in range(55):
        if i < 11:
            enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)
        elif i < 33:
            enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)
        else:
            enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)
        enemy.rect.x = 85 + (i % 11) \* 50
        enemy.rect.y = 120 + (i // 11) \* 45
        enemies\_group.add(enemy)
    boomed\_enemies\_group = pygame.sprite.Group()
    en\_bullets\_group = pygame.sprite.Group()
    ufo = ufoSprite(color=cfg.RED)
    # 我方
    myaircraft = aircraftSprite(color=cfg.GREEN, bullet\_color=cfg.WHITE)
    my\_bullets\_group = pygame.sprite.Group()
    # 用于控制敌方位置更新
    # --移动一行
    enemy\_move\_count = 24
    enemy\_move\_interval = 24
    enemy\_move\_flag = False
    # --改变移动方向(改变方向的同时集体下降一次)
    enemy\_change\_direction\_count = 0
    enemy\_change\_direction\_interval = 60
    enemy\_need\_down = False
    enemy\_move\_right = True
    enemy\_need\_move\_row = 6
    enemy\_max\_row = 5
    # 用于控制敌方发射子弹
    enemy\_shot\_interval = 100
    enemy\_shot\_count = 0
    enemy\_shot\_flag = False
    # 游戏进行中
    running = True
    is\_win = False
    # 主循环
    while running:
        screen.fill(cfg.BLACK)
        for event in pygame.event.get():
            # --点右上角的X或者按Esc键退出游戏
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K\_ESCAPE:
                    pygame.quit()
                    sys.exit()
            # --射击
            if event.type == pygame.MOUSEBUTTONDOWN:
                my\_bullet = myaircraft.shot()
                if my\_bullet:
                    my\_bullets\_group.add(my\_bullet)
        # --我方子弹与敌方/UFO碰撞检测
        for enemy in enemies\_group:
            if pygame.sprite.spritecollide(enemy, my\_bullets\_group, True, None):
                boomed\_enemies\_group.add(enemy)
                enemies\_group.remove(enemy)
                myaircraft.score += enemy.reward
        if pygame.sprite.spritecollide(ufo, my\_bullets\_group, True, None):
            ufo.is\_dead = True
            myaircraft.score += ufo.reward
        # --更新并画敌方
        # ----敌方子弹
        enemy\_shot\_count += 1
        if enemy\_shot\_count > enemy\_shot\_interval:
            enemy\_shot\_flag = True
            enemies\_survive\_list = \[enemy.number for enemy in enemies\_group\]
            shot\_number = random.choice(enemies\_survive\_list)
            enemy\_shot\_count = 0
        # ----敌方移动
        enemy\_move\_count += 1
        if enemy\_move\_count > enemy\_move\_interval:
            enemy\_move\_count = 0
            enemy\_move\_flag = True
            enemy\_need\_move\_row -= 1
            if enemy\_need\_move\_row == 0:
                enemy\_need\_move\_row = enemy\_max\_row
            enemy\_change\_direction\_count += 1
            if enemy\_change\_direction\_count > enemy\_change\_direction\_interval:
                enemy\_change\_direction\_count = 1
                enemy\_move\_right = not enemy\_move\_right
                enemy\_need\_down = True
                # ----每次下降提高移动和射击速度
                enemy\_move\_interval = max(15, enemy\_move\_interval-3)
                enemy\_shot\_interval = max(50, enemy\_move\_interval-10)
        # ----遍历更新
        for enemy in enemies\_group:
            if enemy\_shot\_flag:
                if enemy.number == shot\_number:
                    en\_bullet = enemy.shot()
                    en\_bullets\_group.add(en\_bullet)
            if enemy\_move\_flag:
                if enemy.number in range((enemy\_need\_move\_row-1)\*11, enemy\_need\_move\_row\*11):
                    if enemy\_move\_right:
                        enemy.update('right', cfg.SCREENSIZE\[1\])
                    else:
                        enemy.update('left', cfg.SCREENSIZE\[1\])
            else:
                enemy.update(None, cfg.SCREENSIZE\[1\])
            if enemy\_need\_down:
                if enemy.update('down', cfg.SCREENSIZE\[1\]):
                    running = False
                    is\_win = False
                enemy.change\_count -= 1
            enemy.draw(screen)
        enemy\_move\_flag = False
        enemy\_need\_down = False
        enemy\_shot\_flag = False
        # ----敌方爆炸特效
        for boomed\_enemy in boomed\_enemies\_group:
            if boomed\_enemy.boom(screen):
                boomed\_enemies\_group.remove(boomed\_enemy)
                del boomed\_enemy
        # --敌方子弹与我方飞船碰撞检测
        if not myaircraft.one\_dead:
            if pygame.sprite.spritecollide(myaircraft, en\_bullets\_group, True, None):
                myaircraft.one\_dead = True
        if myaircraft.one\_dead:
            if myaircraft.boom(screen):
                myaircraft.resetBoom()
                myaircraft.num\_life -= 1
                if myaircraft.num\_life < 1:
                    running = False
                    is\_win = False
        else:
            # ----更新飞船
            myaircraft.update(cfg.SCREENSIZE\[0\])
            # ----画飞船
            myaircraft.draw(screen)
        if (not ufo.has\_boomed) and (ufo.is\_dead):
            if ufo.boom(screen):
                ufo.has\_boomed = True
        else:
            # ----更新UFO
            ufo.update(cfg.SCREENSIZE\[0\])
            # ----画UFO
            ufo.draw(screen)
        # --画我方飞船子弹
        for bullet in my\_bullets\_group:
            if bullet.update():
                my\_bullets\_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        # --画敌方子弹
        for bullet in en\_bullets\_group:
            if bullet.update(cfg.SCREENSIZE\[1\]):
                en\_bullets\_group.remove(bullet)
                del bullet
            else:
                bullet.draw(screen)
        if myaircraft.score > highest\_score:
            highest\_score = myaircraft.score
        # --得分每增加2000我方飞船增加一条生命
        if (myaircraft.score % 2000 == 0) and (myaircraft.score > 0) and (myaircraft.score != myaircraft.old\_score):
            myaircraft.old\_score = myaircraft.score
            myaircraft.num\_life = min(myaircraft.num\_life + 1, myaircraft.max\_num\_life)
        # --敌人都死光了的话就胜利了
        if len(enemies\_group) < 1:
            is\_win = True
            running = False
        # --显示文字
        # ----当前得分
        showText(screen, 'SCORE: ', cfg.WHITE, font, 200, 8)
        showText(screen, str(myaircraft.score), cfg.WHITE, font, 200, 24)
        # ----敌人数量
        showText(screen, 'ENEMY: ', cfg.WHITE, font, 370, 8)
        showText(screen, str(len(enemies\_group)), cfg.WHITE, font, 370, 24)
        # ----历史最高分
        showText(screen, 'HIGHEST: ', cfg.WHITE, font, 540, 8)
        showText(screen, str(highest\_score), cfg.WHITE, font, 540, 24)
        # ----FPS
        showText(screen, 'FPS: ' + str(int(clock.get\_fps())), cfg.RED, font, 8, 8)
        # --显示剩余生命值
        showLife(screen, myaircraft.num\_life, cfg.GREEN)
        pygame.display.update()
        clock.tick(cfg.FPS)
    with open('score', 'w') as f:
        f.write(str(highest\_score))
    return is\_win
 
 
'''主函数'''
def main():
    # 初始化
    pygame.init()
    pygame.display.set\_caption('外星人入侵 —— 九歌')
    screen = pygame.display.set\_mode(cfg.SCREENSIZE)
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set\_volume(0.4)
    pygame.mixer.music.play(-1)
    while True:
        is\_win = startGame(screen)
        endInterface(screen, cfg.BLACK, is\_win)
 
 
'''run'''
if \_\_name\_\_ == '\_\_main\_\_':
    main()



  • 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

13、贪心鸟


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

14、井字棋888‘’


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

源码分享:

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


  • 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
  • 253
  • 254

关于Python技术储备

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/229886
推荐阅读
相关标签