import pygame, sys, random
from pygame.locals import *
white = 255, 255, 255
blue = 0, 0, 200
num = 5
A = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
# 判断格子是否已满
def fill():
t = 0
for i in range(4):
for j in range(4):
if A[i][j] == 0:
t += 1
if t == 0:
return False
else:
return True
# 随机产生“2”
def random_2():
if fill():
while True:
x = random.randint(0, 3)
y = random.randint(0, 3)
if A[x][y] == 0:
A[x][y] = 2
return 0
# 格子移动
def move(n):
if n == "a":
for i in range(4):
for j in range(3, 0, -1):
if A[i][j - 1] == 0:
A[i][j - 1] = A[i][j]
A[i][j] = 0
elif A[i][j] == A[i][j - 1] != 0:
A[i][j - 1] = A[i][j] + A[i][j - 1]
A[i][j] = 0
break
if n == "w":
for i in range(3, 0, -1):
for j in range(4):
if A[i - 1][j] == 0:
A[i - 1][j] = A[i][j]
A[i][j] = 0
elif A[i][j] == A[i - 1][j] != 0:
A[i - 1][j] = A[i][j] + A[i - 1][j]
A[i][j] = 0
break
if n == "s":
for i in range(3):
for j in range(4):
if A[i + 1][j] == 0:
A[i + 1][j] = A[i][j]
A[i][j] = 0
if A[i][j] == A[i + 1][j] != 0:
A[i + 1][j] = A[i][j] + A[i + 1][j]
A[i][j] = 0
break
if n == "d":
for i in range(4):
for j in range(3):
if A[i][j + 1] == 0:
A[i][j + 1] = A[i][j]
A[i][j] = 0
if A[i][j] == A[i][j + 1] != 0:
A[i][j + 1] = A[i][j] + A[i][j + 1]
A[i][j] = 0
break
def To2048():
for i in range(4):
for j in range(4):
if A[i][j]==32:
return True
# 初始化
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Python+Pygame实现2048")
myfont = pygame.font.Font(None, 60)
screen.fill(blue)
# 走循环
while True:
for i in range(4):
for j in range(4):
text = myfont.render(str(A[i][j]), True, white)
screen.blit(text, (100 + 100 * j, 100 + 100 * i))
if To2048():
text_2 = text = myfont.render("You Win!", True, white)
screen.blit(text_2, (500, 400))
text_1=text = myfont.render("WASD to move", True, white)
screen.blit(text_1, (500, 200))
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
elif event.type == KEYUP:
if event.key == pygame.K_a:
move("a")
if event.key == pygame.K_w:
move("w")
if event.key == pygame.K_s:
move("s")
if event.key == pygame.K_d:
move("d")
random_2()
screen.fill(blue)
pygame.display.update()
为了简单,32=win。