百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

如何用Python制作游戏?内附代码!详细教学

off999 2024-11-06 11:24 33 浏览 0 评论

今天为大家带来的内容是实战:用python写个小游戏!(详细解释,建议收藏)本文具有不错的参考意义及学习意义,希望大家会喜欢!要是觉得不错记得点赞,转发关注,不迷路哦!

一、游戏简介

本游戏是通过python编写的小游戏,给初学者熟悉python编程语言抛砖引玉,希望有所帮助。
成型的效果图如下:


二、编写步骤

1.引入库

代码如下:

###### AUTHOR:破茧狂龙 ######
###### DATE:20201002 ######
###### DESCRIPTION:移动的木板 ######
import pygame
from pygame.locals import *
import sys
import time
import random

2.初始化

代码如下:

pygame.init()
BLACK = (0, 0, 0) # 黑色
WHITE = (255, 255, 255) # 白色
bg_color = (0,0,70)  # 背景颜色
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)

smallText = pygame.font.SysFont('SimHei', 20) #comicsansms
midlText = pygame.font.SysFont('SimHei', 50)

barsize = [30, 10]
SCREEN_SIZE = [400, 500]  # 屏幕大小
BALL_SIZE = [15, 15]  # 球的尺寸
fontcolor = (255,255,255)  # 定义字体的颜色

myimg = r"img\b1.jpg"
background = pygame.image.load(myimg) # 图片位置
background = pygame.transform.scale(background, SCREEN_SIZE)

# ball 初始位置
ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2
ball_pos_y = 0

# ball 移动方向
ball_dir_y = 1  # 1:down
ball_pos = pygame.Rect(ball_pos_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])

clock = pygame.time.Clock()  # 定时器
screen = pygame.display.set_mode(SCREEN_SIZE)
# 设置标题
pygame.display.set_caption('python小游戏-移动木板')
# 设置图标
image = pygame.image.load(myimg)
pygame.display.set_icon(image)

3.相关自定义函数

代码如下:

###### 自定义函数 ######
def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic, (x, y, w, h))
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w / 2)), (y + (h / 2)))
    screen.blit(textSurf, textRect)

def text_objects(text, font):
    textSurface = font.render(text, True, fontcolor)
    return textSurface, textSurface.get_rect()

def quitgame():
    pygame.quit()
    quit()

def message_diaplay(text):
    largeText = pygame.font.SysFont('SimHei', 115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((screen[0] / 2), (screen[1] / 2))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    time.sleep(2)
    game_loop()

4.相关自定义函数

代码如下:


def game_first_win():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        screen.fill(bg_color)
        ###游戏名称
        TextSurf, TextRect = text_objects('移动木板', midlText)
        TextRect.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 - 70 ))
        screen.blit(TextSurf, TextRect)
        ###作者
        TextSurf_ZZ, TextRect_ZZ = text_objects('AUTHOR:破茧狂龙', smallText)
        TextRect_ZZ.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 + 30))
        screen.blit(TextSurf_ZZ, TextRect_ZZ)
        button("开始", 60, 400, 100, 50, green, bright_green, game_loop)
        button("取消", 230, 400, 100, 50, red, bright_red, quitgame)
        pygame.display.update()
        clock.tick(15)

###### 移动的木板游戏类 ######
def game_loop():
    pygame.mouse.set_visible(1)  # 移动鼠标不可见
    ###变量###
    score = 0 #分数
    count_O = 0 #循环的次数变量1 用于统计等级
    count_N = 0 #循环的次数变量2 用于统计等级
    c_level = 1 #等级

    x_change = 0 #移动的变量
    x = SCREEN_SIZE[0] // 2 - barsize[0] // 2
    y = SCREEN_SIZE[1] - barsize[1]

    # ball 初始位置
    ball_pos_pz = ball_pos
    while True:
        bar_move_left = False
        bar_move_right = False
        ###当每次满X分后,升级等级
        if count_O != count_N and score % 5 == 0:
            c_level += 1
        count_O = count_N
        ###### 获取键盘输入 ######
        for event in pygame.event.get():
            if event.type == QUIT:  # 当按下关闭按键
                pygame.quit()
                sys.exit()  # 接收到退出事件后退出程序
            elif event.type == KEYDOWN:
                ##按键盘Q键 暂停
                if event.key == pygame.K_q:
                    time.sleep(10)
                ##左移动
                if event.key == pygame.K_LEFT:
                    bar_move_left = True
                    x_change = -30
                else:
                    bar_move_left = False
                ##右移动
                if event.key == pygame.K_RIGHT:
                    bar_move_right = True
                    x_change = +30
                else:
                    bar_move_right = False
                if event.key != pygame.K_LEFT and event.key != pygame.K_RIGHT:
                    bar_move_left = False
                    bar_move_right = False

            ##木板的位置移动
            if bar_move_left == True and bar_move_right == False:
                x += x_change
            if bar_move_left == False and bar_move_right == True:
                x += x_change

        ##填充背景
        screen.blit(background, (0, 0))  # (0,0)代表图片位置起点x 轴  Y轴
        ##获取最新的木板位置,并渲染在前台
        bar_pos = pygame.Rect(x, y, barsize[0], BALL_SIZE[1])
        bar_pos.left = x
        pygame.draw.rect(screen, WHITE, bar_pos)

        ## 球移动,并渲染在前台
        ball_pos_pz.bottom += ball_dir_y * 3
        pygame.draw.rect(screen, WHITE, ball_pos_pz)

        ## 判断球是否落到板上
        if bar_pos.top <= ball_pos_pz.bottom and (
                bar_pos.left <= ball_pos_pz.right and bar_pos.right >= ball_pos_pz.left):
            score += 1  # 分数每次加1
            count_N += 1
        elif bar_pos.top <= ball_pos_pz.bottom and (
                bar_pos.left > ball_pos_pz.right or bar_pos.right < ball_pos_pz.left):
            print("Game Over: ", score)
            return score

        ## 更新球下落的初始位置
        if bar_pos.top <= ball_pos_pz.bottom:
            ball_x = random.randint(0, SCREEN_SIZE[0] - BALL_SIZE[0])
            ball_pos_pz = pygame.Rect(ball_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])

        ######### 显示游戏等级 #########
        TextSurf_lev, TextRect_lev = text_objects("等级 : " + str(c_level), smallText)
        TextRect_lev.center = (60, 20)
        screen.blit(TextSurf_lev, TextRect_lev)

        ######### 显示分数结果 #########
        TextSurf_sco, TextRect_sco = text_objects("分数 : " + str(score), smallText)
        TextRect_sco.center = (60, 50)
        screen.blit(TextSurf_sco, TextRect_sco)

        pygame.display.update()  # 更新软件界面显示
        clock.tick(60)

# 三、完整的代码

代码如下:

###### AUTHOR:破茧狂龙 ######
###### DATE:20201002 ######
###### DESCRIPTION:移动的木板 ######
import pygame
from pygame.locals import *
import sys
import time
import random

pygame.init()
BLACK = (0, 0, 0) # 黑色
WHITE = (255, 255, 255) # 白色
bg_color = (0,0,70)  # 背景颜色
red = (200, 0, 0)
green = (0, 200, 0)
bright_red = (255, 0, 0)
bright_green = (0, 255, 0)

smallText = pygame.font.SysFont('SimHei', 20) #comicsansms
midlText = pygame.font.SysFont('SimHei', 50)

barsize = [30, 10]
SCREEN_SIZE = [400, 500]  # 屏幕大小
BALL_SIZE = [15, 15]  # 球的尺寸
fontcolor = (255,255,255)  # 定义字体的颜色

myimg = r"img\b1.jpg"
background = pygame.image.load(myimg) # 图片位置
background = pygame.transform.scale(background, SCREEN_SIZE)

# ball 初始位置
ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2
ball_pos_y = 0

# ball 移动方向
ball_dir_y = 1  # 1:down
ball_pos = pygame.Rect(ball_pos_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])

clock = pygame.time.Clock()  # 定时器
screen = pygame.display.set_mode(SCREEN_SIZE)
# 设置标题
pygame.display.set_caption('python小游戏-移动木板')
# 设置图标
image = pygame.image.load(myimg)
pygame.display.set_icon(image)

###### 自定义函数 ######
def button(msg, x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    if x + w > mouse[0] > x and y + h > mouse[1] > y:
        pygame.draw.rect(screen, ac, (x, y, w, h))
        if click[0] == 1 and action != None:
            action()
    else:
        pygame.draw.rect(screen, ic, (x, y, w, h))
    textSurf, textRect = text_objects(msg, smallText)
    textRect.center = ((x + (w / 2)), (y + (h / 2)))
    screen.blit(textSurf, textRect)

def text_objects(text, font):
    textSurface = font.render(text, True, fontcolor)
    return textSurface, textSurface.get_rect()

def quitgame():
    pygame.quit()
    quit()

def message_diaplay(text):
    largeText = pygame.font.SysFont('SimHei', 115)
    TextSurf, TextRect = text_objects(text, largeText)
    TextRect.center = ((screen[0] / 2), (screen[1] / 2))
    screen.blit(TextSurf, TextRect)
    pygame.display.update()
    time.sleep(2)
    game_loop()

def game_first_win():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        screen.fill(bg_color)
        ###游戏名称
        TextSurf, TextRect = text_objects('移动木板', midlText)
        TextRect.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 - 70 ))
        screen.blit(TextSurf, TextRect)
        ###作者
        TextSurf_ZZ, TextRect_ZZ = text_objects('AUTHOR:破茧狂龙', smallText)
        TextRect_ZZ.center = ((SCREEN_SIZE[0] / 2), (SCREEN_SIZE[1] / 2 + 30))
        screen.blit(TextSurf_ZZ, TextRect_ZZ)
        button("开始", 60, 400, 100, 50, green, bright_green, game_loop)
        button("取消", 230, 400, 100, 50, red, bright_red, quitgame)
        pygame.display.update()
        clock.tick(15)

###### 移动的木板游戏类 ######
def game_loop():
    pygame.mouse.set_visible(1)  # 移动鼠标不可见
    ###变量###
    score = 0 #分数
    count_O = 0 #循环的次数变量1 用于统计等级
    count_N = 0 #循环的次数变量2 用于统计等级
    c_level = 1 #等级

    x_change = 0 #移动的变量
    x = SCREEN_SIZE[0] // 2 - barsize[0] // 2
    y = SCREEN_SIZE[1] - barsize[1]

    # ball 初始位置
    ball_pos_pz = ball_pos
    while True:
        bar_move_left = False
        bar_move_right = False
        ###当每次满X分后,升级等级
        if count_O != count_N and score % 5 == 0:
            c_level += 1
        count_O = count_N
        ###### 获取键盘输入 ######
        for event in pygame.event.get():
            if event.type == QUIT:  # 当按下关闭按键
                pygame.quit()
                sys.exit()  # 接收到退出事件后退出程序
            elif event.type == KEYDOWN:
                ##按键盘Q键 暂停
                if event.key == pygame.K_q:
                    time.sleep(10)
                ##左移动
                if event.key == pygame.K_LEFT:
                    bar_move_left = True
                    x_change = -30
                else:
                    bar_move_left = False
                ##右移动
                if event.key == pygame.K_RIGHT:
                    bar_move_right = True
                    x_change = +30
                else:
                    bar_move_right = False
                if event.key != pygame.K_LEFT and event.key != pygame.K_RIGHT:
                    bar_move_left = False
                    bar_move_right = False

            ##木板的位置移动
            if bar_move_left == True and bar_move_right == False:
                x += x_change
            if bar_move_left == False and bar_move_right == True:
                x += x_change

        ##填充背景
        screen.blit(background, (0, 0))  # (0,0)代表图片位置起点x 轴  Y轴
        ##获取最新的木板位置,并渲染在前台
        bar_pos = pygame.Rect(x, y, barsize[0], BALL_SIZE[1])
        bar_pos.left = x
        pygame.draw.rect(screen, WHITE, bar_pos)

        ## 球移动,并渲染在前台
        ball_pos_pz.bottom += ball_dir_y * 3
        pygame.draw.rect(screen, WHITE, ball_pos_pz)

        ## 判断球是否落到板上
        if bar_pos.top <= ball_pos_pz.bottom and (
                bar_pos.left <= ball_pos_pz.right and bar_pos.right >= ball_pos_pz.left):
            score += 1  # 分数每次加1
            count_N += 1
        elif bar_pos.top <= ball_pos_pz.bottom and (
                bar_pos.left > ball_pos_pz.right or bar_pos.right < ball_pos_pz.left):
            print("Game Over: ", score)
            return score

        ## 更新球下落的初始位置
        if bar_pos.top <= ball_pos_pz.bottom:
            ball_x = random.randint(0, SCREEN_SIZE[0] - BALL_SIZE[0])
            ball_pos_pz = pygame.Rect(ball_x, ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])

        ######### 显示游戏等级 #########
        TextSurf_lev, TextRect_lev = text_objects("等级 : " + str(c_level), smallText)
        TextRect_lev.center = (60, 20)
        screen.blit(TextSurf_lev, TextRect_lev)

        ######### 显示分数结果 #########
        TextSurf_sco, TextRect_sco = text_objects("分数 : " + str(score), smallText)
        TextRect_sco.center = (60, 50)
        screen.blit(TextSurf_sco, TextRect_sco)

        pygame.display.update()  # 更新软件界面显示
        clock.tick(60)

####程序执行顺序######
game_first_win()
game_loop()
pygame.quit()

结尾

最后多说一句,小编是一名python开发工程师,这里有我自己整理了一套最新的python系统学习教程,包括从基础的python脚本到web开发、爬虫、数据分析、数据可视化、机器学习等。想要这些资料的可以关注小编,并在后台私信小编:“01”即可领取。


本文的文字及图片来源于网络加上自己的想法,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

相关推荐

安全教育登录入口平台(安全教育登录入口平台官网)

122交通安全教育怎么登录:122交通网的注册方法是首先登录网址http://www.122.cn/,接着打开网页后,点击右上角的“个人登录”;其次进入邮箱注册,然后进入到注册页面,输入相关信息即可完...

大鱼吃小鱼经典版(大鱼吃小鱼经典版(经典版)官方版)

大鱼吃小鱼小鱼吃虾是于谦跟郭麒麟的《我的棒儿呢?》郭德纲说于思洋郭麒麟作诗的相声,最后郭麒麟做了一首,师傅躺在师母身上大鱼吃小鱼小鱼吃虾虾吃水水落石出师傅压师娘师娘压床床压地地动山摇。...

谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
  • 谷歌地球下载高清卫星地图(谷歌地球地图下载器)
哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)
哪个软件可以免费pdf转ppt(免费的pdf转ppt软件哪个好)

要想将ppt免费转换为pdf的话,我们建议大家可以下一个那个wps,如果你是会员的话,可以注册为会员,这样的话,在wps里面的话,就可以免费将ppt呢转换为pdfpdf之后呢,我们就可以直接使用,不需要去直接不需要去另外保存,为什么格式转...

2026-02-04 09:03 off999

电信宽带测速官网入口(电信宽带测速官网入口app)

这个网站看看http://www.swok.cn/pcindex.jsp1.登录中国电信网上营业厅,宽带光纤,贴心服务,宽带测速2.下载第三方软件,如360等。进行在线测速进行宽带测速时,尽...

植物大战僵尸95版手机下载(植物大战僵尸95 版下载)

1可以在应用商店或者游戏平台上下载植物大战僵尸95版手机游戏。2下载教程:打开应用商店或者游戏平台,搜索“植物大战僵尸95版”,找到游戏后点击下载按钮,等待下载完成即可安装并开始游戏。3注意:确...

免费下载ppt成品的网站(ppt成品免费下载的网站有哪些)

1、Chuangkit(chuangkit.com)直达地址:chuangkit.com2、Woodo幻灯片(woodo.cn)直达链接:woodo.cn3、OfficePlus(officeplu...

2025世界杯赛程表(2025世界杯在哪个国家)

2022年卡塔尔世界杯赛程公布,全部比赛在卡塔尔境内8座球场举行,2022年,决赛阶段球队全部确定。揭幕战于当地时间11月20日19时进行,由东道主卡塔尔对阵厄瓜多尔,决赛于当地时间12月18日...

下载搜狐视频电视剧(搜狐电视剧下载安装)

搜狐视频APP下载好的视频想要导出到手机相册里方法如下1、打开手机搜狐视频软件,进入搜狐视频后我们点击右上角的“查找”,找到自已喜欢的视频。2、在“浏览器页面搜索”窗口中,输入要下载的视频的名称,然后...

pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
  • pubg免费下载入口(pubg下载入口官方正版)
永久免费听歌网站(丫丫音乐网)

可以到《我爱音乐网》《好听音乐网》《一听音乐网》《YYMP3音乐网》还可以到《九天音乐网》永久免费听歌软件有酷狗音乐和天猫精灵,以前要跳舞经常要下载舞曲,我从QQ上找不到舞曲下载就从酷狗音乐上找,大多...

音乐格式转换mp3软件(音乐格式转换器免费版)

有两种方法:方法一在手机上操作:1、进入手机中的文件管理。2、在其中选择“音乐”,将显示出手机中的全部音乐。3、点击“全选”,选中所有音乐文件。4、点击屏幕右下方的省略号图标,在弹出菜单中选择“...

电子书txt下载(免费的最全的小说阅读器)

1.Z-library里面收录了近千万本电子书籍,需求量大。2.苦瓜书盘没有广告,不需要账号注册,使用起来非常简单,直接搜索预览下载即可。3.鸠摩搜书整体风格简洁清晰,书籍资源丰富。4.亚马逊图书书籍...

最好免费观看高清电影(播放免费的最好看的电影)

在目前的网上选择中,IMDb(互联网电影数据库)被认为是最全的电影网站之一。这个网站提供了各种类型的电影和电视节目的海量信息,包括剧情介绍、演员表、评价、评论等。其还提供了有关电影制作背后的详细信息,...

孤单枪手2简体中文版(孤单枪手2简体中文版官方下载)

要将《孤胆枪手2》游戏的征兵秘籍切换为中文,您可以按照以下步骤进行操作:首先,打开游戏设置选项,通常可以在游戏主菜单或游戏内部找到。然后,寻找语言选项或界面选项,点击进入。在语言选项中,选择中文作为游...

取消回复欢迎 发表评论: