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

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

off999 2024-11-06 11:24 27 浏览 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”即可领取。


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

相关推荐

qq个性签名(qq个性签名怎么看)
qq个性签名(qq个性签名怎么看)

QQ上发说说的方法1、在QQ界面点击“空间”图标。2、点击右上角的“+”按钮,点击“说说”图标。3、输入想要发送的文字,点击“发表”即可。4、总结如下。扩展资料:有趣的QQ说说推荐:1、喜欢你、是否没道理、、2、花有百样红,人与狗不同3、走...

2026-01-18 05:15 off999

office2003怎么安装(microsoft office2003怎样安装完整版)

首先,必须要确认您的win10系统中有没有安装过office。很多品牌笔记本或台式机,在购机之后,打开系统就会发现有office软件(可能需要续费后才能使用),而且版本较新。如果此时直接安装较老版本o...

租房网(租房网名怎么写吸引人)
  • 租房网(租房网名怎么写吸引人)
  • 租房网(租房网名怎么写吸引人)
  • 租房网(租房网名怎么写吸引人)
  • 租房网(租房网名怎么写吸引人)
一键root官网(一键root 官网)

卓大师的一键Root功能有三种模式,分别是获取永久Root权限,获取临时Root权限和去除Root。顾名思义,永久Root,就是一次操作,永久生效,让手机永远处于Root状态。而临时Root,在手机重...

消灭星星经典版老款(消灭星星免费下载)

《消灭星星》是由BrianBaek公司开发的一款消除类休闲娱乐手机游戏,于2014年发行,游戏大小为3.8M。本作特点是易上手,点击两个或两个以上颜色相同的方块即可消除,没有时间限制。《PopSta...

脓包痘痘如何处理(脓包痘痘怎么弄)

最好不要用手指去挤压,防止局部出现感染或者留下疤痕,在这个时候可以给局部涂抹维a酸乳膏,也可以使用硫磺皂的方法来清洗面部,并且在饮食上最好不要吃辛辣油炸的发物食品,以清淡的食物为主,多吃水果蔬菜,多喝...

德国二战游戏单机手游(以德军为视角的二战手机游戏)

元帅,私奔吧甜文穿越二战隆美尔第三帝国之未来战争帝国雄心帝国苍穹德意志的荣耀狗运战神普鲁士雄鹰战起1938复活战斗在第三帝国《我的二战不可能这么萌》作者:月面书评:异界后宫二战军事穿越流。本书...

酷我音乐官方免费下载安装(酷我音乐官方免费下载安装app)

要下载手机铃声,首先需要打开酷我音乐APP,然后点击“我的”页面,再选择“铃声中心”进入铃声下载界面。在这里,你可以根据喜好选择不同类型的铃声,比如热门、经典、儿歌等。找到心仪的铃声后,点击右侧的下载...

下载免费的小说(免费下载小说软件推荐)

http://www.ziweishuwu.comhttp://www.txtbook.com.cn/https://www.xiashutxt.com/https://www.jjxs.la/都可以...

安装播放器 app下载(安装播放器软件)

1.首先,打开浏览器,访问播放器官网,找到下载地址,点击下载。2.点击下载后,会弹出一个提示框,点击“保存”,然后把文件保存到本地磁盘。3.打开保存的文件,双击运行安装程序,按照提示安装播放器。4.安...

游戏蜂窝(游戏蜂窝免root)

人人蜂窝和游戏蜂窝有以下几点区别:1.目标用户不同:人人蜂窝是一家提供移动网络服务的运营商,主要面向一般用户提供通信服务;而游戏蜂窝是一个游戏信息平台,主要为游戏爱好者提供游戏相关资讯和社交互动。2...

正版win7旗舰版官网(win7旗舰版官方)

从来就没有win7官网这样的说法,这是因为win7本身就是微软公司旗下产品,是Windows系统的一个版本而已,并不存在win7官网,当然主要的相关资源还是可以到微软官网去查找下载。首先,官网下载的W...

打米传奇手游可提现(打米传奇手游怎么提现)

个人感觉有些传奇游戏还是可以提现的,也就是现在所谓的搬砖服,不过想要提现也是需要付出的,普通的游戏玩家一天可以得到的收益并不是很高。想要获得高额收益是需要投资的。个人建议投资之前最好先观望一下,免的造...

虚拟号码发送短信平台(虚拟手机号收短信平台)

用虚拟手机号给别人发送短信的方法如下1、下载安装定时达人软件(安卓手机端),进入首页,点击下部的“添加新任务”,左边选择“通信”项。2、这时就可以看到右边的“虚拟电话”和“虚拟短信”选项。3、点击进入...

免费阅读软件(一念永恒小说免费阅读软件)

  追书免费全本小说、追书神器免费版、易追书、全本追书阅读器等软件都是比较好用的免费读书软件。具体介绍如下:  1、追书免费全本小说,免费阅读热门网络小说;  2、追书神器免费版,有海量的书库,更...

取消回复欢迎 发表评论: