python做表白小游戏_屌丝的寂寞你不懂——2048小游戏python实现版

最近这款小游戏非常火,想想算法也挺简单,忍不住用python实现了一个,目前还很简陋,代码也很丑陋,初版以实现功能为主,以后慢慢优化,争取写的好看点。

暂时只有终端界面,以后考虑用一种GUI美化(wxpython,qt,kivy...还没选好),或者flask,django的web框架,都简单

目前终端只支持按键回车操作,以后考虑直接终端捕获按键,无需按回车确认。

另外,规则也不完善,比如每次新插入的数字只有2,没有加入随机数4,以后加上。

没有用堆栈存储矩阵,只是用变量存储了一次,所以只能撤销一部,无法一直撤销,以后也容易改。

项目托管在github: https://github.com/abcfy2/python-2048

2014-04-27晚更新:使用堆栈存储每次移动的结果,可以一直撤销到初始状态了

2014-04-08更新:改用wsad来移动矩阵

1.[代码][Python]代码

#!/usr/bin/env python

# encoding: utf-8

"""

The minigame 2048 in python

"""

import random

def init():

"""

initialize a 2048 matrix. return a matrix list

"""

matrix = [ 0 for i in range(16) ]

random_lst = random.sample( range(16), 2 ) # generate 2 different number

matrix[random_lst[0]] = matrix[random_lst[1]] = 2

return matrix

def move(matrix,direction):

"""

moving the matrix. return a matrix list

"""

mergedList = [] #initial the merged index

if direction == 'u':

for i in range(16):

j = i

while j - 4 >= 0:

if matrix[j-4] == 0:

matrix[j-4] = matrix[j]

matrix[j] = 0

elif matrix[j-4] == matrix[j] and j - 4 not in mergedList and j not in mergedList:

matrix[j-4] *=2

matrix[j] = 0

mergedList.append(j-4)

mergedList.append(j) #prevent the number to be merged twice

j -= 4

elif direction == 'd':

for i in range(15,-1,-1):

j = i

while j + 4 < 16:

if matrix[j+4] == 0:

matrix[j+4] = matrix[j]

matrix[j] = 0

elif matrix[j+4] == matrix[j] and j + 4 not in mergedList and j not in mergedList:

matrix[j+4] *=2

matrix[j] = 0

mergedList.append(j)

mergedList.append(j+4)

j += 4

elif direction == 'l':

for i in range(16):

j = i

while j % 4 != 0:

if matrix[j-1] == 0:

matrix[j-1] = matrix[j]

matrix[j] = 0

elif matrix[j-1] == matrix[j] and j - 1 not in mergedList and j not in mergedList:

matrix[j-1] *=2

matrix[j] = 0

mergedList.append(j-1)

mergedList.append(j)

j -= 1

else:

for i in range(15,-1,-1):

j = i

while j % 4 != 3:

if matrix[j+1] == 0:

matrix[j+1] = matrix[j]

matrix[j] = 0

elif matrix[j+1] == matrix[j] and j + 1 not in mergedList and j not in mergedList:

matrix[j+1] *=2

matrix[j] = 0

mergedList.append(j)

mergedList.append(j+1)

j += 1

return matrix

def insert(matrix):

"""insert one 2 or 4 into the matrix. return the matrix list

"""

getZeroIndex = []

for i in range(16):

if matrix[i] == 0:

getZeroIndex.append(i)

randomZeroIndex = random.choice(getZeroIndex)

matrix[randomZeroIndex] = 2

return matrix

def output(matrix):

"""

print the matrix. return the matrix list

"""

max_num_width = len(str(max(matrix)))

demarcation = ( '+' + '-'*(max_num_width+2) ) * 4 + '+' #generate demarcation line like '+---+---+---+'

print demarcation

for i in range(len(matrix)):

if matrix[i] == 0:

printchar = ' '

else:

printchar = str(matrix[i])

print '|',

print '{0:>{1}}'.format(printchar,max_num_width),

if (i + 1) % 4 == 0:

print '|'

print demarcation

print

def isOver(matrix):

"""is game over? return bool

"""

if 0 in matrix:

return False

else:

for i in range(16):

if i % 4 != 3:

if matrix[i] == matrix[i+1]:

return False

if i < 12:

if matrix[i] == matrix [i+4]:

return False

return True

def play():

matrix = init()

matrix_stack = [] # just used by back function

matrix_stack.append(list(matrix))

step = len(matrix_stack) - 1

while True:

output(matrix)

if isOver(matrix) == False:

if max(matrix) == 2048:

input = raw_input('The max number is 2048, win the goal! q for quit, others for continue. ')

if input == 'q':

exit()

while True:

input = raw_input("Step {0:2d} Choose which direction? u(p)/d(own)/l(eft)/r(ight), q for quit, b for back: ".format(step))

if input in [ 'u', 'd', 'l', 'r' ]:

matrix = move(matrix,input)

if matrix == matrix_stack[-1]:

print 'Not chaged. Try another direction.'

else:

insert(matrix)

matrix_stack.append(list(matrix))

break

elif input == 'b':

if len(matrix_stack) == 1:

print 'Cannot back anymore...'

continue

matrix_stack.pop()

matrix = list(matrix_stack[-1])

break

elif input == 'q':

print 'Byebye!'

exit()

else:

print 'Input error! Try again.'

else:

print 'Cannot move anyway. Game Over...'

exit()

step = len(matrix_stack) - 1

if __name__ == '__main__':

play()

2.[图片] short.jpg

25192049_i1Ul.jpg

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,2048小游戏可以使用Python的Pygame库来实现游戏界面和交互。下面是一个简单的实现过程: 1. 安装Pygame库 使用pip命令安装Pygame库: ``` pip install pygame ``` 2. 创建游戏窗口 使用Pygame库中的`pygame.display.set_mode()`函数创建游戏窗口。 ```python import pygame # 初始化Pygame pygame.init() # 设置游戏窗口大小 screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) # 设置游戏标题 pygame.display.set_caption('2048 Game') ``` 3. 显示游戏界面 使用Pygame库中的`pygame.draw.rect()`函数和`pygame.font.Font()`函数来绘制游戏界面和文字。 ```python # 绘制游戏背景 background_color = (187, 173, 160) screen.fill(background_color) # 绘制游戏界面 game_background_color = (205, 193, 180) game_padding = 10 game_width = screen_width - game_padding * 2 game_height = screen_height - game_padding * 2 pygame.draw.rect(screen, game_background_color, (game_padding, game_padding, game_width, game_height)) # 绘制游戏标题 font = pygame.font.Font(None, 36) text_color = (119, 110, 101) text = font.render('2048 Game', True, text_color) text_rect = text.get_rect() text_rect.center = (screen_width // 2, game_padding // 2) screen.blit(text, text_rect) # 更新屏幕显示 pygame.display.update() ``` 4. 处理用户输入 使用Pygame库中的`pygame.event.get()`函数获取用户输入。 ```python # 处理用户输入 for event in pygame.event.get(): if event.type == pygame.QUIT: # 用户关闭窗口 pygame.quit() exit() elif event.type == pygame.KEYDOWN: # 用户按下键盘 if event.key == pygame.K_ESCAPE: # 用户按下ESC键 pygame.quit() exit() ``` 5. 更新游戏状态并绘制游戏界面 根据用户输入更新游戏状态,并重新绘制游戏界面。 ```python # 更新游戏状态 # ... # 绘制游戏界面 # ... # 更新屏幕显示 pygame.display.update() ``` 以上是一个简单的2048游戏的实现过程,具体的游戏逻辑和实现细节还需要根据实际需求进行调整和完善。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值