Compare commits

..

2 Commits

Author SHA1 Message Date
c6e4e40e82 Add Game of life
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-11-16 21:52:41 +01:00
119d988a58 Add .gitignore
Signed-off-by: Manuel Vergara <manuel@vergaracarmona.es>
2023-11-16 21:52:21 +01:00
4 changed files with 256 additions and 0 deletions

104
.gitignore vendored Normal file
View File

@ -0,0 +1,104 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/

20
Game-of-Life/README.md Normal file
View File

@ -0,0 +1,20 @@
# Game-of-Life
Un simulador del Juego de la Vida de John Conway escrito en python usando la biblioteca pygame.
## Reglas
- Cada bloque puede estar encendido o apagado.
- Si un bloque está encendido y tiene dos o tres adyacentes que están encendidos, permanecerá encendido.
- Si un bloque está apagado y tiene tres adyacentes que están encendidos, se encenderá. De lo contrario, el bloque estará apagado. Sin embargo, cuando un bloque está en los márgenes, tiene menos adyacentes que otros bloques y eso significa que las reglas para ellos funcionarán de forma diferente a otros bloques.
## Instrucciones de uso
Puede activar un bloque desactivado haciendo clic sobre él y desactivar un bloque activado haciendo clic sobre él.
Pulsando el botón Volver el programa se pausará o reanudará.
Pulsando el botón derecho puede actualizar el tablero para un paso.
Pulsando el botón 's' puede guardar su trabajo.
Pulsando el botón 'l' puede cargar un trabajo guardado.
Pulsando el botón 'd' puede activar 'Arrastrar y dibujar'.

1
Game-of-Life/_config.yml Normal file
View File

@ -0,0 +1 @@
remote_theme: "dracula/gh-pages"

131
Game-of-Life/gameoflife.py Normal file
View File

@ -0,0 +1,131 @@
#!/usr/bin/env python3
#
# Game of life
#
# inspired by John conway
#
import pygame
import sys
import os
pygame.init()
dis = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Game of Life")
WINW, WINH = dis.get_size()
BOXW = 10
BOXH = 10
assert WINW % BOXW == 0 and WINH % BOXH == 0
BOARDW = WINW//BOXW
BOARDH = WINH//BOXH
fill_color = (255, 255, 255)
empty_color = (0, 0, 0)
def make_new_board(w, h):
return list([0]*w for i in range(h))
def check(board, x, y):
m = 0
for i in range(-1, 2):
for j in range(-1, 2):
if not(i == j == 0) and (0 <= i+y < BOARDH) and (0 <= j+x < BOARDW):
m += board[i+y][j+x]
if board[y][x]:
if m == 2 or m == 3:
return True
if not board[y][x]:
if m == 3:
return True
return False
def update(board):
nb = make_new_board(BOARDW, BOARDH)
for i in range(BOARDH):
for j in range(BOARDW):
nb[i][j] = check(board, j, i)
return nb
def draw(win, board):
for i in range(BOARDH):
for j in range(BOARDW):
if board[i][j]:
pygame.draw.rect(win, fill_color, (j*BOXW, i*BOXH, BOXW, BOXH))
else:
pygame.draw.rect(win, empty_color,
(j*BOXW, i*BOXH, BOXW, BOXH))
def recommend_name():
n = 0
a = os.listdir()
l = []
for f in a:
if f.startswith("gol") and f.endswith(".png"):
l.append(f)
t = True
while t:
n += 1
t = False
if "gol"+str(n)+".png" in l:
t = True
return "gol"+str(n)+".png"
def load(name):
nb = make_new_board(BOARDW, BOARDH)
s = pygame.image.load(name)
for i in range(BOARDH):
for j in range(BOARDW):
nb[i][j] = (s.get_at((j*BOXW+BOXW//2, i*BOXH+BOXH//2))
== fill_color)
return nb
board = make_new_board(BOARDW, BOARDH)
updating = False
drag = False
down = False
dragval = False
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif e.type == pygame.MOUSEBUTTONDOWN:
x, y = e.pos
x, y = x//BOXW, y//BOXH
down = True
dragval = not board[y][x]
if drag == False:
board[y][x] = not board[y][x]
elif e.type == pygame.MOUSEBUTTONUP:
down = False
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_RETURN:
updating = not updating
elif e.key == pygame.K_RIGHT:
board = update(board)
elif e.key == pygame.K_s:
pygame.image.save(dis, recommend_name())
elif e.key == pygame.K_l:
board = load(input())
elif e.key == pygame.K_d:
drag = not drag
if drag and down:
x, y = pygame.mouse.get_pos()
x, y = x//BOXW, y//BOXH
board[y][x] = dragval
if updating:
board = update(board)
draw(dis, board)
pygame.display.update()