分别用python和go语言来实现的风靡一时的2048 游戏,包含完整代码
由于篇幅所限,这里仅提供2048游戏的核心函数实现,并不包括完整的UI和输入处理。
Python版本的2048游戏实现:
import random
import sys
def print_board(board):
for row in board:
print(' '.join(map(str, row)))
print()
def add_two(board):
(i, j) = random.choice([(i, j) for i in range(4) for j in range(4) if board[i][j] == 0])
board[i][j] = 2
def move(board, direction):
def move_row(row):
row = [i for i in row if i != 0]
while len(row) < 4:
row.append(0)
if direction == 'left':
row = [0] * (4 - len(row)) + row
else:
row = row + [0] * (4 - len(row))
return row
if direction == 'up':
board = [[move_row(row) for row in zip(*board)][i] for i in range(4)]
elif direction == 'down':
board = [[move_row(row) for row in zip(*board)][i] for i in range(3, -1, -1)]
else:
board = [move_row(col) for col in board]
for i in range(4):
for j in range(4):
if board[i][j] == board[i][j + 1] and board[i][j] != 0:
board[i][j] *= 2
board[i][j + 1] = 0
elif board[i][j] == 0 and board[i][j + 1] != 0:
board[i][j] = board[i][j + 1]
board[i][j + 1] = 0
return board
def game_over(board):
for i in range(4):
for j in range(4):
if board[i][j] == 2048:
return True
return any(move(board, direction) == board for direction in ['left', 'right', 'up', 'down'])
def play_game():
board = [[0 for _ in range(4)] for _ in range(4)]
add_two(board)
add_two(board)
print_board(board)
while not game_over(board):
direction = input("Enter 'w', 's', 'a', or 'd' to move: ")
if direction not in ['w', 's', 'a', 'd']:
print("Invalid input. Please enter 'w', 's', 'a', or 'd'.")
continue
if direction in ['w', 's']:
board = move(board, 'up' if direction == 'w' else 'down')
else:
board = move(board, 'left' if direction == 'a' else 'right')
print_board(board)
if game_over(board):
print("Game over!")
sys.exit()
play_game()
Go版本的2048游戏实现:
package main
import (
"fmt"
"math/rand"
"os"
"time"
)
func printBoard(board [][]int) {
for _, row := range board {
fmt.Printf("%d ", row)
fmt.Println()
}
fmt.Print
评论已关闭