python代碼小游戲
㈠ 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]