python编写小游戏详细教程,python编写小游戏的代码

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

大家好,小编来为大家解答以下问题,python编写小游戏详细教程,python编写小游戏的代码,现在让我们一起来看看吧!

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

今天给大家带来十五个Python小游戏,找回童年的同时学习编程还可以摸鱼,源码附上结尾领取。

一、接金币(1分)

普通难度:❤

玩法介绍: 吃金币,控制左右键,有手就行python的turtle画老虎。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

普通难度:❤

玩法介绍: 滑雪吃小旗子,控制上下左右键,关键控制好速度,有手就行。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

普通难度:❤

玩法介绍: 双人小游戏,可以选择单打或者双打,有手就行。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

四、俄罗斯方块 (2分)

困难难度:❤❤

玩法介绍: 小时候的经典游戏,加速玩法有一点点难度。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

五、消消乐(2分)

困难难度:❤❤

玩法介绍: 以前经典的游戏,给我感觉趣味性少了点

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

六、飞机大战(2分)

困难难度:❤❤

玩法介绍: 并夕夕版飞机大战,也是个双人小游戏。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

七、保卫森林(3分)

抓狂难度:❤❤❤

玩法介绍: 塔防类小游戏,老白喜欢玩的一类,比较考验策略和大局安排。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

八、24点游戏(3分)

抓狂难度:❤❤❤

玩法介绍: 几个数字通过加减乘除最后结果为24,老白开始觉得很简单,后面越玩越觉得有点意思。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

九、外星人入侵(3分)

抓狂难度:❤❤❤

玩法介绍: 打怪走位都要控制好,还是考验操作的。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十、坦克大战(3分)

抓狂难度:❤❤❤

玩法介绍: 强烈推荐,童年系列来了,太好玩了,现在玩也不觉得过时,双人玩美滋滋。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十一、吃豆豆(4分)

恶梦难度:❤❤❤❤

玩法介绍: 这个很考验走位啊,一不小心就没了。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十二、推箱子(4分)

恶梦难度:❤❤❤❤

玩法介绍: 小时候拿着大人的手机玩这个,越到后面越玩,有通过的大佬吗?

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十三、2048(4分)

恶梦难度:❤❤❤❤

玩法介绍: 也是一款经典的游戏,前面还好,越到后面越难。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十四、塔防(5分)

地狱难度:❤❤❤❤❤

玩法介绍: 大家到的我可没加速,就是这么快,坚持三分钟就不容易了。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十五、拼图(5分)

地狱难度:❤❤❤❤❤

玩法介绍: 这个拼图我认为在这个十五个里算是最难的,真的很难拼!

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

​ 最后

为了帮助大家更好的学习Python,小编给大家准备了一份Python学习资料,里面的内容都是适合零基础小白的笔记和资料,不懂编程也能听懂、看懂,需要获取方式:点击这里【 Python全套资料】 即可获取。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

CSDN大礼包:《Python开发全套学习笔记/实战项目/安装工具》免费分享

👉Python学习路线汇总👈

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
​👉Python必备开发工具👈

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
👉精品Python学习书籍👈

当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。

温馨提示:篇幅有限,已打包文件夹,获取方式:点击这里【 Python全套资料】 即可获取。

CSDN大礼包:《Python开发全套学习笔记/实战项目/安装工具》免费分享

👉Python学习视频600合集👈

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

​​​👉100道Python练习题👈

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
👉面试刷题👈
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
​​​
👉实战案例👈
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

👉Python副业兼职与全职路线👈
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

​​​获取方式:点击这里【 Python全套资料】 或扫描下方即可获取。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

**CSDN大礼包:《Python开发全套学习笔记/实战项目/安装工具》免费分享**​文章来源地址https://www.toymoban.com/news/detail-798062.html

今天给大家带来十五个Python小游戏,找回童年的同时学习编程还可以摸鱼,源码附上结尾领取。

一、接金币(1分)

普通难度:❤

玩法介绍: 吃金币,控制左右键,有手就行python的turtle画老虎。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

普通难度:❤

玩法介绍: 滑雪吃小旗子,控制上下左右键,关键控制好速度,有手就行。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

普通难度:❤

玩法介绍: 双人小游戏,可以选择单打或者双打,有手就行。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

四、俄罗斯方块 (2分)

困难难度:❤❤

玩法介绍: 小时候的经典游戏,加速玩法有一点点难度。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

五、消消乐(2分)

困难难度:❤❤

玩法介绍: 以前经典的游戏,给我感觉趣味性少了点

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

源码分享

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

六、飞机大战(2分)

困难难度:❤❤

玩法介绍: 并夕夕版飞机大战,也是个双人小游戏。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

七、保卫森林(3分)

抓狂难度:❤❤❤

玩法介绍: 塔防类小游戏,老白喜欢玩的一类,比较考验策略和大局安排。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

八、24点游戏(3分)

抓狂难度:❤❤❤

玩法介绍: 几个数字通过加减乘除最后结果为24,老白开始觉得很简单,后面越玩越觉得有点意思。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

九、外星人入侵(3分)

抓狂难度:❤❤❤

玩法介绍: 打怪走位都要控制好,还是考验操作的。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十、坦克大战(3分)

抓狂难度:❤❤❤

玩法介绍: 强烈推荐,童年系列来了,太好玩了,现在玩也不觉得过时,双人玩美滋滋。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十一、吃豆豆(4分)

恶梦难度:❤❤❤❤

玩法介绍: 这个很考验走位啊,一不小心就没了。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十二、推箱子(4分)

恶梦难度:❤❤❤❤

玩法介绍: 小时候拿着大人的手机玩这个,越到后面越玩,有通过的大佬吗?

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十三、2048(4分)

恶梦难度:❤❤❤❤

玩法介绍: 也是一款经典的游戏,前面还好,越到后面越难。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十四、塔防(5分)

地狱难度:❤❤❤❤❤

玩法介绍: 大家到的我可没加速,就是这么快,坚持三分钟就不容易了。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

十五、拼图(5分)

地狱难度:❤❤❤❤❤

玩法介绍: 这个拼图我认为在这个十五个里算是最难的,真的很难拼!

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

​ 最后

为了帮助大家更好的学习Python,小编给大家准备了一份Python学习资料,里面的内容都是适合零基础小白的笔记和资料,不懂编程也能听懂、看懂,需要获取方式:点击这里【 Python全套资料】 即可获取。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

CSDN大礼包:《Python开发全套学习笔记/实战项目/安装工具》免费分享

👉Python学习路线汇总👈

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
​👉Python必备开发工具👈

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
👉精品Python学习书籍👈

当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。

温馨提示:篇幅有限,已打包文件夹,获取方式:点击这里【 Python全套资料】 即可获取。

CSDN大礼包:《Python开发全套学习笔记/实战项目/安装工具》免费分享

👉Python学习视频600合集👈

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

​​​👉100道Python练习题👈

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
👉面试刷题👈
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
​​​
👉实战案例👈
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows
光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

👉Python副业兼职与全职路线👈
python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

​​​获取方式:点击这里【 Python全套资料】 或扫描下方即可获取。

python编写小游戏详细教程,python编写小游戏的代码,pygame,python,开发语言,windows

**CSDN大礼包:《Python开发全套学习笔记/实战项目/安装工具》免费分享**​

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

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

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

相关文章

  • 用Python编写的超级马里奥小游戏(基于Pygame)

    在本文中,我将向您展示如何使用Python编写一个简单的超级马里奥小游戏,使用Pygame库来处理游戏的图形和输入。 首先,我们需要确保已安装Pygame库。您可以使用以下命令在终端或命令提示符中安装Pygame: 一旦安装完成,我们就可以开始编写代码了。下面是完整的Python代码

    2024年01月16日
    浏览(26)
  • python做小游戏代码可复制,python编写小游戏的代码

    这篇文章主要介绍了python简单小游戏代码教程,具有一定借鉴价值,需要的朋友可以参考下。希望大家阅读完这篇文章后大有收获,下面让小编带着大家一起了解一下。 哈喽铁子们 表弟最近在学Python,总是跟我抱怨很枯燥无味,其实,他有没有认真想过,可能是自己学习姿

    2024年01月16日
    浏览(44)
  • Python版基于pygame的玛丽快跑小游戏源代码,玛丽冒险小游戏代码,支持双人模式

    基于pygame的玛丽快跑小游戏源代码,玛丽冒险小游戏代码,支持双人模式 按空格进入单人模式,按‘t’进入双人模式,双人模式下玛丽1采用空格键上跳,玛丽2采用方向上键上跳。 完整代码下载地址:Python版基于pygame的玛丽快跑小游戏源代码 完整代码下载地址:Python版基于

    2024年02月11日
    浏览(22)
  • python编写一个简单的游戏,python编写小游戏的代码

    大家好,本文将围绕如何用python编写一个简单的小游戏展开说明,用python做一个小游戏代码是一个很多人都想弄明白的事情,想搞清楚python编写小游戏详细教程需要先了解以下几个事情。 今天玩点别的吧都说 Python 除了生孩子什么都能干 咱们今天就用 Python 写个小游戏 贪吃蛇

    2024年02月02日
    浏览(35)
  • python编写小游戏的代码,python游戏编程代码大全

    大家好,小编来为大家解答以下问题,python游戏编程入门游戏代码,python编写小游戏的代码,现在让我们一起来看看吧! 大家好,本文将围绕python小游戏编程100例运行成功截图展开说明,python小游戏编程100例1000行源码是一个很多人都想弄明白的事情,想搞清楚python编写的入

    2024年02月19日
    浏览(23)
  • 基于Python pygame简易版斗兽棋小游戏源代码

    基于Python pygame简易版斗兽棋小游戏源代码 游戏规则如下: 胜利条件: 1.吃掉对方全部棋子 2.走入对方兽穴(不可进入自己洞穴) 吃法: 1.象狮虎豹狼狗猫鼠象 2.同类棋子先行者吃掉对方 3.老鼠可以进河,老鼠在河里时,岸上的动物不能捕食他,他也不能捕食岸上的动物 4.狮虎在河中没

    2023年04月09日
    浏览(79)
  • 基于Python+Pygame实现一个俄罗斯方块小游戏【完整代码】

    俄罗斯方块,一款起源于上世纪80年代的经典电子游戏,凭借简单的规则和独特的魅力,一跃成为全球家喻户晓的经典。你知道其实只需要一些基础的编程知识,就可以自己实现它吗?今天,我们将使用Python的Pygame库,一步步带你构建属于自己的俄罗斯方块小游戏! 游戏初始

    2024年02月04日
    浏览(25)
  • Python版经典小游戏愤怒的小鸟源代码,基于pygame+pymunk

    Python版经典小游戏愤怒的小鸟源代码,基于pygame+pymunk 程序依赖:pygame 2.0.1, pymunk 5.5.0 直接运行main.py 完整代码下载地址:Python版经典小游戏愤怒的小鸟源代码 tool.py 完整代码下载地址:Python版经典小游戏愤怒的小鸟源代码

    2024年02月16日
    浏览(23)
  • Python编写简易猜数字小游戏(附完整代码)

    Python编写简易猜数字小游戏(附完整代码) 猜数字游戏是一款非常经典的小游戏,本文将介绍如何使用Python编写一个简易的猜数字游戏,并提供完整的源代码。 首先,让我们了解一下游戏规则。游戏开始时,程序会随机生成一个1到100之间的数字,玩家需要通过输入数字来猜

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

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

    2024年02月03日
    浏览(31)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包