欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

2048小游戏

程序员文章站 2022-04-19 14:02:35
python实现2048小游戏介绍主要思路实验码片介绍本次是简简单单实现2048小游戏,没窗口化主要思路实验码片实验代码:import sys #导入需要的库import osimport randomimport itertoolsdef trim(seqs, direction = 0): return([0,0,0,0] + [n for n in seqs if n])[-4:] if direction else ([n for n in seqs if...

python实现2048小游戏

介绍

本次是简简单单实现2048小游戏,没窗口化

主要思路

2048小游戏

实验代码

import sys      #导入需要的库
import os
import random
import itertools

def trim(seqs, direction = 0):
    return([0,0,0,0] + [n for n in seqs if n])[-4:] if direction else ([n for n in seqs if n] + [0,0,0,0])[:4]

def sum_seqs(seqs,direction = 0):   #操作后相同数字相加
    if seqs[1] and seqs[2] and seqs[1] == seqs[2]:
        return trim([seqs[0],seqs[1]*2,0,seqs[3]],direction = direction)
    if seqs[0] and seqs[1] and seqs[0] == seqs[1]:
        seqs[0],seqs[1] = seqs[0]*2,0,
    if seqs[2] and seqs[3] and seqs[2] == seqs[3]:
        seqs[2],seqs[3] = seqs[2]*2,0
    return trim(seqs,direction = direction)

def up(grid):       #上
    for col in [0,1,2,3]:
        for _idx,n in enumerate(sum_seqs(trim([row[col] for row in grid]))):
                grid[_idx][col] = n
    return grid        
    
def down(grid):     #下
    for col in [0,1,2,3]:
        for _idx,n in enumerate(sum_seqs(trim([row[col] for row in grid],direction = 1),direction = 1)):
                grid[_idx][col] = n
    return grid 
    
def left(grid):     #左
    return [sum_seqs(trim(row)) for row in grid]
    
def right(grid):    #右
    return [sum_seqs(trim(row,direction = 1),direction = 1) for row in grid]
    

class A:
    grid = []   #定义游戏界面
    controls = ["w","a","s","d"]    #定义控制键
    
    def rnd_field(self):    #随机取两个数输出到游戏内
        number = random.choice([4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2,4,2])
        x,y = random.choice([(x,y) for x,y in itertools.product([0,1,2,3],[0,1,2,3]) if self.grid[x][y] == 0])
        self.grid[x][y] = number

    def print_screen(self):     #游戏界面设定
        os.system('clear')      #清空界面
        print('-' * 21)
        for row in self.grid:
            print('|{}|'.format("|".join([str(col or ' ').center(4) for col in row])))
            print('-' * 21)

    def logic(self,control):    #控制操作
        grid = {'w': up,'a': left,'s': down,'d':right}[control]([[c for c in r]for r in self.grid])     #字典定义操作
        if grid != self.grid:   #前后对比,有变化才输入新的随机值
            del self.grid[:]    #刷新界面
            self.grid.extend(grid)  #刷新后的界面去代替
            if [n for n in itertools.chain(*grid) if n >= 2048]:    #到2048成功游戏结束
                return 1, "你赢了!"
            self.rnd_field()
        else:       #上下左右能操作等于1游戏继续,不能操作不等于1游戏结束
            if not[1 for g in [f(grid) for f in [up,down,left,right]]if g != self.grid]:
                return -1, "你输了!"
        
        return 0,''
    
    def main_loop(self):       #游戏主事件
        #初始化游戏界面
        self.grid = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]   #初始化游戏界面
        self.rnd_field()
        self.rnd_field()
        
        while True:     #重复循环直到游戏结束
            self.print_screen()
            control = input('请选择操作: w/a/s/d:')
            if control in self.controls:
                status,info = self.logic(control)
                if status:
                    print(info)
                    if input('再来一局?[y/n]').lower() == "y":    #游戏结束后的选择
                        break
                    else:
                        sys.exit(0)     #退出游戏
        self.main_loop()    #再启动游戏
         
if  __name__ == "__main__":     #启动游戏
    A().main_loop()

实验结果

2048小游戏
2048小游戏

本文地址:https://blog.csdn.net/weixin_42758025/article/details/107185513