当前位置:首页 » 编程语言 » python代码小游戏

python代码小游戏

发布时间: 2023-05-23 12:14:40

python能做什么游戏

Python是一门高级且有趣的编程语言,除了网络爬虫、人工智能、数据分析之外,Python还可以进行游戏开发,为大家介绍五个支持Python的2D、3D游戏开发库。
1、Cocos2d:是一系列开源软件框架,用于构建跨平台2D游戏和应用程序,由cocos2d-x、cocos2d-js、cocos2d-xna和cocos2d多种框架组成,像大鱼赌场、城堡冲突等小游戏,就是用此框架开发出来的。
2、Panda3D:是由迪士尼开发的3D游戏引擎,一个用于Python和C++程序的3D渲染和游戏开发框架,并由卡内基梅陇娱乐技术中心负责维护,使用C++编写的,针对Python进行了完全的封装。
3、Pygame:它是一组Python模块,用来编写游戏,可支持Python3.7,游戏例子有:纸牌游戏、超级马里奥、击球等多种游戏。
4、Pyogre:ogre 3D渲染引擎的Python绑定,可以用来开发游戏和仿真程序等任何3D应用,它的API更加稳定,也非常快速灵活。
5、RenPy:一个视觉小说引擎,被世界各地的成千万的创造者所使用,它可以帮助你使用文字、图像和声音来讲述电脑和移动设备上的故事。RenPy是开放源码的,可免费的商业用途,易于学习的脚本语言任何人都能有效地编写大型视觉小说,它的Python脚本足以用来模拟游戏。

㈡ 球球各位大神怎么用python写一个猜词小游戏的代码

key = input('请输入一个单词:')
description = input('输入单词描述:')
chance = 5
mark = 5
print('现在开始游戏')
print(description + ' '+'\t 这是单词的描述,请你输入这个单词: ')
for i in range(0, 5):
a = input('请你输入单词:')
if a == key:
print('恭喜你答对了,您的分数%d', mark)
else:
print('对不起,你打错了,你还有 %d 次机会,你的分数%d' % (chance-1, mark-1))
if chance == 0:
print('很抱歉,你已经没有机会了,最后得分%d' % mark)
chance -= 1
mark -= 1

㈢ 用Python写一个简单的小游戏

相信大家都玩过俄罗斯方块吧,应该是小时候的回忆吧,但是想不想了解一下这个程序是怎么写出来的呢,自己写出来的应该玩起来更有感觉吧!

感觉还是蛮好玩吧!

接下来,我就分享一下这个游戏的源码过程啊!

先用python创建一个py文件

定义这次程序所需要的类

然后写出它所需要的模块

画背景图

画网格线

# 画已经落下的方块

# 画单个方块

# 画得分等信息

这样就可以写出来一个十分简单的俄罗斯方块啦,是不是觉得还不错呢!

㈣ python编程应用:小游戏hangman

代码分析:

1.import random导入模块

导入random模块,本程序主要是使用random.randint(0,3)方法生成一个0-3之间的随机的随机数。

2、HANGMAN_PICS常量

Python默认把定义的常量大写,HANGMAN_PICS是一个字符列表常量,字母全部大些也提醒一次赋值之后不再改变,这就是常量的意思。

3、列表格式

animals=['frog','rabbit','owl','peacock'] 列表包含4个元素(item),每一个元素用逗号隔开,左边方括号和右边的方括号是列表必须格式必须带的。

4、列表访问

用索引访问元素animals[0],0就是索引号,以此类推还想访问其他元素...animals[1],animals[2],animals[3],如果继续访问animals[4]就会造成索引越界报indexError的错误。

5、“ + ”连接符

“ + ”号 在程序中除了进行运算,还有就是连接字符串和列表,例1:animals='frog',+'rabbit'就会得到animals = 'frograbbit'. 例2:animals = ['frog','rabbit']和river_animals = ['ck','snake']两个列表通过 “+”连接符 就获得['frog', 'rabbit', 'ck', 'snake']一个合成新列表。

6、用索引赋值来修改列表元素

animals[1] = 'swan' 生成一个新列表 animals = [ 'frog' , 'swan' ]

7、in操作符

in操作符告诉我们in左边的值是否包含在右边列表中,如果该值在列表中它将要返回True;如果该值不在列表中,返回值是False。例1:'dragonfly' in [ 'frog' , 'rabbit' ] 返回值是 False 例2 :'ck' in [ 'ck' , 'snake' ] 返回值是True 。例3: ' bee ' in ' sanke bee bird bear lion owl .'

8、调用方法(method)

8.1针对列表的方法 reverse( ) 和 append( )

reverse() 方法会把列表中的元素顺序反转,numbers = [ 1 , 2 , 3 , 4 , 5 ]然后 numbers.reverse( )会反转列表元素 numbers = [ 5 , 4 , 3 , 2 , 1 ]

append()方法在列表的最后添加一个元素,numbers.append( 6 ) 得到 numbers = [ 1 , 2 , 3 ,4 , 5, 6]

8.2 字符串方法 split( )

程序的51行使用此方法,让字符串 words 反馈一个words = [ 'ant', 'baboon', 'badger', 'bat', 'bear'........] 列表

㈤ Python游戏开发,Python实现贪吃蛇小游戏与吃豆豆 附带源码

Python版本: 3.6.4

相关模块:

pygame模块;

以及一些Python自带的模块。

安装Python并添加到环境变量,pip安装需要的相关模块即可。

贪吃蛇的 游戏 规则应该不需要我多做介绍了吧T_T。写个贪吃蛇 游戏 其实还是很简单的。首先,我们进行一下 游戏 初始化:

然后定义一个贪吃蛇类:

其中head_coord用来记录蛇头所在位置,而tail_coords是一个二维数组,用来记录所有蛇身的位置。一开始,贪吃蛇长为3,并且位置是随机生成的。用户通过 键来控制贪吃蛇的行动:

需要注意的是,贪吃蛇不能180 大拐弯,只能90 地拐弯。例如正在向左行动的贪吃蛇不能瞬间变成向右行动。具体而言,代码实现如下:

然后,我们需要随机生成一个食物,且需要保证该食物的位置不与贪吃蛇的位置相同:

在更新贪吃蛇的时候,如果它吃到了食物,则蛇身长加一,否则只是简单的按照给定的方向行动而不改变蛇身长度:

同时,当贪吃蛇吃到食物时,需要重新生成一个新的食物:

最后,当贪吃蛇碰到墙壁或者蛇头碰到蛇身时, 游戏 结束:

并显示一下 游戏 结束界面:

玩家通过 键控制 游戏 的主角吃豆人吃掉藏在迷宫内的所有豆子,并且不能被鬼魂抓到。

若能顺利吃完迷宫内的所有豆子并且不被鬼魂抓到,则 游戏 胜利,否则 游戏 失败。

逐步实现:

Step1:定义 游戏 精灵类

首先,让我们先来明确一下该 游戏 需要哪些 游戏 精灵类。

① 墙类

② 食物类(即豆豆)

③ 角色类

角色类包括吃豆人和鬼魂,鬼魂由电脑控制其运动轨迹,吃豆人由玩家控制其运动轨迹。

显然,其均需具备更新角色位置和改变角色运动方向的能力,其源代码如下:

Step2:设计 游戏 地图

利用Step1中定义的 游戏 精灵类,我们就可以开始设计 游戏 地图了。由于时间有限,我只写了一个关卡的 游戏 地图,有兴趣的小伙伴可以在此基础上进行扩展(在我的源代码基础上进行扩展是很方便滴~)。 游戏 地图的设计包括以下四方面内容:

① 创建墙

② 创建门(一开始关幽灵用的)

image.gif

③ 创建角色

④ 创建食物

因为食物不能和墙、门以及角色的位置重叠,所以为了方便设计 游戏 地图,要先创建完墙、门以及角色后再创建食物:

Step3:设计 游戏 主循环

接下来开始设计 游戏 主循环。首先是初始化:

然后定义主函数:

其中startLevelGame函数用于开始某一关 游戏 ,其源代码如下:

showText函数用于在 游戏 结束或关卡切换时在 游戏 界面中显示提示性文字,其源代码如下:


㈥ python小游戏2048,上班摸鱼必备(附源码)

话不多说,直接上菜

为了方便大家,我就不分段解释了

import turtle, random

# 定义一个类,用来画除了数字方块之外的图形

class BackGround(turtle.Turtle):

    def __init__(self):

        super().__init__()

        self.penup()

        self.ht()

    def draw_block(self):

        self.shape('bg.gif')  # 画出背景方块

        for i in allpos:

            self.goto(i)

            self.stamp()

        self.color('white', 'white')  # 画出其他背景

        self.goto(-215, 120)

        self.begin_fill()

        self.goto(215, 120)

        self.goto(215, 110)

        self.goto(-215, 110)

        self.end_fill()

        self.shape('title.gif')

        self.goto(-125, 210)

        self.stamp()

        self.shape('score.gif')

        self.goto(125, 245)

        self.stamp()

        self.shape('top_score.gif')

        self.goto(125, 170)

        self.stamp()

    # 游戏失败及达成2048的提示文字

    def judge(self):

        global flag_win, flag_win_lose_text

        self.color('blue')

        judge = 0  # 判断是否还有位置可以移动

        for i in block_dic.values():

            for j in block_dic.values():

                if i.num == 0 or i.num == j.num and i.distance(j) == 100:

                    judge += 1

        if judge == 0:  # 无位置可移动,游戏失败

            self.write('    GAME OVER\n重新开始请按空格键', align='center', font=('黑体', 30, 'bold'))

            flag_win_lose_text = False

        if flag_win is True:  # 此条件让2048达成的判断只能进行一次

            for k in block_dic.values():

                if k.num == 2048:  # 游戏达成

                    flag_win = False

                    self.write('    达成2048\n继续游戏请按回车键', align='center', font=('黑体', 30, 'bold'))

                    flag_win_lose_text = False

    def win_lose_clear(self):

        global flag_win_lose_text

        self.clear()

        flag_win_lose_text = True

    def show_score(self):  # 分值的显示

        global score, top_score

        if score > top_score:

            top_score = score

            with open('.\\score.txt', 'w') as f:

                f.write(f'{top_score}')

        self.color('white')

        self.goto(125, 210)

        self.clear()

        self.write(f'{score}', align='center', font=('Arial', 20, 'bold'))

        self.goto(125, 135)

        self.write(f'{top_score}', align='center', font=('Arial', 20, 'bold'))

# 数字方块类

class Block(turtle.Turtle):

    def __init__(self):

        super().__init__()

        self.ht()

        self.penup()

        self.num = 0

    def draw(self):

        self.clear()

        dic_draw = {2: '#eee6db', 4: '#efe0cd', 8: '#f5af7b',

                    16: '#fb9660', 32: '#f57d5a', 64: '#f95c3d',

                    128: '#eccc75', 256: '#eece61', 512: '#efc853',

                    1024: '#ebc53c', 2048: '#eec430', 4096: '#aeb879',

                    8192: '#aab767', 16384: '#a6b74f'}

        if self.num > 0:  # 数字大于0,画出方块

            self.color(f'{dic_draw[self.num]}')  # 选择颜色

            self.begin_fill()

            self.goto(self.xcor()+48, self.ycor()+48)

            self.goto(self.xcor()-96, self.ycor())

            self.goto(self.xcor(), self.ycor()-96)

            self.goto(self.xcor()+96, self.ycor())

            self.goto(self.xcor(), self.ycor()+96)

            self.end_fill()

            self.goto(self.xcor()-48, self.ycor()-68)

            if self.num > 4:  # 按照数字选择数字的颜色

                self.color('white')

            else:

                self.color('#6d6058')

            self.write(f'{self.num}', align='center', font=('Arial', 27, 'bold'))

            self.goto(self.xcor(), self.ycor()+20)

class Game():

    def init(self):

        back = BackGround()  # 实例画出游戏的背景

        back.draw_block()

        for i in allpos:  # 画出16个海龟对应16个数字块

            block = Block()

            block.goto(i)

            block_dic[i] = block

        game.grow()

    def restart(self):  # 重开游戏的方法

        global score, flag_win_lose_text

        score = 0

        for i in block_dic.values():

            i.num = 0

            i.clear()

        win_lose_text.clear()

        game.grow()

        flag_win_lose_text = True  # 此flag为游戏达成或失败出现提示语后的判断,要提示语被clear后才能继续move

    def grow(self):  # 随机出现一个2或4的数字块

        block_list = []

        for i in allpos:

            if block_dic[i].num == 0:

                block_list.append(block_dic[i])  # 挑出空白方块的海龟

        turtle_choice = random.choice(block_list)  # 随机选中其中一个海龟

        turtle_choice.num = random.choice([2, 2, 2, 2, 4])  # 赋属性num=2/4

        turtle_choice.draw()

        win_lose_text.judge()

        show_score_text.show_score()

        ms.update()

    def move_up(self):

        allpos1 = allpos[::4]  # 切片为四列

        allpos2 = allpos[1::4]

        allpos3 = allpos[2::4]

        allpos4 = allpos[3::4]

        self.move_move(allpos1, allpos2, allpos3, allpos4)

    def move_down(self):

        allpos1 = allpos[-4::-4]

        allpos2 = allpos[-3::-4]

        allpos3 = allpos[-2::-4]

        allpos4 = allpos[-1::-4]

        self.move_move(allpos1, allpos2, allpos3, allpos4)

    def move_left(self):

        allpos1 = allpos[:4]

        allpos2 = allpos[4:8]

        allpos3 = allpos[8:12]

        allpos4 = allpos[12:16]

        self.move_move(allpos1, allpos2, allpos3, allpos4)

    def move_right(self):

        allpos1 = allpos[-1:-5:-1]

        allpos2 = allpos[-5:-9:-1]

        allpos3 = allpos[-9:-13:-1]

        allpos4 = allpos[-13:-17:-1]

        self.move_move(allpos1, allpos2, allpos3, allpos4)

    def move_move(self, allpos1, allpos2, allpos3, allpos4):

        if flag_win_lose_text is True:

            count1 = self.move(allpos1)  # 四列或四行依次移动

            count2 = self.move(allpos2)

            count3 = self.move(allpos3)

            count4 = self.move(allpos4)

            if count1 or count2 or count3 or count4:  # 判断是否有方块移动,有才能继续出现新的数字块

                self.grow()

    def move(self, pos_list):

        num_list = []  # 为某一列或行的数字块海龟的坐标

        for i in pos_list:

            num_list.append(block_dic[i].num)  #  把这些海龟的NUM形成list

        new_num_list, count = self.list_oper(num_list)  #  只是list_oper的方法形成新的list

        for j in range(len(new_num_list)):  # 把新的list依次赋值给对应的海龟.num属性并调用draw()方法

            block_dic[pos_list[j]].num = new_num_list[j]

            block_dic[pos_list[j]].draw()

        return count

    def list_oper(self, num_list):  # num_list的操作,假设其为【2,0,2,2】

        global score

        count = True

        temp = []

        new_temp = []

        for j in num_list:

            if j != 0:

                temp.append(j)  # temp=[2,2,2]

        flag = True

        for k in range(len(temp)):

            if flag:

                if k < len(temp)-1 and temp[k] == temp[k+1]:

                    new_temp.append(temp[k]*2)

                    flag = False

                    score += temp[k]

                else:

                    new_temp.append(temp[k])  # new_temp=[4,2]

            else:

                flag = True

        for m in range(len(num_list)-len(new_temp)):

            new_temp.append(0)  # new_temp=[4,2,0,0]

        if new_temp == num_list:

            count = False  # 此变量判断num_list没有变化,数字块无移动

        return(new_temp, count)

if __name__ == '__main__':

    ms = turtle.Screen()  # 主窗口的设置

    ms.setup(430, 630, 400, 50)

    ms.bgcolor('gray')

    ms.title('2048')

    ms.tracer(0)

    ms.register_shape('bg.gif')

    ms.register_shape('title.gif')

    ms.register_shape('score.gif')

    ms.register_shape('top_score.gif')

    block_dic = {}  # 放数字方块海龟的字典,位置坐标为key,对应海龟为value

    allpos = [(-150, 50), (-50, 50), (50, 50), (150, 50),

              (-150, -50), (-50, -50), (50, -50), (150, -50),

              (-150, -150), (-50, -150), (50, -150), (150, -150),

              (-150, -250), (-50, -250), (50, -250), (150, -250)]

    flag_win = True  # 达成2048的判断,让达成的文字仅出现一次

    flag_win_lose_text = True  # 用来判断失败或成功的提示文字是否有被清除,不清除不能继续移动方块

    score = 0

    with open('.\\score.txt', 'r') as f:

        top_score = int(f.read())  #  读取score中的数据

    show_score_text = BackGround()

    win_lose_text = BackGround()

    game = Game()

    game.init()

    ms.listen()

    ms.onkey(game.move_up, 'Up')

    ms.onkey(game.move_down, 'Down')

    ms.onkey(game.move_left, 'Left')

    ms.onkey(game.move_right, 'Right')

    ms.onkey(win_lose_text.win_lose_clear, 'Return')

    ms.onkey(game.restart, 'space')

    ms.mainloop()

这是游戏界面:

欢迎挑战最高分。

要运行出来,必须本地要有这些文件:bg.gif,score.gif,title.gif,top_score.gif,score.txt

我把这些文件放在了群里,还有一些学习的资料,群号642109462,欢迎对python感兴趣的进群讨论。

支持作者的,可以关注和点赞。感谢你们!

㈦ Python程序开发之简单小程序实例(11)小游戏-跳动的小球

Python程序开发之简单小程序实例

(11)小 游戏 -跳动的小球

一、项目功能

用户控制挡板来阻挡跳动的小球。

二、项目分析

根据项目功能自定义两个类,一个用于控制小球在窗体中的运动,一个用于接收用户按下左右键时,挡板在窗体中的运动。在控制小球的类中,我们还需要考虑当小球下降时,碰到挡板时的位置判断。

三、程序源代码

源码部分截图:

源码:

#!/usr/bin/python3.6

# -*- coding: GBK -*-

#导入相应模块

from tkinter import *

import random

import time

#自定义小球的类 Ball

class Ball:

# 初始化

def __init__(self,canvas,paddle,color):

#传递画布值

self.canvas=canvas

#传递挡板值

self.paddle=paddle

#画圆并且保存其ID

self.id=canvas.create_oval(10,10,25,25,fill=color)

self.canvas.move(self.id,245,100)

#小球的水平位置起始列表

start=[-3,-2,-1,1,2,3]

#随机化位置列表

random.shuffle(start)

self.x=start[0]

self.y=-2

self.canvas_heigh=self.canvas.winfo_height()#获取窗口高度并保存

self.canvas_width=self.canvas.winfo_width()

#根据参数值绘制小球

def draw(self):

self.canvas.move(self.id,self.x,self.y)

pos=self.canvas.coords(self.id)#返回相应ID代表的图形的当前坐标(左上角和右上角坐标)

#使得小球不会超出窗口

pad=self.canvas.coords(self.paddle.id)#获取小球挡板的坐标

if pos[1]=self.canvas_heigh or(pos[3]>=pad[1] and pos[2]>=pad[0] and pos[2]

热点内容
n皇后算法 发布:2025-05-20 01:49:15 浏览:65
如何配置图形电脑 发布:2025-05-20 01:47:51 浏览:391
及解压 发布:2025-05-20 01:44:49 浏览:415
如何用计算器刷安卓 发布:2025-05-20 01:09:29 浏览:576
移动宽带密码重置后怎么办 发布:2025-05-20 01:02:04 浏览:808
php不是内部命令 发布:2025-05-20 00:41:09 浏览:97
淘宝图片上传用什么软件 发布:2025-05-20 00:40:55 浏览:346
mysql64位forlinux 发布:2025-05-20 00:37:25 浏览:345
工伤辅助器如何配置 发布:2025-05-20 00:25:13 浏览:602
opencv存储图片 发布:2025-05-20 00:16:10 浏览:953