awacke1's picture
Create app.py
fc4809e
import streamlit as st
import random
import string
# Function to generate a random grid
def generate_grid(size, words):
grid = [[' ' for _ in range(size)] for _ in range(size)]
for word in words:
placed = False
while not placed:
direction = random.choice(['horizontal', 'vertical'])
if direction == 'horizontal':
row = random.randint(0, size - 1)
start_col = random.randint(0, size - len(word))
for col in range(start_col, start_col + len(word)):
if grid[row][col] != ' ' and grid[row][col] != word[col - start_col]:
break
else:
for col in range(start_col, start_col + len(word)):
grid[row][col] = word[col - start_col]
placed = True
elif direction == 'vertical':
col = random.randint(0, size - 1)
start_row = random.randint(0, size - len(word))
for row in range(start_row, start_row + len(word)):
if grid[row][col] != ' ' and grid[row][col] != word[row - start_row]:
break
else:
for row in range(start_row, start_row + len(word)):
grid[row][col] = word[row - start_row]
placed = True
return grid
# Streamlit app
st.title("Word Search with Memory")
st.write("Welcome to the Word Search game with memory! Add a new word and the grid will update without losing previously placed words.")
# Session state to store the word list
if 'word_list' not in st.session_state:
st.session_state.word_list = []
new_word = st.text_input("Enter a new word (up to 10 characters):").upper()
if len(new_word) <= 10 and new_word.isalpha():
st.session_state.word_list.append(new_word)
if st.button("Clear words"):
st.session_state.word_list = []
# Grid size
size = st.sidebar.slider("Grid size", min_value=10, max_value=20, value=10, step=1)
# Generate grid and display it
grid = generate_grid(size, st.session_state.word_list)
for row in grid:
st.write(" ".join(row))
st.write("Words added:")
st.write(", ".join(st.session_state.word_list))