『壹』 初學python,有哪些 Pythonic 的源碼推薦閱讀
如果一定要推薦一些 python 的源碼去讀,我的建議是標准庫里關於網路的代碼。從 SocketServer 開始,補上 socket
模塊的知識,熟悉 TCP/UDP 編程,然後了解 Mixin 機制的最佳示例
SocketServer.{ForkingMixIn|ThreadingMixIn},借這個機會了解 thread/threading
模塊,這時會對並發量提出新的要求,就可以讀 select 模塊,開始對 select/{epoll|kqueue}
有深刻理解,搞懂以後就可以接觸一下非同步框架 asyncore 和 asynchat。這時開始出現分岔。如果是做敬拿 game 等以 TCP/UDP
協議為基礎的應用,可以去讀 greenlet 和 gevent,如果是沖弊做 web,則亮判搭走下一條路。
做 web,讀
BaseHTTPServer、SimpleHTTPServer 和 CGIHTTPServer,讀
cgi/cgitb,自己隨意寫框架,讀cookielib,讀 wsgiref,這時候自己寫一個簡便的 web framework 就 so
easy 了,老闆再也不擔心你寫 web 了,選擇 flask/web.py/django/pyramid 都心中有數了。因為走的是 web
的路,所以難免要調用一下別人的 api,搞懂一下 httplib/urllib/urllib/urlparse。
『貳』 python實現超級瑪麗小游戲(動圖演示+源碼分享)
效果演示:
基礎源碼
1.基礎設置(tools部分)
2.設置背景音樂以及場景中的文字(setup部分)
3.設置 游戲 規則(load_screen)
4.設置 游戲 內菜舉埋單等(main_menu)
5.main()
6.調用以上函數實現
1.基肆答橘礎設置(tools部分)
這個裂團部分設置馬里奧以及 游戲 中蘑菇等怪的的移動設置。
『叄』 我想閱讀用python開發的項目的源碼,求推薦
github上面很多。關鍵是業務。你想做網路的話可以看看web.py和大將。想做數值的話看numpy。游戲的話,看pygame。不看業務就看源代碼,很頭疼的。
『肆』 在線等!求一個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小游戲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版本: 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寫一個簡單的小游戲
相信大家都玩過俄羅斯方塊吧,應該是小時候的回憶吧,但是想不想了解一下這個程序是怎麼寫出來的呢,自己寫出來的應該玩起來更有感覺吧!
感覺還是蠻好玩吧!
接下來,我就分享一下這個游戲的源碼過程啊!
先用python創建一個py文件
定義這次程序所需要的類
然後寫出它所需要的模塊
畫背景圖
畫網格線
# 畫已經落下的方塊
# 畫單個方塊
# 畫得分等信息
這樣就可以寫出來一個十分簡單的俄羅斯方塊啦,是不是覺得還不錯呢!