当前位置:首页 » 编程语言 » python游戏案例

python游戏案例

发布时间: 2023-01-08 23:00:36

① 求一个python案例

# 以下程序可能要安装OpenCV2.0(并编译好并配置好环境)以及Xvid解码器才能运行
# _*_coding: cp936_*_
import cv
capture = cv.CreateFileCapture("tmp.avi")
#请确保当前目录下有tmp.avi文件
fps = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FPS)
totalFrameNumber =cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_COUNT)
frameWidth = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH)
frameHeight = cv.GetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT)
print fps, totalFrameNumber, frameWidth, frameHeight
frame = cv.QueryFrame(capture)
while frame:
cv.ShowImage('Title', frame)
frame = cv.QueryFrame(capture)
if cv.WaitKey(1000 / fps) == 27:# ESC键退出视频播放
cv.DestroyWindow('Title')
break

一个文件夹整理工具wxPython版本(不清楚软件用法情况下可以打开该软件看看界面但请不要使用里面的功能,后果自负。)
# -*- coding: cp936 -*-
# file:aa.py
import os, shutil, sys
import wx

sourceDir = ''
sourceFiles = ''
preWord = 0

def browse(event):
global sourceDir, textPreWord, textDirName
dialog = wx.DirDialog(None, u'选择待处理文件夹', style = wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
sourceDir = dialog.GetPath().strip('\"')
textDirName.SetLabel(sourceDir)
dialog.Destroy()
textPreWord.SetFocus()

def okRun(event):
global preWord, sourceDir, sourceFiles, textPreWord
preWord = int(textPreWord.GetValue())
if preWord <= 0:
wx.MessageBox(u'请正确输入前缀字符个数!', u'出错啦', style = wx.ICON_ERROR | wx.OK)
textPreWord.SetFocus()
return
sourceDir = textDirName.GetValue()
sourceFiles = os.listdir(sourceDir)
for currentFile in sourceFiles:
tmp = currentFile
currentFile = sourceDir + '\\' + currentFile
currentFile = currentFile.strip('\"')
if os.path.isdir(currentFile):
continue
targetDir = '%s\\%s'%(sourceDir, tmp[:preWord])
if not os.path.exists(targetDir):
os.mkdir(targetDir)
shutil.move(currentFile, targetDir)
wx.MessageBox(u'任务完成!', u'好消息', style = wx.ICON_ERROR | wx.OK)

def onChange(event):
global dir1, textDirName
p = dir1.GetPath()
textDirName.SetLabel(p)

app = wx.App(0)
win = wx.Frame(None, title = u'文件整理', size = (400, 450))
bg = wx.Panel(win)

btnBrowse = wx.Button(bg, label = u'浏览')
btnBrowse.Bind(wx.EVT_BUTTON, browse)

btnRun = wx.Button(bg, label = u'整理')
btnRun.Bind(wx.EVT_BUTTON, okRun)

dir1 = wx.GenericDirCtrl(bg, -1, dir='', style=wx.DIRCTRL_DIR_ONLY)
tree = dir1.GetTreeCtrl()
dir1.Bind(wx.wx.EVT_TREE_SEL_CHANGED, onChange, id = tree.GetId())

textPreWord = wx.TextCtrl(bg)
textDirName = wx.TextCtrl(bg)
textPreWord.SetFocus()

class MyFileDropTarget(wx.FileDropTarget):#声明释放到的目标
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window

def OnDropFiles(self, x, y, filenames):#释放文件处理函数数据
for name in filenames:
if not os.path.isdir(name):
wx.MessageBox(u'只能选择文件夹!', '出错啦', style = wx.ICON_ERROR | wx.OK)
return
self.window.SetValue(name)

dt = MyFileDropTarget(textDirName)
textDirName.SetDropTarget(dt)

hbox0 = wx.BoxSizer()
hbox0.Add(dir1, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)

hbox1 = wx.BoxSizer()
hbox1.Add(textDirName, proportion = 1, flag = wx.EXPAND, border = 5)
hbox1.Add(btnBrowse, proportion = 0, flag = wx.LEFT, border = 5)

hbox2 = wx.BoxSizer()
hbox2.Add(textPreWord, proportion = 1, flag = wx.EXPAND, border = 5)
hbox2.Add(btnRun, proportion = 0, flag = wx.LEFT, border = 5)

vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(hbox0, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
vbox.Add(wx.StaticText(bg, -1, u'\n 选择待处理文件夹路径:'))
vbox.Add(hbox1, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
vbox.Add(wx.StaticText(bg, -1, u'\n\n 前缀字符个数:'))
vbox.Add(hbox2, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
vbox.Add(wx.StaticText(bg, -1, u'\n'))

bg.SetSizer(vbox)
win.Center()
win.Show()

app.MainLoop()
#py2exe打包代码如下:
from distutils.core import setup
import py2exe
setup(windows=["aa.py"])
打包好了之后有18Mb。

一个文件内容批量替换摸查器(wxPython版本):
# _*_ coding:cp936 _*_
from string import join, split
import os
import wx

def getAllFiles(adir):
tmp = []
for parent, dirs, files in os.walk(adir):
for afile in files:
tmp.append(os.path.join(parent, afile))
return tmp

def browse(event):
dialog = wx.DirDialog(None, '选择待处理文件夹', style=wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
aDir = dialog.GetPath()
textDir.SetLabel(aDir)
dialog.Destroy()

def check():
promp.SetForegroundColour('#FF0000')
promp.SetLabel(' 搜索中...')
listFound.ClearAll()
tmp = []
files = getAllFiles(textDir.GetValue())
for filename in files:
try:
afile = open(filename, 'r')
except IOError:
print '打开文件错误。'
continue
try:
content = afile.read().decode('utf-8')
afile.close()
except:
try:
afile = open(filename, 'r')
content = afile.read().decode('cp936')
afile.close()
except:
continue
if textNeedChar.GetValue() in content:
tmp.append(filename)
listFound.InsertStringItem(0, filename)
parentDir.SetForegroundColour('#FF0000')
# parentDir.SetLabel(' 正在搜索:'+filename)
return tmp

def onFind(event):
check()
parentDir.SetLabel(' 搜索结果:')
promp.SetLabel(' 任务完成。')
wx.MessageBox(listFound.GetItemCount() and '任务完成,找到%d个文件。' % listFound.GetItemCount()
or '未找到包含"%s"的文件!' % textNeedChar.GetValue().encode('cp936'), '查找结束',
style=wx.ICON_INFORMATION | wx.OK)

def onReplace(event):
dg = wx.TextEntryDialog(bg, '替换成:', '提示', style=wx.OK | wx.CANCEL)
if dg.ShowModal() != wx.ID_OK:
return
files = check()
userWord = dg.GetValue()
#if not userWord:
#wx.MessageBox('请输入要替换为何字!', style=wx.ICON_ERROR | wx.OK)
#onReplace(event)
#return
for filename in files:
try:
afile = open(filename, 'r')
except IOError:
print '打开文件错误。'
continue
try:
content = afile.read().decode('utf-8')
afile.close()
except:
try:
afile = open(filename, 'r')
content = afile.read().decode('cp936')
afile.close()
except IOError:
print '打开文件错误。'
continue
content = content.replace(textNeedChar.GetValue(), userWord)
try:
content = content.encode('utf-8')
except:
pass
open(filename, 'w').write(content)

parentDir.SetLabel(' 替换的文件:')
promp.SetLabel(' 任务完成。')
wx.MessageBox(listFound.GetItemCount() and '任务完成,替换了%d个文件。' % listFound.GetItemCount()
or '未找到包含"%s"的文件!' % textNeedChar.GetValue().encode('cp936'), '替换结束', style=wx.ICON_INFORMATION | wx.OK)

app = wx.App(0)
win = wx.Frame(None, title='文件整理', size=(400, 450))
bg = wx.Panel(win)

btnBrowse = wx.Button(bg, label='浏览')
btnBrowse.Bind(wx.EVT_BUTTON, browse)

btnFind = wx.Button(bg, label='查找')
btnFind.Bind(wx.EVT_BUTTON, onFind)
btnFind.SetDefault()

btnReplace = wx.Button(bg, label='替换')
btnReplace.Bind(wx.EVT_BUTTON, onReplace)

textNeedChar = wx.TextCtrl(bg, value='你好')
textDir = wx.TextCtrl(bg, value='E:\Workspace\Python\Python\e')

parentDir = wx.StaticText(bg)
promp = wx.StaticText(bg)

listFound = wx.ListCtrl(bg, style=wx.VERTICAL)

class MyFileDropTarget(wx.FileDropTarget):#声明释放到的目标
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window

def OnDropFiles(self, x, y, filenames):#释放文件处理函数数据
for name in filenames:
'''if not os.path.isdir(name):
wx.MessageBox('只能选择文件夹!', '出错啦', style=wx.ICON_ERROR | wx.OK)
return '''
self.window.SetValue(name)

dt = MyFileDropTarget(textDir)
textDir.SetDropTarget(dt)

hbox1 = wx.BoxSizer()
hbox1.Add(textDir, proportion=1, flag=wx.EXPAND, border=5)
hbox1.Add(btnBrowse, proportion=0, flag=wx.LEFT, border=5)

hbox2 = wx.BoxSizer()
hbox2.Add(textNeedChar, proportion=1, flag=wx.EXPAND, border=5)
hbox2.Add(btnFind, proportion=0, flag=wx.LEFT, border=5)
hbox2.Add(btnReplace, proportion=0, flag=wx.LEFT, border=5)

vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(wx.StaticText(bg, -1, '\n 选择待处理文件夹(可拖动文件夹到下面区域中):'))
vbox.Add(hbox1, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
vbox.Add(wx.StaticText(bg, -1, '\n\n 要替换 / 查找的文字:'))
vbox.Add(hbox2, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
vbox.Add(promp, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
vbox.Add(parentDir, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
vbox.Add(listFound, proportion=1,
flag=wx.EXPAND | wx.LEFT | wx.BOTTOM | wx.RIGHT, border=5)

bg.SetSizer(vbox)
win.Center()
win.Show()

app.MainLoop()

② 《Python宝典》txt下载在线阅读全文,求百度网盘云资源

《Python宝典》(杨佩璐/宋强)电子书网盘下载免费在线阅读

链接:

提取码:rbpu

书名:《Python宝典》

作者:杨佩璐/宋强

译者:

豆瓣评分:

出版社:电子工业出版社

出版年份:2014-5

页数:504

内容简介:Python是目前流行的脚本语言之一。《Python宝典》由浅入深、循序渐进地为读者讲解了如何使用Python进行编程开发。《Python宝典》内容共分三篇,分为入门篇、高级篇和案例篇。入门篇包括Python的认识和安装、开发工具简介、Python基本语法、数据结构与算法、多媒体编程、系统应用、图像处理和GUI编程等内容。高级篇包括用Python操作数据库、进行Web开发、网络编程、科学计算、多线程编程等内容。案例篇选择了3个案例演示了Python在Windows系统优化、大数据处理和游戏开发方面的应用。

《Python宝典》针对Python的常用扩展模块给出了详细的语法介绍,并且给出了典型案例,通过对《Python宝典》的学习,读者能够很快地使用Python进行编程开发。

《Python宝典》适合Python初学者、程序设计人员、编程爱好者、本科及大专院校学生,以及需要进行对科学的计算的工程人员阅读。

③ 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软件开发的案例有哪些,可用于哪些开发

列举一些比较有名的网站或应用。这其中有一些是用python进行开发,有一些在部分业务或功能上使用到了python,还有的是支持python作为扩展脚本语言。数据大部分来自Wikepedia和Quora。
Reddit - 社交分享网站,最早用Lisp开发,在2005年转为python
Dropbox - 文件分享服务
豆瓣网 - 图书、唱片、电影等文化产品的资料数据库网站
Django - 鼓励快速开发的Web应用框架
Fabric - 用于管理成百上千台Linux主机的程序库
EVE - 网络游戏EVE大量使用Python进行开发
Blender - 以C与Python开发的开源3D绘图软件
BitTorrent - bt下载软件客户端
Ubuntu Software Center - Ubuntu 9.10版本后自带的图形化包管理器
YUM - 用于RPM兼容的Linux系统上的包管理器
Civilization IV - 游戏《文明4》
Battlefield 2 - 游戏《战地2》
Google - 谷歌在很多项目中用python作为网络应用的后端,如Google Groups、Gmail、Google Maps等,Google App Engine支持python作为开发语言
NASA - 美国宇航局,从1994年起把python作为主要开发语言
Instrial Light & Magic - 工业光魔,乔治·卢卡斯创立的电影特效公司
Yahoo! Groups - 雅虎推出的群组交流平台
YouTube - 视频分享网站,在某些功能上使用到python
Cinema 4D - 一套整合3D模型、动画与绘图的高级三维绘图软件,以其高速的运算和强大的渲染插件着称
Autodesk Maya - 3D建模软件,支持python作为脚本语言
gedit - Linux平台的文本编辑器
GIMP - Linux平台的图像处理软件
Minecraft: Pi Edition - 游戏《Minecraft》的树莓派版本
MySQL Workbench - 可视化数据库管理工具
Digg - 社交新闻分享网站
Mozilla - 为支持和领导开源的Mozilla项目而设立的一个非营利组织
Quora - 社交问答网站
Path - 私密社交应用
Pinterest - 图片社交分享网站
SlideShare - 幻灯片存储、展示、分享的网站
Yelp - 美国商户点评网站
Slide - 社交游戏/应用开发公司,被谷歌收购

⑤ 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]

⑥ Python能做什么,能够开发什么项目

Python是一种计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的、大型项目的开发。

Python是一种解释型脚本语言,可以应用于Web 和 Internet开发、科学计算和统计、人工智能、教育、桌面界面开发、软件开发、后端开发这些领域。

Python的应用

1、系统编程

提供API(Application Programming Interface应用程序编程接口),能方便进行系统维护和管理,Linux下标志性语言之一,是很多系统管理员理想的编程工具。

2、图形处理

有PIL、Tkinter等图形库支持,能方便进行图形处理。

3、数学处理

NumPy扩展提供大量与许多标准数学库的接口。

4、文本处理

python提供的re模块能支持正则表达式,还提供SGML,XML分析模块,许多程序员利用python进行XML程序的开发。


5、数据库编程

程序员可通过遵循Python DB-API(数据库应用程序编程接口)规范的模块与Microsoft SQL Server,Oracle,Sybase,DB2,MySQL、SQLite等数据库通信。python自带有一个Gadfly模块,提供了一个完整的SQL环境。

6、网络编程

提供丰富的模块支持sockets编程,能方便快速地开发分布式应用程序。很多大规模软件开发计划例如Zope,Mnet 及BitTorrent. Google都在广泛地使用它。

7、Web编程

应用的开发语言,支持最新的XML技术。

8、多媒体应用

Python的PyOpenGL模块封装了“OpenGL应用程序编程接口”,能进行二维和三维图像处理。PyGame模块可用于编写游戏软件。

9、pymo引擎

PYMO全称为python memories off,是一款运行于Symbian S60V3,Symbian3,S60V5, Symbian3, Android系统上的AVG游戏引擎。因其基于python2.0平台开发,并且适用于创建秋之回忆(memories off)风格的AVG游戏,故命名为PYMO。

10、黑客编程

python有一个hack的库,内置了你熟悉的或不熟悉的函数,但是缺少成就感。

⑦ 求简洁优美的python代码例子、片段、参考资料

建议你去看一本书:《计算机程序的构造与解释》。里面用的语言是Scheme,一种Lisp的方言。通过这本书学习程序的抽象、封装,以及重要的函数式编程思想。等看完这本书以后,你在来写写Python代码,就知道如何让其简洁直观而又不失其可读性了。

同时,要让代码写得简洁,你也得熟悉Python本身,充分挖掘其能力。Python内建的几个高阶函数:map,rece,filter,enumerate等等,lambda表达式,zip函数,以及标准库里强大的itertools、functools模块,都是函数式编程的利器。此外Python本身提供了许多非常好的语法糖衣,例如装饰器、生成器、*args和**kwargs参数、列表推导等等,也是简化代码的有效手段。还有,Python有着强大的库。多参考官方的文档了解其原理和细节,我相信你也能写出高效简洁的代码的。

其实代码的简洁没有什么捷径,它要求你了解你要解决的问题,所使用的语言和工具,相关的算法或流程。这些都得靠你自己不断地练习和持续改进代码,不断地专研问题和学习知识。加油吧,少年!

楼下让你参考PEP 20,其实不用去查,标准库里的this模块就是它(试试import this):The Zen of Python(Python之禅)。它就是一段话:

s='''
TheZenofPython,byTimPeters

Beautifulisbetterthanugly.
Explicitisbetterthanimplicit.
Simpleisbetterthancomplex.
.
Flatisbetterthannested.
Sparseisbetterthandense.
Readabilitycounts.
Specialcasesaren'tspecialenoughtobreaktherules.
.
Errorsshouldneverpasssilently.
Unlessexplicitlysilenced.
Inthefaceofambiguity,refusethetemptationtoguess.
Thereshouldbeone--andpreferablyonlyone--obviouswaytodoit.
'reDutch.
Nowisbetterthannever.
*right*now.
,it'sabadidea.
,itmaybeagoodidea.
--let'sdomoreofthose!
'''

让我们来做个小游戏吧:统计上面这段话的单词总数目,以及各个单词的数量(不区分大小写),然后按字典顺序输出每个单词出现的次数。要求,例如it's和you're等要拆分成it is和you are。你会怎么写代码呢?如何保持简洁呢?

下面是我的参考答案,争取比我写的更简洁吧~

importre

p=re.compile("(w+)('s|'re|n't)?")
wc={}
tail_map={"'s":'is',"'re":'are',"n't":'not'}

forminre.finditer(p,s):
word=m.group(1).lower()#Getthewordinlowercase
wc[word]=wc.get(word,0)+1#Increasewordcount
tail=m.group(2)#Getthewordtail
iftailisnotNone:#Ifawordtailexists,
tail=tail_map[tail]#mapittoitsfullform
wc[tail]=wc.get(tail,0)+1#Increasewordcount

print('Totalwordcount:%d'%sum(wc.values()))#Outputthetotalcount
max_len=max(map(len,wc.keys()))#
forwinsorted(wc.keys()):#Sortthewords
print('%*s=>%d'%(max_len,w,wc[w]))#Output

⑧ python 案例问题

这个有2个知识点

1、python 的bool类型,也就是True和False,实质上市int型,也就是1和0,即True==1,False = 0
2、 [
[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
[31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
][is_leap_year(year)]
也就是函数返回True,返回list[1],反之list[0]

热点内容
java返回this 发布:2025-10-20 08:28:16 浏览:585
制作脚本网站 发布:2025-10-20 08:17:34 浏览:881
python中的init方法 发布:2025-10-20 08:17:33 浏览:574
图案密码什么意思 发布:2025-10-20 08:16:56 浏览:761
怎么清理微信视频缓存 发布:2025-10-20 08:12:37 浏览:677
c语言编译器怎么看执行过程 发布:2025-10-20 08:00:32 浏览:1005
邮箱如何填写发信服务器 发布:2025-10-20 07:45:27 浏览:250
shell脚本入门案例 发布:2025-10-20 07:44:45 浏览:108
怎么上传照片浏览上传 发布:2025-10-20 07:44:03 浏览:799
python股票数据获取 发布:2025-10-20 07:39:44 浏览:705