Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # tk_war.py
- import tkinter as tk
- import random
- import math
- from PIL import Image, ImageTk, ImageDraw
- WINDOW_WIDTH = 500
- WINDOW_HEIGHT = 500
- CX, CY = WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2
- ROCK_COUNT = PAPER_COUNT = SCISSORS_COUNT = 150
- EDGE_AVOID_RADIUS = 20
- REPULSION_RADIUS = 25
- CONVERT_RADIUS = 20
- SPEED = 1
- root = tk.Tk()
- root.title("tk_war")
- root.geometry("%dx%d+%d+%d" % (WINDOW_WIDTH, WINDOW_HEIGHT, 10, 10))
- canvas = tk.Canvas(root, width=WINDOW_WIDTH, height=WINDOW_HEIGHT, bg="white")
- canvas.pack()
- tribe_color = {
- "rock": "red",
- "paper": "lime",
- "scissors": "black"
- }
- chase = {
- "rock": "scissors",
- "scissors": "paper",
- "paper": "rock",
- }
- cxy = {
- "rock": "",
- "scissors": "",
- "paper": ""
- }
- food_chain = '{rock} > {scissors} > {paper} > {rock}'.format_map(tribe_color)
- def offset(t=1.2):
- return random.uniform(-t, t)
- def avoid_edges():
- x0 = min(WINDOW_WIDTH - EDGE_AVOID_RADIUS, max(x, EDGE_AVOID_RADIUS))
- y0 = min(WINDOW_HEIGHT - EDGE_AVOID_RADIUS, max(y, EDGE_AVOID_RADIUS))
- return x0, y0
- def avoid_entities(x, y):
- for j, (x2, y2, entity2) in enumerate(entities):
- if i != j:
- distance = distance_to(x, y, x2, y2)
- if distance < REPULSION_RADIUS:
- angle = math.atan2(y - y2, x - x2)
- x += 5 * math.cos(angle)
- y += 5 * math.sin(angle)
- if distance < CONVERT_RADIUS:
- entities[j] = (x2, y2, entity)
- return x, y
- return movement(x, y, CX, CY)
- def movement(x, y, target_x, target_y):
- angle = math.atan2(y - target_y, x - target_x) + if_rev
- x += SPEED * math.cos(angle + offset())
- y += SPEED * math.sin(angle + offset())
- return x, y
- def distance_to(x1, y1, x2, y2):
- return math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
- def draw_entity(x, y, entity):
- color = tribe_color[entity]
- draw.ellipse((x - 2, y - 2, x + 2, y + 2), fill=color, outline=color)
- def start(event=0):
- global entities
- entities = [(random.randint(0, WINDOW_WIDTH), random.randint(0, WINDOW_HEIGHT), "rock") for _ in range(ROCK_COUNT)]
- entities += [(random.randint(0, WINDOW_WIDTH), random.randint(0, WINDOW_HEIGHT), "paper") for _ in range(PAPER_COUNT)]
- entities += [(random.randint(0, WINDOW_WIDTH), random.randint(0, WINDOW_HEIGHT), "scissors") for _ in range(SCISSORS_COUNT)]
- random.shuffle(entities)
- start()
- root.bind("<space>", start)
- pil_image = Image.new('RGB', (WINDOW_WIDTH, WINDOW_HEIGHT), color='white')
- draw = ImageDraw.Draw(pil_image)
- while True:
- for i, (x, y, entity) in enumerate(entities):
- if_rev = math.pi
- x, y = avoid_edges()
- x, y = avoid_entities(x, y)
- draw_entity(x, y, entity)
- entities[i] = (x, y, entity)
- photo_image = ImageTk.PhotoImage(pil_image)
- canvas.create_image(0, 0, anchor='nw', image=photo_image)
- root.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement