用Django写一个幻方
时间: 2023-05-31 16:05:04 浏览: 75
幻方是一个由数字组成的矩阵,其中每一行、每一列和对角线上的数字之和相等。下面是一个3阶幻方的例子:
8 1 6
3 5 7
4 9 2
我们可以用Django框架来实现一个幻方生成器。下面是代码实现:
1. 创建一个Django项目和app
$ django-admin startproject magic_square
$ cd magic_square
$ python manage.py startapp generator
2. 在generator/views.py中编写代码
from django.shortcuts import render
import numpy as np
def magic_square(request):
if request.method == 'POST':
n = int(request.POST.get('size'))
if n % 2 == 0:
return render(request, 'generator/error.html')
else:
magic = np.zeros((n,n), dtype=int)
i, j = 0, n//2
for num in range(1, n**2+1):
magic[i, j] = num
next_i, next_j = (i-1)%n, (j+1)%n
if magic[next_i, next_j]:
i += 1
else:
i, j = next_i, next_j
return render(request, 'generator/magic_square.html', {'magic': magic})
return render(request, 'generator/index.html')
3. 在generator/templates/generator目录下创建index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Magic Square Generator</title>
</head>
<body>
<h1>Magic Square Generator</h1>
<form method="post">
{% csrf_token %}
<label for="size">Enter the size of magic square (odd number):</label>
<input type="number" id="size" name="size" min="3" required>
<br><br>
<button type="submit">Generate</button>
</form>
</body>
</html>
4. 在generator/templates/generator目录下创建magic_square.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Magic Square</title>
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
width: 50px;
height: 50px;
text-align: center;
vertical-align: middle;
}
</style>
</head>
<body>
<h1>Magic Square</h1>
<table>
{% for row in magic %}
<tr>
{% for num in row %}
<td>{{ num }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>
5. 在generator/templates/generator目录下创建error.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<h1>Error</h1>
<p>The size of magic square must be an odd number.</p>
<a href="{% url 'magic_square' %}">Back to generator</a>
</body>
</html>
6. 在generator/urls.py中编写代码
from django.urls import path
from . import views
urlpatterns = [
path('', views.magic_square, name='magic_square'),
]
7. 在magic_square/urls.py中添加generator的urls
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('', include('generator.urls')),
path('admin/', admin.site.urls),
]
8. 运行Django项目
$ python manage.py runserver
访问http://localhost:8000/即可看到幻方生成器的页面。输入一个奇数大小后,点击Generate按钮,即可生成一个幻方。
阅读全文