24點遊戲(自動生成隨機數)

2021-09-18 02:40:56 字數 3279 閱讀 7107

如果有錯,請大神指正啊,撒花撒花~~ 

24點遊戲是經典的紙牌益智遊戲。常見遊戲規則:從撲克中每次取出4張牌。使用加減乘除,第乙個能得出24者為贏。(其中,j代表11,q代表12,k代表13,a代表1),按照要求程式設計解決24點遊戲。

隨機產生四個數字用python中的函式進行全排列對於python隨機數的生成,通過匯入包來實現,即import  random本程式中因為要生成4個(1——13)的整形數字,採用randint對於python可以通過python的包itertools所以不用自己寫遞迴函式實現

itertools.permutations
通俗地講,就是返回可迭代物件的所有數學全排列方式。

listcardset = list(set(itertools.permutations(listcardnum, 4)))#全排列4個數

return listcardset

例如:8,13,3,5產生的全排列(8, 13, 3, 5), (13, 5, 8, 3), (5, 3, 8, 13), (13, 3, 8, 5), (3, 5, 8, 13), (3, 13, 5, 8),(3, 5, 13, 8), (5, 3, 13, 8), (8, 13, 5, 3), (8, 5, 13, 3), (8, 3, 5, 13), (5, 8, 3, 13),(13, 8, 3, 5), (13, 3, 5, 8), (8, 3, 13, 5), (5, 8, 13, 3), (3, 8, 13, 5), (5, 13, 3, 8),

(13, 8, 5, 3), (5, 13, 8, 3), (8, 5, 3, 13), (3, 13, 8, 5), (3, 8, 5, 13), (13, 5, 3, 8)

if __name__ == "__main__":

print("************************歡迎進入24點遊戲************************")

print("該系統會隨機產生四張牌,並幫助您算出可以實現24點的所有演算法")

i.需要的包:

import itertools

import random

ii.隨機產生數字和全排列:

def card_rand():

for i in range(4):

list_quanpai = list(set(itertools.permutations(list_random, 4)))#全排列4個數

return list_quanpai

listcard = card_rand() # 排列組合結果

#print(listcard)#輸出所有排列

iii. 計算函式:

def card_calculate():

for i in range(len(listcard)):

list1_card = listcard[i]

cardone = list1_card[0]

cardtwo = list1_card[1]

cardthree = list1_card[2]

cardfour = list1_card[3] # 得到四張牌的點數

flag = false # 標誌位

try:

for o1 in listoperator:

resultone = 0 # 前兩個數的運算結果

if o1 == "+":

resultone = cardone+cardtwo

elif o1 == "-":

resultone = cardone-cardtwo

elif o1 == "*":

resultone = cardone*cardtwo

elif o1 == "/":

resultone = cardone/cardtwo

for o2 in listoperator:

resulttwo = 0 # 前三個數的運算結果

if o2 == "+":

resulttwo = resultone + cardthree

elif o2 == "-":

resulttwo = resultone - cardthree

elif o2 == "*":

resulttwo = resultone * cardthree

elif o2 == "/":

resulttwo = resultone / cardthree

for o3 in listoperator:

resultthree = 0 # 四個數的運算結果

resultfinal = 0 # 最後兩個數的運算結果

if o3 == "+":

resultthree = resulttwo + cardfour

resultfinal = cardthree + cardfour

elif o3 == "-":

resultthree = resulttwo - cardfour

resultfinal = cardthree - cardfour

elif o3 == "*":

resultthree = resulttwo * cardfour

resultfinal = cardthree * cardfour

elif o3 == "/":

resultthree = resulttwo / cardfour

resultfinal = cardthree / cardfour

如需原始碼:24點python源**

隨機生成隨機數

現畫乙個command命令按鈕,進行貼上。private sub command1 click show me scale 0,0 18,8 me.auto redraw true me.draw mode 2 circle 3,4 3,vb red me.auto redraw false lin...

隨機數生成

原型 void srand unsigned seed 用法 srand和rand 配合使用產生偽隨機數序列。rand函式在產生隨機數前,需要系統提供的生成偽隨機數序列的種子,rand根據這個種子的值產生一系列隨機數。如果系統提供的種子沒有變化,每次呼叫rand函式生成的偽隨機數序列都是一樣的。sr...

生成隨機數

1 生成num位數驗證碼 用於簡訊驗證功能 public static random rand new random public static string getcode int num result,s k return result random r new random 建立乙個隨機數生成...