Nyt pyytäisin apua joltain python taitajalta kun opiskelen tekemään apuohjelmia virtuaalisen Simpu Gui Os sisään. En ymmärrä miten saan toimimaan piirto ohjelmassa painikkeet ympyrän piirto ja neliön piirto siten, että valitsen hiiren vasemmalla piirtoalueelle miten se piirtää sen? Ja mie sweeper peli käynnistyy valikon kautta kun painan painiketta. Sain aikaisemmin toimimaan mutta en tyhmänä tallentanut koodia kun yritin saada toimintoa kun painaa tyhjää kohtaa niin sinne ilmaantuu numeroin kuinka monta tyhjää on miinan vieressä?
Tässä oli yksinkertaisen miinaharavan koodin pätkä tällä millä pystyi hiirellä painelemaan ja tyhjästä ei tapahtu mitään, mutta peli alkoi uudelleen miinaan osuessaan.
Tarvitsen viisaamman apua miten pitää muuttaa koodia ja mitä tapahtui, että nämä pari ohjelmaa lakkasi toimimasta? Olen kiitollinen avusta olen vasta alkuvaiheessa opiskelen itsenäisesti omaksi iloksi ja kokeilen kaikkea.
class Minesweeper:
def __init__(self, root):
self.root = root
self.root.title("Minesweeper")
self.create_board()
def create_board(self):
self.board_size = 8
self.mine_count = 10
self.buttons = {}
self.mines = set(random.sample(range(self.board_size ** 2), self.mine_count))
for row in range(self.board_size):
for col in range(self.board_size):
btn = tk.Button(self.root, width=3, height=1, command=lambda r=row, c=col: self.reveal_cell(r, c))
btn.grid(row=row, column=col)
self.buttons[(row, col)] = btn
def reveal_cell(self, row, col):
idx = row * self.board_size + col
if idx in self.mines:
self.buttons[(row, col)].config(text="*")
messagebox.showinfo("Game Over", "You hit a mine!")
self.reset_game()
else:
self.buttons[(row, col)].config(text="0", state=tk.DISABLED)
Tähän alas nyt laitan sen uusimman koodin missä kaikki muut ohjelmat toimivat, mutta ei piirto ohjelma ja minesweeper peli?
Koodi :
import tkinter as tk
from tkinter import simpledialog, colorchooser, messagebox, filedialog
import os
import random
class SimpleGUIOS:
def __init__(self, root):
self.root = root
self.root.title("Simple GUI OS")
self.create_widgets()
def create_widgets(self):
# Create a frame for the menu
self.menu_frame = tk.Frame(self.root)
self.menu_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)
# Add buttons for various applications to the menu frame
tk.Button(self.menu_frame, text='File Manager', command=self.open_file_manager).pack(pady=5)
tk.Button(self.menu_frame, text='Calculator', command=self.open_calculator).pack(pady=5)
tk.Button(self.menu_frame, text='Drawing App', command=self.open_drawing_app).pack(pady=5)
tk.Button(self.menu_frame, text='Minesweeper Game', command=self.open_minesweeper).pack(pady=5)
tk.Button(self.menu_frame, text='Text Editor', command=self.open_text_editor).pack(pady=5)
tk.Button(self.menu_frame, text='Solitaire', command=self.open_solitaire).pack(pady=5)
tk.Button(self.menu_frame, text='Exit', command=self.close_app).pack(pady=5)
# Label for welcome message
self.label = tk.Label(self.root, text="Welcome to Simple GUI OS")
self.label.pack(pady=10)
def open_file_manager(self):
file_manager_window = tk.Toplevel(self.root)
FileManager(file_manager_window)
def open_calculator(self):
calculator_window = tk.Toplevel(self.root)
Calculator(calculator_window)
def open_drawing_app(self):
drawing_window = tk.Toplevel(self.root)
DrawingApp(drawing_window)
def open_minesweeper(self):
minesweeper_window = tk.Toplevel(self.root)
Minesweeper(minesweeper_window)
def open_text_editor(self):
text_editor_window = tk.Toplevel(self.root)
TextEditor(text_editor_window)
def open_solitaire(self):
solitaire_window = tk.Toplevel(self.root)
Solitaire(solitaire_window)
def close_app(self):
self.root.quit()
class FileManager:
def __init__(self, root):
self.root = root
self.root.title("File Manager")
self.label = tk.Label(root, text="Select a folder:")
self.label.pack(pady=5)
self.folder_path = tk.Entry(root, width=50)
self.folder_path.pack(pady=5)
browse_btn = tk.Button(root, text="Browse", command=self.browse_folder)
browse_btn.pack(pady=5)
self.files_listbox = tk.Listbox(root, width=50, height=20)
self.files_listbox.pack(pady=10)
def browse_folder(self):
folder = filedialog.askdirectory()
if folder:
self.folder_path.delete(0, tk.END)
self.folder_path.insert(0, folder)
self.list_files(folder)
def list_files(self, folder):
self.files_listbox.delete(0, tk.END)
for file in os.listdir(folder):
self.files_listbox.insert(tk.END, file)
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Calculator")
self.create_widgets()
def create_widgets(self):
self.entry = tk.Entry(self.root, width=16, font=('Arial', 24), borderwidth=5)
self.entry.pack(pady=10)
button_frame = tk.Frame(self.root)
button_frame.pack()
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row = 0
col = 0
for button in buttons:
action = lambda x=button: self.on_button_click(x)
tk.Button(button_frame, text=button, width=5, height=2, command=action).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
def on_button_click(self, value):
if value == '=':
try:
result = str(eval(self.entry.get()))
self.entry.delete(0, tk.END)
self.entry.insert(0, result)
except Exception as e:
self.entry.delete(0, tk.END)
self.entry.insert(0, "Error")
else:
self.entry.insert(tk.END, value)
class DrawingApp:
def __init__(self, root):
self.root = root
self.root.title("Drawing App")
self.color = "black"
self.current_tool = "free_draw"
self.start_x = None
self.start_y = None
self.temp_shape = None
self.create_canvas()
def create_canvas(self):
self.canvas = tk.Canvas(self.root, bg="white", width=600, height=400)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<B1-Motion>", self.paint)
self.canvas.bind("<Button-1>", self.start_draw)
self.canvas.bind("<ButtonRelease-1>", self.end_draw)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=5)
free_draw_btn = tk.Button(button_frame, text="Free Draw", command=lambda: self.select_tool("free_draw"))
free_draw_btn.pack(side=tk.LEFT, padx=5)
circle_btn = tk.Button(button_frame, text="Draw Circle", command=lambda: self.select_tool("circle"))
circle_btn.pack(side=tk.LEFT, padx=5)
square_btn = tk.Button(button_frame, text="Draw Square", command=lambda: self.select_tool("square"))
square_btn.pack(side=tk.LEFT, padx=5)
color_btn = tk.Button(button_frame, text="Select Color", command=self.select_color)
color_btn.pack(side=tk.LEFT, padx=5)
clear_btn = tk.Button(button_frame, text="Clear", command=self.clear_canvas)
clear_btn.pack(side=tk.LEFT, padx=5)
def select_tool(self, tool):
self.current_tool = tool
def select_color(self):
self.color = colorchooser.askcolor(color=self.color)[1]
def start_draw(self, event):
self.start_x, self.start_y = event.x, event.y
if self.current_tool in ["circle", "square"]:
self.temp_shape = None
def end_draw(self, event):
if self.current_tool == "circle":
if self.temp_shape:
self.canvas.delete(self.temp_shape)
self.canvas.create_oval(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
elif self.current_tool == "square":
if self.temp_shape:
self.canvas.delete(self.temp_shape)
self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
self.temp_shape = None
def paint(self, event):
if self.current_tool == "free_draw":
x, y = event.x, event.y
self.canvas.create_line(x, y, x + 1, y + 1, fill=self.color, width=2)
elif self.current_tool in ["circle", "square"]:
if self.temp_shape:
self.canvas.delete(self.temp_shape)
if self.current_tool == "circle":
self.temp_shape = self.canvas.create_oval(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
elif self.current_tool == "square":
self.temp_shape = self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
def clear_canvas(self):
self.canvas.delete("all")
class Minesweeper:
def __init__(self, root):
self.root = root
self.root.title("Minesweeper")
self.create_board()
def create_board(self):
self.board_size = 8
self.mine_count = 10
self.buttons = {}
self.mines = set(random.sample(range(self.board_size ** 2), self.mine_count))
self.adjacent_counts = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)]
for mine in self.mines:
row, col = divmod(mine, self.board_size)
for r in range(max(0, row - 1), min(self.board_size, row + 2)):
for c in range(max(0, col - 1), min(self.board_size, col + 2)):
self.adjacent_counts[r][c] += 1
for row in range(self.board_size):
for col in range(self.board_size):
btn = tk.Button(self.root, width=3, height=1)
btn.grid(row=row, column=col)
btn.bind("<Button-1>", lambda e, r=row, c=col: self.reveal_cell(r, c))
btn.bind("<Button-3>", lambda e, r=row, c=col: self.mark_mine(r, c))
self.buttons[(row, col)] = btn
def reveal_cell(self, row, col):
idx = row * self.board_size + col
if idx in self.mines:
self.buttons[(row, col)].config(text="*", bg="red")
messagebox.showinfo("Game Over", "You hit a mine!")
self.reset_game()
else:
count = self.adj
class TextEditor:
def __init__(self, root):
self.root = root
self.root.title("Text Editor")
self.create_widgets()
def create_widgets(self):
self.text = tk.Text(self.root, wrap='word')
self.text.pack(expand=True, fill='both')
toolbar = tk.Frame(self.root)
toolbar.pack(side=tk.TOP, fill=tk.X)
bold_button = tk.Button(toolbar, text="Bold", command=self.toggle_bold)
bold_button.pack(side=tk.LEFT)
italic_button = tk.Button(toolbar, text="Italic", command=self.toggle_italic)
italic_button.pack(side=tk.LEFT)
size_button = tk.Button(toolbar, text="Change Font Size", command=self.change_font_size)
size_button.pack(side=tk.LEFT)
def toggle_bold(self):
current_tags = self.text.tag_names("sel.first")
if "bold" in current_tags:
self.text.tag_remove("bold", "sel.first", "sel.last")
else:
self.text.tag_add("bold", "sel.first", "sel.last")
self.text.tag_configure("bold", font=("Arial", 12, "bold"))
def toggle_italic(self):
current_tags = self.text.tag_names("sel.first")
if "italic" in current_tags:
self.text.tag_remove("italic", "sel.first", "sel.last")
else:
self.text.tag_add("italic", "sel.first", "sel.last")
self.text.tag_configure("italic", font=("Arial", 12, "italic"))
def change_font_size(self):
size = simpledialog.askinteger("Font Size", "Enter font size:", minvalue=1, maxvalue=100)
if size:
self.text.tag_configure("font_size", font=("Arial", size))
self.text.tag_add("font_size", "sel.first", "sel.last")
class Solitaire:
def __init__(self, root):
self.root = root
self.root.title("Solitaire")
self.setup_game()
def setup_game(self):
self.create_widgets()
self.initialize_deck()
self.deal_cards()
def create_widgets(self):
self.canvas = tk.Canvas(self.root, width=800, height=600, bg="green")
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<Button-1>", self.on_click)
def initialize_deck(self):
suits = ['♠', '♥', '♦', '♣']
self.deck = [f"{value} {suit}" for suit in suits for value in range(1, 14)]
random.shuffle(self.deck)
self.columns = [[] for _ in range(7)]
self.stock = []
self.waste = []
self.foundation = {suit: [] for suit in suits}
def deal_cards(self):
for i in range(7):
for j in range(i + 1):
card = self.deck.pop()
self.columns.append(card)
self.stock = self.deck
self.draw_tableau()
def draw_tableau(self):
self.canvas.delete("all")
x_offset = 50
y_offset = 50
for i, column in enumerate(self.columns):
x = x_offset + i * 100
for j, card in enumerate(column):
y = y_offset + j * 30
text = card if j == len(column) - 1 else "X"
self.canvas.create_rectangle(x, y, x + 70, y + 100, fill="white" if j == len(column) - 1 else "gray")
self.canvas.create_text(x + 35, y + 50, text=text, font=("Arial", 12))
self.canvas.create_rectangle(50, 400, 120, 470, fill="blue")
self.canvas.create_text(85, 435, text="Stock", font=("Arial", 12))
if self.waste:
self.canvas.create_rectangle(150, 400, 220, 470, fill="white")
self.canvas.create_text(185, 435, text=self.waste[-1], font=("Arial", 12))
def on_click(self, event):
x, y = event.x, event.y
if 50 <= x <= 120 and 400 <= y <= 470:
self.draw_from_stock()
return
column_clicked = (x - 50) // 100
if 0 <= column_clicked < len(self.columns):
self.handle_tableau_click(column_clicked)
def draw_from_stock(self):
if self.stock:
card = self.stock.pop()
self.waste.append(card)
else:
self.stock = self.waste[::-1]
self.waste = []
self.draw_tableau()
def handle_tableau_click(self, column_index):
column = self.columns[column_index]
if not column:
return
card = column.pop()
for other_column in self.columns:
if other_column and other_column[-1].split()[1] != card.split()[1]:
other_column.append(card)
break
self.draw_tableau()
if __name__ == "__main__":
root = tk.Tk()
app = SimpleGUIOS(root)
root.mainloop()
Tässä oli yksinkertaisen miinaharavan koodin pätkä tällä millä pystyi hiirellä painelemaan ja tyhjästä ei tapahtu mitään, mutta peli alkoi uudelleen miinaan osuessaan.
Tarvitsen viisaamman apua miten pitää muuttaa koodia ja mitä tapahtui, että nämä pari ohjelmaa lakkasi toimimasta? Olen kiitollinen avusta olen vasta alkuvaiheessa opiskelen itsenäisesti omaksi iloksi ja kokeilen kaikkea.
class Minesweeper:
def __init__(self, root):
self.root = root
self.root.title("Minesweeper")
self.create_board()
def create_board(self):
self.board_size = 8
self.mine_count = 10
self.buttons = {}
self.mines = set(random.sample(range(self.board_size ** 2), self.mine_count))
for row in range(self.board_size):
for col in range(self.board_size):
btn = tk.Button(self.root, width=3, height=1, command=lambda r=row, c=col: self.reveal_cell(r, c))
btn.grid(row=row, column=col)
self.buttons[(row, col)] = btn
def reveal_cell(self, row, col):
idx = row * self.board_size + col
if idx in self.mines:
self.buttons[(row, col)].config(text="*")
messagebox.showinfo("Game Over", "You hit a mine!")
self.reset_game()
else:
self.buttons[(row, col)].config(text="0", state=tk.DISABLED)
Tähän alas nyt laitan sen uusimman koodin missä kaikki muut ohjelmat toimivat, mutta ei piirto ohjelma ja minesweeper peli?
Koodi :
import tkinter as tk
from tkinter import simpledialog, colorchooser, messagebox, filedialog
import os
import random
class SimpleGUIOS:
def __init__(self, root):
self.root = root
self.root.title("Simple GUI OS")
self.create_widgets()
def create_widgets(self):
# Create a frame for the menu
self.menu_frame = tk.Frame(self.root)
self.menu_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)
# Add buttons for various applications to the menu frame
tk.Button(self.menu_frame, text='File Manager', command=self.open_file_manager).pack(pady=5)
tk.Button(self.menu_frame, text='Calculator', command=self.open_calculator).pack(pady=5)
tk.Button(self.menu_frame, text='Drawing App', command=self.open_drawing_app).pack(pady=5)
tk.Button(self.menu_frame, text='Minesweeper Game', command=self.open_minesweeper).pack(pady=5)
tk.Button(self.menu_frame, text='Text Editor', command=self.open_text_editor).pack(pady=5)
tk.Button(self.menu_frame, text='Solitaire', command=self.open_solitaire).pack(pady=5)
tk.Button(self.menu_frame, text='Exit', command=self.close_app).pack(pady=5)
# Label for welcome message
self.label = tk.Label(self.root, text="Welcome to Simple GUI OS")
self.label.pack(pady=10)
def open_file_manager(self):
file_manager_window = tk.Toplevel(self.root)
FileManager(file_manager_window)
def open_calculator(self):
calculator_window = tk.Toplevel(self.root)
Calculator(calculator_window)
def open_drawing_app(self):
drawing_window = tk.Toplevel(self.root)
DrawingApp(drawing_window)
def open_minesweeper(self):
minesweeper_window = tk.Toplevel(self.root)
Minesweeper(minesweeper_window)
def open_text_editor(self):
text_editor_window = tk.Toplevel(self.root)
TextEditor(text_editor_window)
def open_solitaire(self):
solitaire_window = tk.Toplevel(self.root)
Solitaire(solitaire_window)
def close_app(self):
self.root.quit()
class FileManager:
def __init__(self, root):
self.root = root
self.root.title("File Manager")
self.label = tk.Label(root, text="Select a folder:")
self.label.pack(pady=5)
self.folder_path = tk.Entry(root, width=50)
self.folder_path.pack(pady=5)
browse_btn = tk.Button(root, text="Browse", command=self.browse_folder)
browse_btn.pack(pady=5)
self.files_listbox = tk.Listbox(root, width=50, height=20)
self.files_listbox.pack(pady=10)
def browse_folder(self):
folder = filedialog.askdirectory()
if folder:
self.folder_path.delete(0, tk.END)
self.folder_path.insert(0, folder)
self.list_files(folder)
def list_files(self, folder):
self.files_listbox.delete(0, tk.END)
for file in os.listdir(folder):
self.files_listbox.insert(tk.END, file)
class Calculator:
def __init__(self, root):
self.root = root
self.root.title("Calculator")
self.create_widgets()
def create_widgets(self):
self.entry = tk.Entry(self.root, width=16, font=('Arial', 24), borderwidth=5)
self.entry.pack(pady=10)
button_frame = tk.Frame(self.root)
button_frame.pack()
buttons = [
'7', '8', '9', '/',
'4', '5', '6', '*',
'1', '2', '3', '-',
'0', '.', '=', '+'
]
row = 0
col = 0
for button in buttons:
action = lambda x=button: self.on_button_click(x)
tk.Button(button_frame, text=button, width=5, height=2, command=action).grid(row=row, column=col)
col += 1
if col > 3:
col = 0
row += 1
def on_button_click(self, value):
if value == '=':
try:
result = str(eval(self.entry.get()))
self.entry.delete(0, tk.END)
self.entry.insert(0, result)
except Exception as e:
self.entry.delete(0, tk.END)
self.entry.insert(0, "Error")
else:
self.entry.insert(tk.END, value)
class DrawingApp:
def __init__(self, root):
self.root = root
self.root.title("Drawing App")
self.color = "black"
self.current_tool = "free_draw"
self.start_x = None
self.start_y = None
self.temp_shape = None
self.create_canvas()
def create_canvas(self):
self.canvas = tk.Canvas(self.root, bg="white", width=600, height=400)
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<B1-Motion>", self.paint)
self.canvas.bind("<Button-1>", self.start_draw)
self.canvas.bind("<ButtonRelease-1>", self.end_draw)
button_frame = tk.Frame(self.root)
button_frame.pack(pady=5)
free_draw_btn = tk.Button(button_frame, text="Free Draw", command=lambda: self.select_tool("free_draw"))
free_draw_btn.pack(side=tk.LEFT, padx=5)
circle_btn = tk.Button(button_frame, text="Draw Circle", command=lambda: self.select_tool("circle"))
circle_btn.pack(side=tk.LEFT, padx=5)
square_btn = tk.Button(button_frame, text="Draw Square", command=lambda: self.select_tool("square"))
square_btn.pack(side=tk.LEFT, padx=5)
color_btn = tk.Button(button_frame, text="Select Color", command=self.select_color)
color_btn.pack(side=tk.LEFT, padx=5)
clear_btn = tk.Button(button_frame, text="Clear", command=self.clear_canvas)
clear_btn.pack(side=tk.LEFT, padx=5)
def select_tool(self, tool):
self.current_tool = tool
def select_color(self):
self.color = colorchooser.askcolor(color=self.color)[1]
def start_draw(self, event):
self.start_x, self.start_y = event.x, event.y
if self.current_tool in ["circle", "square"]:
self.temp_shape = None
def end_draw(self, event):
if self.current_tool == "circle":
if self.temp_shape:
self.canvas.delete(self.temp_shape)
self.canvas.create_oval(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
elif self.current_tool == "square":
if self.temp_shape:
self.canvas.delete(self.temp_shape)
self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
self.temp_shape = None
def paint(self, event):
if self.current_tool == "free_draw":
x, y = event.x, event.y
self.canvas.create_line(x, y, x + 1, y + 1, fill=self.color, width=2)
elif self.current_tool in ["circle", "square"]:
if self.temp_shape:
self.canvas.delete(self.temp_shape)
if self.current_tool == "circle":
self.temp_shape = self.canvas.create_oval(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
elif self.current_tool == "square":
self.temp_shape = self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y, outline=self.color, width=2)
def clear_canvas(self):
self.canvas.delete("all")
class Minesweeper:
def __init__(self, root):
self.root = root
self.root.title("Minesweeper")
self.create_board()
def create_board(self):
self.board_size = 8
self.mine_count = 10
self.buttons = {}
self.mines = set(random.sample(range(self.board_size ** 2), self.mine_count))
self.adjacent_counts = [[0 for _ in range(self.board_size)] for _ in range(self.board_size)]
for mine in self.mines:
row, col = divmod(mine, self.board_size)
for r in range(max(0, row - 1), min(self.board_size, row + 2)):
for c in range(max(0, col - 1), min(self.board_size, col + 2)):
self.adjacent_counts[r][c] += 1
for row in range(self.board_size):
for col in range(self.board_size):
btn = tk.Button(self.root, width=3, height=1)
btn.grid(row=row, column=col)
btn.bind("<Button-1>", lambda e, r=row, c=col: self.reveal_cell(r, c))
btn.bind("<Button-3>", lambda e, r=row, c=col: self.mark_mine(r, c))
self.buttons[(row, col)] = btn
def reveal_cell(self, row, col):
idx = row * self.board_size + col
if idx in self.mines:
self.buttons[(row, col)].config(text="*", bg="red")
messagebox.showinfo("Game Over", "You hit a mine!")
self.reset_game()
else:
count = self.adj
class TextEditor:
def __init__(self, root):
self.root = root
self.root.title("Text Editor")
self.create_widgets()
def create_widgets(self):
self.text = tk.Text(self.root, wrap='word')
self.text.pack(expand=True, fill='both')
toolbar = tk.Frame(self.root)
toolbar.pack(side=tk.TOP, fill=tk.X)
bold_button = tk.Button(toolbar, text="Bold", command=self.toggle_bold)
bold_button.pack(side=tk.LEFT)
italic_button = tk.Button(toolbar, text="Italic", command=self.toggle_italic)
italic_button.pack(side=tk.LEFT)
size_button = tk.Button(toolbar, text="Change Font Size", command=self.change_font_size)
size_button.pack(side=tk.LEFT)
def toggle_bold(self):
current_tags = self.text.tag_names("sel.first")
if "bold" in current_tags:
self.text.tag_remove("bold", "sel.first", "sel.last")
else:
self.text.tag_add("bold", "sel.first", "sel.last")
self.text.tag_configure("bold", font=("Arial", 12, "bold"))
def toggle_italic(self):
current_tags = self.text.tag_names("sel.first")
if "italic" in current_tags:
self.text.tag_remove("italic", "sel.first", "sel.last")
else:
self.text.tag_add("italic", "sel.first", "sel.last")
self.text.tag_configure("italic", font=("Arial", 12, "italic"))
def change_font_size(self):
size = simpledialog.askinteger("Font Size", "Enter font size:", minvalue=1, maxvalue=100)
if size:
self.text.tag_configure("font_size", font=("Arial", size))
self.text.tag_add("font_size", "sel.first", "sel.last")
class Solitaire:
def __init__(self, root):
self.root = root
self.root.title("Solitaire")
self.setup_game()
def setup_game(self):
self.create_widgets()
self.initialize_deck()
self.deal_cards()
def create_widgets(self):
self.canvas = tk.Canvas(self.root, width=800, height=600, bg="green")
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<Button-1>", self.on_click)
def initialize_deck(self):
suits = ['♠', '♥', '♦', '♣']
self.deck = [f"{value} {suit}" for suit in suits for value in range(1, 14)]
random.shuffle(self.deck)
self.columns = [[] for _ in range(7)]
self.stock = []
self.waste = []
self.foundation = {suit: [] for suit in suits}
def deal_cards(self):
for i in range(7):
for j in range(i + 1):
card = self.deck.pop()
self.columns.append(card)
self.stock = self.deck
self.draw_tableau()
def draw_tableau(self):
self.canvas.delete("all")
x_offset = 50
y_offset = 50
for i, column in enumerate(self.columns):
x = x_offset + i * 100
for j, card in enumerate(column):
y = y_offset + j * 30
text = card if j == len(column) - 1 else "X"
self.canvas.create_rectangle(x, y, x + 70, y + 100, fill="white" if j == len(column) - 1 else "gray")
self.canvas.create_text(x + 35, y + 50, text=text, font=("Arial", 12))
self.canvas.create_rectangle(50, 400, 120, 470, fill="blue")
self.canvas.create_text(85, 435, text="Stock", font=("Arial", 12))
if self.waste:
self.canvas.create_rectangle(150, 400, 220, 470, fill="white")
self.canvas.create_text(185, 435, text=self.waste[-1], font=("Arial", 12))
def on_click(self, event):
x, y = event.x, event.y
if 50 <= x <= 120 and 400 <= y <= 470:
self.draw_from_stock()
return
column_clicked = (x - 50) // 100
if 0 <= column_clicked < len(self.columns):
self.handle_tableau_click(column_clicked)
def draw_from_stock(self):
if self.stock:
card = self.stock.pop()
self.waste.append(card)
else:
self.stock = self.waste[::-1]
self.waste = []
self.draw_tableau()
def handle_tableau_click(self, column_index):
column = self.columns[column_index]
if not column:
return
card = column.pop()
for other_column in self.columns:
if other_column and other_column[-1].split()[1] != card.split()[1]:
other_column.append(card)
break
self.draw_tableau()
if __name__ == "__main__":
root = tk.Tk()
app = SimpleGUIOS(root)
root.mainloop()