Python编写2048游戏并显示分数
时间: 2024-02-03 14:03:21 浏览: 50
以下是Python编写的2048游戏和显示分数的示例代码:
```python
import random
# 初始化游戏面板
def init_board():
board = [[0 for i in range(4)] for j in range(4)]
return board
# 在随机位置生成2或4
def generate_num(board):
empty_pos = []
for i in range(4):
for j in range(4):
if board[i][j] == 0:
empty_pos.append((i, j))
if not empty_pos:
return False
x, y = random.choice(empty_pos)
board[x][y] = 2 if random.random() < 0.9 else 4
return True
# 合并相同数字
def merge(nums):
new_nums = [n for n in nums if n != 0]
for i in range(len(new_nums) - 1):
if new_nums[i] == new_nums[i+1]:
new_nums[i] *= 2
new_nums[i+1] = 0
new_nums = [n for n in new_nums if n != 0]
new_nums += [0] * (len(nums) - len(new_nums))
return new_nums
# 旋转矩阵
def rotate(board):
return [list(x)[::-1] for x in zip(*board)]
# 判断是否结束游戏
def is_gameover(board):
for i in range(4):
for j in range(4):
if board[i][j] == 0:
return False
if j < 3 and board[i][j] == board[i][j+1]:
return False
if i < 3 and board[i][j] == board[i+1][j]:
return False
return True
# 显示游戏面板和分数
def display(board, score):
print("Score: %s" % score)
for row in board:
print(row)
# 移动游戏面板
def move(board, direction):
if direction == "up":
board = rotate(board)
board = [merge(row) for row in board]
board = rotate(board)
board = rotate(board)
board = rotate(board)
elif direction == "down":
board = rotate(board)
board = rotate(board)
board = rotate(board)
board = [merge(row) for row in board]
board = rotate(board)
elif direction == "left":
board = [merge(row) for row in board]
elif direction == "right":
board = [row[::-1] for row in board]
board = [merge(row) for row in board]
board = [row[::-1] for row in board]
return board
# 游戏主函数
def main():
board = init_board()
score = 0
generate_num(board)
generate_num(board)
display(board, score)
while True:
direction = input("Please input direction(up/down/left/right): ")
board_new = move(board, direction)
if board_new == board:
continue
board = board_new
if not generate_num(board):
print("Game over!")
break
score += 2
display(board, score)
if is_gameover(board):
print("Game over!")
break
if __name__ == "__main__":
main()
```
这个游戏的分数是每次合并相同数字的总和,每次合并相同数字时,分数增加这两个数字的和。在游戏开始时,会随机生成两个数字2或4。玩家可以通过输入指令来移动数字,游戏的结束条件是游戏面板被填满了,没有可以合并的相同数字。
阅读全文