python游戲源碼
『壹』 python可以寫軟體么怎麼寫
22點24分准時推送,第一時間送達
編輯:技術君 | 來源:youerning
上一篇:
正文
前言
用 Python 寫安卓 APP 肯定不是最好的選擇,目前用Java和 kotlin 寫的居多,但是肯定也是一個很偷懶的選擇,而且實在不想學習 Java,再者,就編程而言已經會的就 Python與Golang(註:Python,Golang水平都一般),那麼久Google了一下Python 寫安卓的 APP 的可能性,還真行。
既然要寫個APP,那麼總得要有個想法吧。其實想做兩個APP來著,一個是自己寫著好玩的,一個是關於運維的。關於運維的APP,設計應該如下
可能長這樣
然後設計應該是這樣。
如果覺得可行的話,評論留言一下你覺得應該寫進這個APP的運維常用命令吧^_^,筆者暫時想到的是top,free -m,df –h,uptime,iftop,iotop,如果有什麼好的想法就狠狠的砸過來吧,筆者到時應該也會把這個寫成一個項目放到github上,大家一起用嘛,開源才是王道,哈哈。
開發安卓APP
我們使用kivy開發安卓APP,Kivy是一套專門用於跨平台快速應用開發的開源框架,使用Python和Cython編寫,對於多點觸控有著非常良好的支持,不僅能讓開發者快速完成簡潔的交互原型設計,還支持代碼重用和部署,絕對是一款頗讓人驚艷的NUI框架。
因為跨平台的,所以只寫一遍代碼,就可以同時生成安卓及IOS的APP,很酷吧。
本文會帶大家寫一個Hello world並瞧一瞧 Python 版的2048的代碼
kivy安裝
環境說明:筆者在用的是Python2.7.10
這里僅介紹windows平台安裝
所有平台參考: https://kivy.org/#download
更新pip,setuptools
python -m pip install --upgrade pip wheel setuptools
然後是安裝所需要的依賴
python -m pip install docutils pygmentspypiwin32 kivy.deps.sdl2 kivy.deps.glew
kivy.deps.gstreamer --extra-index-url https://kivy.org/downloads/packages/simple/
值得注意的是,上面的安卓需要訪問Google,所以請自備梯子,而且kivy.deps.gstreamer這個包比較大(95MB),可以單獨本地安裝,http://pan..com/s/1o7mlxNk
然後就是安裝kivy了
python -m pip install kivy
至此,安裝就已經完畢了,值得注意的是64位系統沒有開啟虛擬化支持,在導入kivy的時候會報錯,如果是64位系統就設置一下機器的BIOS,開啟虛擬化支持吧。
註:這里只是kivy的運行環境,這樣我就能直接在windows機器上直接調試了,怎麼將代碼編譯成APK文件我們會在後面講到。
如果kivy在python中應該就能導入了。
按照世界慣例,我們」hello」一下吧。
新建一個.py文件
from kivy.app import Appfrom kivy.uix.button importButton
class TestApp(App):
def build(self):
return Button(text='Hello,kivy')
TestApp().run()
運行
然後會彈出一個框,大概如下,點擊」hello,kivy」會變顏色
點擊窗口並按「F1」會這個窗口的一些屬性
然後我們回過頭看一看代碼。
##導入App,然後讓TestApp這個類繼承
from kivy.app import App##導入一個Button,運維有這個button,當你點擊的時候才會有所反應
from kivy.uix.button
importButton
###定義類,名字必須是xxxAppclass TestApp(App):
###build一個Button
def build(self):
###返回一個Button,文字內容是「Hello,kivy」
return Button(text='Hello,kivy')
##運行,因為繼承了App,所以才有的run這個方法TestApp().run()
上面就是我們的Hello了
在windows上運行當然沒有什麼太大的意義,怎麼在安卓手機上運行才是我們想要的,
這時我們需要一個編譯環境。
官方說明的環境,如下:
You』ll need:
A linux computer or a virtual machine
Java
Python 2.7 (not 2.6.)
Jinja2 (python mole)
Apache ant
Android SDK
Kivy Buildozer VM
Or select the Torrent
雖然官方提供了一個似乎還不錯的虛擬機鏡像,但是還是有很多內容需要翻出去,所以筆者在這里提供相對而言更加完善的鏡像
下載地址:http://pan..com/s/1geyAY7x
注:virtualbox,vmware需自行下載
root密碼:kivy
默認使用賬戶kivy,密碼:kivy123
當然你也可以下載官方鏡像,因為第一次編譯需要去國外下一大堆東西,所以請自行去下載。
Virtual Machine
A Virtual Machine with Android SDK and NDK and all otherpre-requisites pre installed to ease apk generation:
在筆者提供的鏡像里,桌面上有一個dev_and,只要將上面寫的代碼,放入這個文件夾即可(當然也可以在其他目錄,後面會講到)。
在公眾號Python人工智慧技術後台回復「面試」,獲取騰訊Python面試題和答案。
cd Desktop/dev_and/
初始化會在當前目錄生成一個buildozer.spec文件 用於配置生成的apk相關信息
buildozer init
###修改buildozer.spec文件
vi buildozer.spec
至少修改下面三項
# (str) Title of your applicationtitle = helloworld
# (str) Package namepackage.name = helloapp
# (str) Package domain (needed for android/ios packaging)package.domain = youer.com
然後注釋
# (str) Application versioning (method 1)#version.regex = __version__ = ['"](.*)['"]#version.filename = %(source.dir)s/main.py
下面這行改為非注釋
version = 1.2.0
最後我們生成我們需要的apk文件
buildozer -v android debug
buildozer.spec更詳細的相關參數配置參考:
http://buildozer.readthedocs.org/en/latest/specifications.html
buildozer命令會在當前文件夾創建一個bin,該文件夾裡面有我們想要的apk文件
helloapp-1.2.0-debug.apk
helloapp-1.2.0-debug.apk
安裝以後是這樣:
話說在編譯的時候可能出現空間不足的情況,根據虛擬機的不同(vmware或virtualbox)自行擴容吧。
最後我們來瞧瞧簡易版Python開發的2048這個游戲的源代碼。
代碼:
https://github.com/mvasilkov/kb/tree/master/6_2048
先看效果圖:
試玩了一下,還是蠻流暢的,有興趣的可以下載玩一下
下載地址:http://pan..com/s/1eQZACDW
這個游戲代碼雖然不長,但是還是蠻占篇幅的,所以簡要的說明一下流程。
主要由三部分組成,一是素材,圖片音頻之類的文件,二是Python代碼,三是kv文件,這個kv文件有點像 html 中的css。
Python代碼的文件名一般命名為 main.py
然後一定有一個叫做 XXXApp 的類,並繼承 App。
比如該類叫做GameApp,那麼該目錄下的kv文件則必須為Game,如上圖所示,如果不是,那麼kv文件中的一些設定就不會生效。
比如設定一個標簽
Label:
id: time
text: 'xxxx'
font_size: 60
id為time,text文本內容為'xxxx',然後字體為60
好吧,點到為止吧,不過似乎什麼都沒點到~~~
你還有什麼想要補充的嗎?
你在看嗎?一起成長
『貳』 從哪能找到python示常式序或源碼
哥,要下載源碼也是去官網下載啊,點下面那個就行了
https://www.python.org/ftp/python/3.4.3/python-3.4.3.tar.xz
『叄』 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 五子棋源代碼,最好是有「人人對弈」和「人機對弈」功能的,不勝感謝!
試試這個吧。
import numpy as np
import pygame
import sys
import traceback
import
from pygame.locals import *
pygame.init()
pygame.mixer.init()
#顏色
background=(201,202,187)
checkerboard=(80,80,80)
button=(52,53,44)
#音樂
play_chess_sound = pygame.mixer.Sound("music/play_chess.wav")
play_chess_sound.set_volume(0.2)
button_sound = pygame.mixer.Sound("music/button.wav")
button_sound.set_volume(0.2)
victor_sound = pygame.mixer.Sound("music/victory.wav")
victor_sound.set_volume(0.2)
#繪制棋盤
def Draw_a_chessboard(screen):
#填充背景色
screen.fill(background)
Background=pygame.image.load("background.jpg").convert_alpha()
screen.blit(Background,(0,0))
#畫棋盤
for i in range(21):
pygame.draw.line(screen, checkerboard, (40*i+3, 3), (40*i+3, 803))
pygame.draw.line(screen, checkerboard, (3, 40*i+3), (803, 40*i+3))
#畫邊線
pygame.draw.line(screen, checkerboard, (3, 3), (803, 3),5)
pygame.draw.line(screen, checkerboard, (3, 3), (3, 803),5)
pygame.draw.line(screen, checkerboard, (803, 3), (803, 803),5)
pygame.draw.line(screen, checkerboard, (3, 803), (803, 803),5)
#畫定位點
pygame.draw.circle(screen, checkerboard, (163, 163), 6)
pygame.draw.circle(screen, checkerboard, (163, 643), 6)
pygame.draw.circle(screen, checkerboard, (643, 163), 6)
pygame.draw.circle(screen, checkerboard, (643, 643), 6)
pygame.draw.circle(screen, checkerboard, (403, 403), 6)
#畫『悔棋』『重新開始』跟『退出』按鈕
pygame.draw.rect(screen,button,[900,350,120,100],5)
pygame.draw.rect(screen,button,[900,500,200,100],5)
pygame.draw.rect(screen,button,[900,650,200,100],5)
s_font=pygame.font.Font('font.ttf',40)
text1=s_font.render("悔棋",True,button)
text2=s_font.render("重新開始",True,button)
text3=s_font.render("退出遊戲",True,button)
screen.blit(text1,(920,370))
screen.blit(text2,(920,520))
screen.blit(text3,(920,670))
#繪制棋子(橫坐標,縱坐標,屏幕,棋子顏色(1代表黑,2代表白))
def Draw_a_chessman(x,y,screen,color):
if color==1:
Black_chess=pygame.image.load("Black_chess.png").convert_alpha()
screen.blit(Black_chess,(40*x+3-15,40*y+3-15))
if color==2:
White_chess=pygame.image.load("White_chess.png").convert_alpha()
screen.blit(White_chess,(40*x+3-15,40*y+3-15))
#繪制帶有棋子的棋盤
def Draw_a_chessboard_with_chessman(map,screen):
screen.fill(background)
Draw_a_chessboard(screen)
for i in range(24):
for j in range(24):
Draw_a_chessman(i+1,j+1,screen,map[i][j])
#定義存儲棋盤的列表,
#列表為24列24行是因為判斷是否勝利函數里的索引會超出19
#列表大一點不會對游戲有什麼影響
map=[]
for i in range(24):
map.append([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])
#清零map列表
def clear():
global map
for i in range(24):
for j in range(24):
map[i][j]=0
#判斷是否勝利
def win(i, j):
k = map[i][j]
p=[]
for a in range(20):
p.append(0)
for i3 in range(i-4,i+5):
for j3 in range(j-4,j+5):
if (map[i3][j3] == k and i3 - i == j3 - j and i3 <= i and j3 <= j):
p[0]+=1
if (map[i3][j3] == k and j3 == j and i3 <= i and j3 <= j):
p[1]+=1
if (map[i3][j3] == k and i3 == i and i3 <= i and j3 <= j):
p[2]+=1
if (map[i3][j3] == k and i3 - i == j3 - j and i3 >= i and j3 >= j):
p[3]+=1
if (map[i3][j3] == k and j3 == j and i3 >= i and j3 >= j):
p[4]+=1
if (map[i3][j3] == k and i3 == i and i3 >= i and j3 >= j):
p[5]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i and j3 >= j):
p[6]+=1
if (map[i3][j3] == k and i3 - i == j - j3 and i3 >= i and j3 <= j):
p[7]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[8]+=1
if (map[i3][j3] == k and j == j3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[9]+=1
if (map[i3][j3] == k and i == i3 and i3 <= i + 1 and i3 >= i - 3 and j3 <= j + 1 and j3 >= j - 3):
p[10]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[11]+=1
if (map[i3][j3] == k and j == j3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[12]+=1
if (map[i3][j3] == k and i == i3 and i3 >= i - 1 and i3 <= i + 3 and j3 >= j - 1 and j3 <= j + 3):
p[13]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i + 1 and i3 >= i - 3 and j3 >= j - 1 and j3 <= j + 3):
p[14]+=1
if (map[i3][j3] == k and i3 - i == j - j3 and i3 >= i - 1 and i3 <= i + 3 and j3 <= j + 1 and j3 >= j - 3):
p[15]+=1
if (map[i3][j3] == k and j - j3 == i - i3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[16]+=1
if (map[i3][j3] == k and j == j3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[17]+=1
if (map[i3][j3] == k and i == i3 and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[18]+=1
if (map[i3][j3] == k and i - i3 == j3 - j and i3 <= i + 2 and i3 >= i - 2 and j3 <= j + 2 and j3 >= j - 2):
p[19]+=1
for b in range(20):
if p[b]==5:
return True
return False
#繪制提示器(類容,屏幕,字大小)
def text(s,screen,x):
#先把上一次的類容用一個矩形覆蓋
pygame.draw.rect(screen,background,[850,100,1200,100])
#定義字體跟大小
s_font=pygame.font.Font('font.ttf',x)
#定義類容,是否抗鋸齒,顏色
s_text=s_font.render(s,True,button)
#將字放在窗口指定位置
screen.blit(s_text,(880,100))
pygame.display.flip()
#用於控制順序
t=True
#用於結束游戲後阻止落子
running=True
#主函數
def main():
#將 t,map,running設置為可改的
global t,map,running,maps,r,h
#將map置零
clear()
#定義儲存所有棋盤狀態的列表(用於悔棋)
map2=.deep(map)
maps=[map2]
#定義窗口
screen = pygame.display.set_mode([1200,806])
#定義窗口名字
pygame.display.set_caption("五子棋")
#在窗口畫出棋盤,提示器以及按鈕
Draw_a_chessboard(screen)
pygame.display.flip()
clock=pygame.time.Clock()
while True:
#只有running為真才能落子,主要用於游戲結束後防止再次落子
if running:
if t:
color=1
text('黑棋落子',screen,54)
else:
color=2
text('白棋落子',screen,54)
for event in pygame.event.get():
#點擊x則關閉窗口
if event.type ==pygame.QUIT:
pygame.quit()
sys.exit()
#點擊窗口裡面類容則完成相應指令
elif event.type == MOUSEBUTTONDOWN:
if event.button == 1:
x,y=event.pos[0],event.pos[1]
for i in range(19):
for j in range(19):
#點擊棋盤相應位置
if i*40+3+20<x<i*40+3+60 and j*40+3+20<y<j*40+3+60 and not map[i][j] and running:
#在棋盤相應位置落相應顏色棋子
Draw_a_chessman(i+1,j+1,screen,color)
#播放音效
play_chess_sound.play(0)
#在map裡面記錄落子位置
map[i][j]=color
#將map存入maps
map3=.deep(map)
maps.append(map3)
#判斷落子後是否有五子一線
if win(i,j):
if t:
text('黑棋勝利,請重新游戲',screen,30)
else:
text('白棋勝利,請重新游戲',screen,30)
#播放音效
victor_sound.play(0)
#阻止再往棋盤落子
running=False
pygame.display.flip()
t=not t
#如果點擊『重新開始』
if 900<x<1100 and 500<y<600:
#取消阻止
running=True
#播放音效
button_sound.play(0)
#重新開始
main()
#點擊『退出遊戲』,退出遊戲
elif 900<x<1100 and 650<y<750:
#播放音效
button_sound.play(0)
pygame.quit()
sys.exit()
#點擊『悔棋』
elif 900<x<1020 and 350<y<450 and len(maps)!=1:
#播放音效
button_sound.play(0)
#刪除maps里最後一個元素
del maps[len(maps)-1]
#再將最後一個元素給map
map=.deep(maps[len(maps)-1])
#切換順序
t=not t
#將map顯示出來
Draw_a_chessboard_with_chessman(map,screen)
#悔棋完成,阻止再次悔棋
x,y=0,0
clock.tick(60)
if __name__ == "__main__":
try:
main()
except SystemExit:
pass
except:
traceback.print_exc()
pygame.quit()
input()
『伍』 怎麼用python編android app
前言:用Python寫安卓APP肯定不是最好的選擇,但是肯定是一個很偷懶的選擇,而且實在不想學習Java,再者,就編程而言已經會的就Python與Golang(註:Python,Golang水平都一般),那麼久Google了一下Python寫安卓的APP的可能性,還真行。
既然要寫個APP,那麼總得要有個想法吧。
其實筆者想做兩個APP來著,一個是自己寫著好玩的,一個是關於運維的。
關於運維的APP,設計應該如下
可能長這樣:

主要由三部分組成,一是素材,圖片音頻之類的文件,二是Python代碼,三是kv文件,這個kv文件有點像html中的css。
Python代碼的文件名一般命名為main.py
然後一定有一個叫做XXXApp的類,並繼承App。
比如該類叫做GameApp,那麼該目錄下的kv文件則必須為Game,如上圖所示,如果不是,那麼kv文件中的一些設定就不會生效。
比如設定一個標簽
Label:
id: time
text: 'xxxx'
font_size: 6012345
id為time,text文本內容為』xxxx』,然後字體為60
好吧,點到為止吧,不過似乎什麼都沒點到~~~
從無到有做一個App,我想我會另起一篇文章吧。
『陸』 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小游戲
Python3X\Lib\turtledemo\nim.py自帶的尼姆游戲
