I'm trying to create a game where images are placed in random cells of a grid. I had managed to create a grid and I tried to use that in order to randomly place the images but it does not seem to work as I would like it to.
try:
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import *
except ImportError:
import Tkinter as tk
from Tkinter import ttk
from Tkinter.ttk import *
import random
from random import randint
window = tk.Tk()
style = ttk.Style(window)
style.configure("BW.TLabel")
game_frame = tk.Frame(window)
game_grid = tk.Canvas(game_frame, width=450, height=450, borderwidth=0,
highlightthickness=0)
def grid_create():
global row, col, cell_width, cell_height, rect, rows , columns
rows = 8
columns = 8
cell_width = 50
cell_height = 50
rect = {}
for i in (game_grid, game_frame):
i.pack()
for column in range(8):
for row in range(8):
x1 = column*cell_width
y1 = row * cell_height
x2 = x1 + cell_width
y2 = y1 + cell_height
rect[row,column] = game_grid.create_rectangle(x1,y1,x2,y2,
fill="green",
tags="rect")
grid_draw()
def grid_draw():
global row, col
game_grid.itemconfig("rect", fill="green")
for i in range(8):
row = random.randint(0,8)
col = random.randint(0,8)
create_objects()
def create_objects():
rows = 8
columns = 8
cell_width = 50
cell_height = 50
bandits = 5
bandit_list = {}
bandit_img = tk.PhotoImage(file="Bandit.png")
for column in range(randint(0,8)):
for row in range(randint(0,8)):
x1 = column*cell_width + 22
y1 = row * cell_height - 22
x2 = x1 + cell_width
y2 = y1 + cell_height
bandit_list[row, column] = game_grid.create_image(x1, y2,
image=bandit_img)
for i in range(randint(0,5)):
row = random.randint(0,8)
col = random.randint(0,8)
grid_create()
window.mainloop()
I only want five 'bandits' to be displayed in random cells - hence the bandits = 5 - but I can't seem to figure out how to do this. I also do not want any of the 'bandits' to overlap. Any help is appreciated.
Image: Link to image as I do not have the required reputation to embed it here.
Aucun commentaire:
Enregistrer un commentaire