python游戲案例
① 求一個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寶典》(楊佩璐/宋強)電子書網盤下載免費在線閱讀
鏈接:
書名:《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]
