python期末
發布時間: 2025-01-09 09:54:01
㈠ 求python大神給個200行左右的代碼,多點注釋,做期末大作業
#-*-coding:utf-8-*-
importcurses#引入curses模塊,curses是一個在Linux/Unix下廣泛應用的圖形函數庫.,作用是可以繪制在DOS下的用戶界面和漂亮的圖形。
fromrandomimportrandrange,choice#從random模塊引入randrange,choice這兩個類
#從collections引入defaultdict這個類
letter_codes=[ord(ch)forchin'WASDRQwasdrq']#ord函數是把字元轉換成對應的數字
actions=['Up','Left','Down','Right','Restart','Exit']#上,左,下,右,重啟,退出
actions_dict=dict(zip(letter_codes,actions*2))#把字母與動作對應起來。zip是把元組中的值對應起來。
#############################
WUp
ALeft
SDown
DRight
RRestart
QExit
wUp
aLeft
sDown
dRight
rRestart
QExit
##############################################
defget_user_action(keyboard):
char="N"#char的初始值為Nwhilecharnotinactions_dict:
char=keyboard.getch()returnactions_dict[char]#阻塞+循環,直到獲得用戶有效輸入才返回對應行為deftranspose(field):return[list(row)forrowinzip(*field)]#zip函數里邊加*號,是把行變列,列變行。所以這句代碼是行列轉置definvert(field):return[row[::-1]forrowinfield]#這句代碼是把列表前後顛倒classGameField(object):#創建一個叫做GameField的類,用來創建棋盤def__init__(self,height=4,width=4,win=2048):這個類三個參數self.height=height#高self.width=width#寬self.win_value=win#過關分數self.score=0#當前分數self.highscore=0#最高分self.reset()#重置棋盤defreset(self):#定義一個reset函數ifself.score>self.highscore:#如果當前分數大於最高分,那麼把當前分數賦值給最高分self.highscore=self.scoreself.score=0#當前分數恢復到0分self.field=[[0foriinrange(self.width)]forjinrange(self.height)]#橫縱坐標恢復到(0,0)self.spawn()#調用spawn這個函數self.spawn()defmove(self,direction):#定義move函數defmove_row_left(row):#向左移deftighten(row):#squeesenon-zeroelementstogether把零散的非零單元擠到一塊
new_row=[iforiinrowifi!=0]#如果i不等於零,把他們賦值到new_row這個元組中
new_row+=[0foriinrange(len(row)-len(new_row))]#其餘位置用0補充returnnew_row#返回這個元組defmerge(row):#定義merge函數,用來合並單元
pair=False#pair初始值為假
new_row=[]#new_row初始值為空foriinrange(len(row)):#讓i在格子里循環ifpair:如果pair為真
new_row.append(2*row[i])#那麼把把row【i】的值乘以2,追加到new_row後邊self.score+=2*row[i]#並且得分為row【i】的值乘以2
pair=False#pair重新賦值為假else:如果pair為真ifi+1<len(row)androw[i]==row[i+1]:#如果i+1還沒到邊界,並且此時的row【i】=row【i+1】
pair=True#那麼pair為真
new_row.append(0)#new_row後追加零else:
new_row.append(row[i])#否則追加row【i】
assertlen(new_row)==len(row)#提醒兩者長度一致returnnew_rowreturntighten(merge(tighten(row)))#反復合並,知道不能合並為止
moves={}
moves['Left']=lambdafield:
[move_row_left(row)forrowinfield]#做移動
moves['Right']=lambdafield:
invert(moves['Left'](invert(field)))#invert是逆轉
moves['Up']=lambdafield:
transpose(moves['Left'](transpose(field)))#transpose是轉置
moves['Down']=lambdafield:
transpose(moves['Right'](transpose(field)))ifdirectioninmoves:ifself.move_is_possible(direction):#如果移動方向在四個方向上,self.field=moves[direction](self.field)那麼調用moves函數self.spawn()#產生隨機數returnTrueelse:returnFalsedefis_win(self):returnany(any(i>=self.win_valueforiinrow)forrowinself.field)defis_gameover(self):returnnotany(self.move_is_possible(move)formoveinactions)defdraw(self,screen):
help_string1='(W)Up(S)Down(A)Left(D)Right'
help_string2='(R)Restart(Q)Exit'
gameover_string='GAMEOVER'
win_string='YOUWIN!'defcast(string):
screen.addstr(string+' ')defdraw_hor_separator():
line='+'+('+------'*self.width+'+')[1:]
separator=defaultdict(lambda:line)ifnothasattr(draw_hor_separator,"counter"):
draw_hor_separator.counter=0
cast(separator[draw_hor_separator.counter])
draw_hor_separator.counter+=1defdraw_row(row):
cast(''.join('|{:^5}'.format(num)ifnum>0else'|'fornuminrow)+'|')
screen.clear()
cast('SCORE:'+str(self.score))if0!=self.highscore:
cast('HGHSCORE:'+str(self.highscore))forrowinself.field:
draw_hor_separator()
draw_row(row)
draw_hor_separator()ifself.is_win():
cast(win_string)else:ifself.is_gameover():
cast(gameover_string)else:
cast(help_string1)
cast(help_string2)defspawn(self):
new_element=4ifrandrange(100)>89else2
(i,j)=choice([(i,j)foriinrange(self.width)forjinrange(self.height)ifself.field[i][j]==0])self.field[i][j]=new_elementdefmove_is_possible(self,direction):defrow_is_left_movable(row):
defchange(i):#trueifthere'llbechangeini-thtileifrow[i]==0androw[i+1]!=0:#MovereturnTrueifrow[i]!=0androw[i+1]==row[i]:#(change(i)foriinrange(len(row)-1))
check={}
check['Left']=lambdafield:
any(row_is_left_movable(row)forrowinfield)
check['Right']=lambdafield:
check['Left'](invert(field))
check['Up']=lambdafield:
check['Left'](transpose(field))
check['Down']=lambdafield:
check['Right'](transpose(field))ifdirectionincheck:returncheck[direction](self.field)else:returnFalsedefmain(stdscr):definit():#重置游戲棋盤
game_field.reset()return'Game'defnot_game(state):#畫出GameOver或者Win的界面
game_field.draw(stdscr)#讀取用戶輸入得到action,判斷是重啟游戲還是結束游戲
action=get_user_action(stdscr)
responses=defaultdict(lambda:state)#默認是當前狀態,沒有行為就會一直在當前界面循環
responses['Restart'],responses['Exit']='Init','Exit'#對應不同的行為轉換到不同的狀態returnresponses[action]defgame():#畫出當前棋盤狀態
game_field.draw(stdscr)#讀取用戶輸入得到action
action=get_user_action(stdscr)ifaction=='Restart':return'Init'ifaction=='Exit':return'Exit'ifgame_field.move(action):#movesuccessfulifgame_field.is_win():return'Win'ifgame_field.is_gameover():return'Gameover'return'Game'
state_actions={'Init':init,'Win':lambda:not_game('Win'),'Gameover':lambda:not_game('Gameover'),'Game':game
}
curses.use_default_colors()
game_field=GameField(win=32)
state='Init'#狀態機開始循環whilestate!='Exit':
state=state_actions[state]()
curses.wrapper(main)
熱點內容