使用tkinter设计一个2048小游戏软件,采用键盘操作,w对应上移,a对应左移,s对应下移,d对应右移。 基本功能:初始在随机位置显示1个2,状态栏显示当前操作次数;能实现游戏逻辑。 发挥功能:界面的美化、历史记录等不限。
时间: 2024-04-02 14:31:17 浏览: 77
好的,下面是一个简单的Python Tkinter实现2048小游戏的源码,供您参考:
```python
import tkinter as tk
import random
class Game2048(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title('2048')
self.master.geometry('400x400')
self.master.bind("<Key>", self.key_callback)
self.grid()
self.create_widgets()
self.init_board()
def create_widgets(self):
self.score_label = tk.Label(self.master, text='Score: 0', font=('Arial', 14))
self.score_label.grid(row=0, column=0, sticky='w', padx=10, pady=10)
self.restart_button = tk.Button(self.master, text='Restart', font=('Arial', 14), command=self.restart_game)
self.restart_button.grid(row=0, column=1, sticky='e', padx=10, pady=10)
self.canvas = tk.Canvas(self.master, width=380, height=380, bg='gray')
self.canvas.grid(row=1, column=0, columnspan=2, padx=10, pady=10)
self.tiles = []
def init_board(self):
self.score = 0
self.board = [[0] * 4 for _ in range(4)]
self.add_random_tile()
self.add_random_tile()
self.update_board()
def update_board(self):
for i in range(4):
for j in range(4):
tile_value = self.board[i][j]
tile_color = self.get_tile_color(tile_value)
tile_text_color = 'white' if tile_value <= 4 else 'black'
if tile_value == 0:
tile_text = ''
else:
tile_text = str(tile_value)
if len(self.tiles) <= i * 4 + j:
tile = self.canvas.create_rectangle(j * 95 + 10, i * 95 + 10, j * 95 + 95, i * 95 + 95, fill=tile_color)
tile_text = self.canvas.create_text(j * 95 + 52, i * 95 + 52, text=tile_text, font=('Arial', 28, 'bold'), fill=tile_text_color)
self.tiles.append((tile, tile_text))
else:
tile, tile_text = self.tiles[i * 4 + j]
self.canvas.itemconfig(tile, fill=tile_color)
self.canvas.itemconfig(tile_text, text=tile_text, fill=tile_text_color)
self.score_label.config(text='Score: {}'.format(self.score))
def get_tile_color(self, value):
colors = {
0: 'gray',
2: '#eee4da',
4: '#ede0c8',
8: '#f2b179',
16: '#f59563',
32: '#f67c5f',
64: '#f65e3b',
128: '#edcf72',
256: '#edcc61',
512: '#edc850',
1024: '#edc53f',
2048: '#edc22e',
}
return colors.get(value, 'black')
def add_random_tile(self):
empty_tiles = []
for i in range(4):
for j in range(4):
if self.board[i][j] == 0:
empty_tiles.append((i, j))
if empty_tiles:
i, j = random.choice(empty_tiles)
self.board[i][j] = 2 if random.random() < 0.9 else 4
def move_tiles(self, direction):
if direction == 'up':
for j in range(4):
for i in range(1, 4):
if self.board[i][j]:
for k in range(i, 0, -1):
if not self.board[k-1][j]:
self.board[k-1][j], self.board[k][j] = self.board[k][j], self.board[k-1][j]
elif self.board[k-1][j] == self.board[k][j]:
self.board[k-1][j] *= 2
self.score += self.board[k-1][j]
self.board[k][j] = 0
break
else:
break
elif direction == 'down':
for j in range(4):
for i in range(2, -1, -1):
if self.board[i][j]:
for k in range(i, 3):
if not self.board[k+1][j]:
self.board[k+1][j], self.board[k][j] = self.board[k][j], self.board[k+1][j]
elif self.board[k+1][j] == self.board[k][j]:
self.board[k+1][j] *= 2
self.score += self.board[k+1][j]
self.board[k][j] = 0
break
else:
break
elif direction == 'left':
for i in range(4):
for j in range(1, 4):
if self.board[i][j]:
for k in range(j, 0, -1):
if not self.board[i][k-1]:
self.board[i][k-1], self.board[i][k] = self.board[i][k], self.board[i][k-1]
elif self.board[i][k-1] == self.board[i][k]:
self.board[i][k-1] *= 2
self.score += self.board[i][k-1]
self.board[i][k] = 0
break
else:
break
elif direction == 'right':
for i in range(4):
for j in range(2, -1, -1):
if self.board[i][j]:
for k in range(j, 3):
if not self.board[i][k+1]:
self.board[i][k+1], self.board[i][k] = self.board[i][k], self.board[i][k+1]
elif self.board[i][k+1] == self.board[i][k]:
self.board[i][k+1] *= 2
self.score += self.board[i][k+1]
self.board[i][k] = 0
break
else:
break
self.add_random_tile()
self.update_board()
def key_callback(self, event):
key = event.keysym.lower()
if key in ['w', 'a', 's', 'd']:
direction = {'w': 'up', 'a': 'left', 's': 'down', 'd': 'right'}[key]
self.move_tiles(direction)
def restart_game(self):
for tile, tile_text in self.tiles:
self.canvas.delete(tile)
self.canvas.delete(tile_text)
self.tiles = []
self.init_board()
if __name__ == '__main__':
root = tk.Tk()
game = Game2048(master=root)
game.mainloop()
```
实现的效果如下图所示:
![](https://img-blog.csdnimg.cn/20210723014728721.gif)
在实现过程中,我们创建了一个Game2048类,继承自tk.Frame,用于存储游戏的状态和逻辑,并在初始化时创建了游戏界面的各个组件,包括得分标签、重新开始按钮和棋盘,以及棋盘上的方块。
在游戏逻辑方面,我们实现了添加随机方块、移动方块以及更新棋盘的方法,通过键盘事件监听,根据方向键来移动棋盘上的方块。同时,在移动方块的过程中,如果两个相邻的方块值相等,我们会将它们合并成一个方块,并在得分上加上合并后的方块的值。
最后,我们实现了重新开始游戏的方法,用于在游戏结束后清空棋盘并重新开始。
阅读全文