python之用Numpy和matplotlib画一个魔方
魔方是一种极受欢迎的玩具,它在全世界范围内都有很多玩家,因为挑战简单而又极具挑战性,它的颜色构成很有美感。本文将会介绍用Python中的Numpy和matplotlib库来画一下魔方的过程。
第一步:代码编写
首先,我们需要安装好依赖库numpy和matplotlib。然后,我们来看看如何编写代码。
首先,我们要定义一个3x3x3的numpy数组(由于魔方是三维的),将其填充成六个不同的面。可以将每面的颜色定义为一个数字,例如:
import numpy as np
# define a 3x3x3 numpy array
cube = np.zeros((3,3,3))
cube[...,0] = 1 # red
cube[...,1] = 2 # green
cube[...,2] = 3 # blue
cube[...,3] = 4 # orange
cube[...,4] = 5 # yellow
cube[...,5] = 6 # white
接下来,我们需要定义一些函数来旋转魔方。这里我们定义的是以x轴顺时针、逆时针旋转,以y轴顺时针、逆时针旋转,以及z轴顺时针、逆时针旋转三个函数。具体实现方法可以参考以下代码:
def rotate_x_clockwise(cube):
"""Rotate the cube along the x-axis clockwise"""
new_cube = np.zeros_like(cube)
new_cube[0,:,:] = cube[0,:,:].T
new_cube[1,:,:] = cube[2,:,:]
new_cube[2,:,:] = cube[1,:,:].T
return new_cube
def rotate_x_anticlockwise(cube):
"""Rotate the cube along the x-axis anticlockwise"""
new_cube = np.zeros_like(cube)
new_cube[0,:,:] = cube[0,:,:].T[::-1]
new_cube[1,:,:] = cube[2,:,:][::-1]
new_cube[2,:,:] = cube[1,:,:].T[::-1]
return new_cube
def rotate_y_clockwise(cube):
"""Rotate the cube along the y-axis clockwise"""
new_cube = np.zeros_like(cube)
new_cube[:,2,:] = cube[:,:,0]
new_cube[:,1,:] = cube[:,:,2]
new_cube[:,0,:] = cube[:,:,1]
return new_cube
def rotate_y_anticlockwise(cube):
"""Rotate the cube along the y-axis anticlockwise"""
new_cube = np.zeros_like(cube)
new_cube[:,0,:] = cube[:,:,2][::-1]
new_cube[:,1,:] = cube[:,:,0][::-1]
new_cube[:,2,:] = cube[:,:,1][::-1]
return new_cube
def rotate_z_clockwise(cube):
"""Rotate the cube along the z-axis clockwise"""
new_cube = np.zeros_like(cube)
new_cube[:,:,2] = cube[:,0,:].T[::-1]
new_cube[:,:,1] = cube[:,::-1,2]
new_cube[:,:,0] = cube[:,2,:].T
return new_cube
def rotate_z_anticlockwise(cube):
"""Rotate the cube along the z-axis anticlockwise"""
new_cube = np.zeros_like(cube)
new_cube[:,:,0] = cube[:,0,:][::-1]
new_cube[:,:,1] = cube[:,::-1,0]
new_cube[:,:,2] = cube[:,2,:][::-1]
return new_cube
接下来我们就可以画魔方啦!由于是三维的,所以我们需要切分出每个面,然后用matplotlib中的imshow来展示每个面。可以参照以下代码来实现:
import matplotlib.pyplot as plt
fig = plt.figure()
cube1 = cube[0,:,:]
plt.imshow(cube1)
cube2 = cube[1,:,:]
plt.imshow(cube2)
cube3 = cube[2,:,:]
plt.imshow(cube3)
cube4 = np.rot90(cube[3,:,:], -1)
plt.imshow(cube4)
cube5 = np.rot90(cube[4,:,:], 1)
plt.imshow(cube5)
cube6 = np.rot90(cube[5,:,:], -1)
plt.imshow(cube6)
plt.axis('off')
plt.show()
第二步:效果展示
最后,我们来看看实际效果如何:
[效果图](https://www.jianshu.com/p/fa53aafaa2de)
摘自[简书](https://www.jianshu.com/p/fa53aafaa2de)