Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
daedalus
import PySimpleGUI as sg
import random
import time
RESOLUTIONS = ["640x400","800x600","1024x800", "1024x960","1200x1024"]
WIDTH, HEIGHT = 800,600
MIN_TILES = 10
MAX_TILES = 200
HELPTEXT = """Escape from the labyrinth. Reach the yellow goal.
You are the green rect.
user cursor keys to navigate. """
#COLORS = []
#for r in range(16,200,8):
# for g in range(16,200,8):
# for b in range(16,200,8):
# COLORS.append("#{}{}{}".format(str(hex(r).replace("0x","")),
# str(hex(g).replace("0x","")),
# str(hex(b).replace("0x","")),
# ))
#print(COLORS)
#random.shuffle(COLORS)
# -------- first gui: theme cooser --------------------------
sg.theme(random.choice(sg.theme_list()))
# ---------------------- theme selector layout -------------
layout1 = [
[
sg.Text("Select theme:"),
sg.Combo(
values=sg.theme_list(),
default_value=sg.theme(),
enable_events=True,
key="selector",
),
],
[sg.Text("# x-tiles:"),sg.Slider(range=(MIN_TILES,MAX_TILES), default_value=50,orientation="h", key="x_slider")],
[sg.Text("# y-tiles:"),sg.Slider(range=(MIN_TILES,MAX_TILES), default_value=20,orientation="h", key="y_slider")],
[sg.Text("canvas resolution in Pixel:"),
sg.Combo(values=RESOLUTIONS, key="resolution", default_value="800x600")],
#[sg.Text("Pause in [ms]:"),sg.Slider(range=(0,1000), default_value=500,orientation="h", key="pause_slider")],
[sg.Button("play the game")],
]
window1 = sg.Window("theme selector", layout1)
# ---------------- main loop for first layout ---------------
while True:
event1, values1 = window1.read()
if event1 == "play the game" or event1 == sg.WIN_CLOSED:
# sg.theme("DarkBlue3")
break
if event1 == "selector":
old = sg.theme()
sg.theme(values1["selector"])
if sg.PopupYesNo("do you like this Theme?") == "Yes":
break
else:
sg.theme(old)
WIDTH, HEIGHT = [int(v) for v in values1["resolution"].split("x")]
X_TILES = int(values1["x_slider"])
Y_TILES = int(values1["y_slider"])
window1.close()
# -----------------end of theme chooser -------------------
# --------------- start of labyrinth game ------------------
class Game:
monsters = {}
number = 0
class Monster:
def __init__(self):
self.number = Game.number
Game.number += 1
Game.monsters[self.number] = self
# calculate starting position
for _ in range(1000):
x = random.randint(MIN_TILES//2, X_TILES-1 )
y = random.randint(MIN_TILES//2, Y_TILES-1 )
print("xy:",x,y)
if lines[y][x] == 0:
break
else:
raise ValueError("Could not create Monster, no empty space in labyrinth?")
self.x = x
self.y = y
self.figure = c.draw_rectangle(
top_left=(self.x, self.y),
bottom_right=(self.x+1, self.y+1),
fill_color="red")
def hunt(self, x,y):
"""moves toward a x,y position, with a random chance to do something else"""
# chance to do a random move
if random.random() < 0.5:
dx = random.choice((-1,0,1))
dy = random.choice((-1,0,1))
return dx, dy
dx = cmp(x, self.x)
dy = cmp(y, self.y)
return dx, dy
def cmp(a, b):
"""returns 0, -1 or 1"""
return (a > b) - (a < b)
def is_free(x,y):
"""returns True if position (in array 'lines') is 0,
returns False if position is not existing or a wall"""
try:
location = lines[y][x]
except IndexError:
return False
if location == 0:
return True
return False
def make_trail():
"""creates a dark green rectangle on the player position
should be appended to list 'figures'"""
return c.draw_rectangle(
top_left=(player_pos_x, player_pos_y),
bottom_right=(player_pos_x+1, player_pos_y+1),
fill_color="green" )
layout2 = [
[sg.Text("Time left (seconds):", font=["System",32]),
sg.Text("60", key="time_left", font=["System",32])],
[sg.Multiline(default_text=HELPTEXT, size=(90,3), disabled=True),
sg.Button("Exit")],
[sg.Graph(canvas_size=(WIDTH,HEIGHT),background_color="black",
key="canvas", graph_bottom_left=(0, Y_TILES),
graph_top_right=(X_TILES,0 ))],
]
window2 = sg.Window("enjoy the game", layout2, return_keyboard_events=True)
window2.finalize() # necessary to be able to draw on canvas
c = window2["canvas"]
# ----- create labyrinth -----
lines = []
figures = [] # for Tkinter
# generate labyrinth
# little chance of empty labyrint
if random.random() < 0.01:
lines = [[0 for x in range(X_TILES)] for y in range(Y_TILES)]
else:
for y in range(Y_TILES):
line = []
for x in range(X_TILES):
if (x,y) == (0,0) :
line.append(0)
continue
if (x,y) == (X_TILES-1, Y_TILES-1):
line.append(0)
continue
line.append(random.choice((0,0,0,0,0,1)))
if line[-1] == 1:
# create wall
figures.append(c.draw_rectangle(top_left=(x,y), bottom_right=(x+1,y+1),
fill_color="white"))
lines.append(line)
# ---- create monsters -----
for m in range(4):
Monster()
# ------------- main loop -----------
duration = 60
player_pos_x = 0
player_pos_y = 0
figures.append(make_trail())
player = c.draw_rectangle(top_left=(0,0), bottom_right=(1,1), fill_color="#00FF00")
goal = c.draw_rectangle(top_left=(X_TILES-1,Y_TILES-1), bottom_right=(X_TILES, Y_TILES), fill_color="yellow")
end_time = time.time() + duration
while not ((player_pos_x == X_TILES-1) and (player_pos_y != Y_TILES+1)):
event2, values2 = window2.read(timeout=100)
print(event2, values2)
if event2 in ("Exit", sg.WINDOW_CLOSED ):
break
if event2 == sg.TIMEOUT_EVENT:
# blink the player
#window2.finalize()
# update time left
if time.time() < end_time:
window2["time_left"].update(f"{end_time-time.time():.2f}")
else:
window2["time_left"].update("time is up - no bonus")
# TODO: windwos (every?) computers have different key-codes!
#if ":" in event2:
# print(player_pos_y, player_pos_x)
moved = False
#if event2 == "Up:111":
if event2.startswith("Up:"):
if is_free(x=player_pos_x, y=player_pos_y-1):
player_pos_y -= 1
figures.append(make_trail())
moved = True
#if event2 == "Left:113":
if event2.startswith("Left:"):
if is_free(x=player_pos_x-1, y=player_pos_y):
player_pos_x -= 1
figures.append(make_trail())
moved = True
#if event2 == "Down:116":
if event2.startswith("Down:"):
if is_free(x=player_pos_x, y=player_pos_y+1):
player_pos_y += 1
figures.append(make_trail())
moved = True
#if event2 == "Right:114":
if event2.startswith("Right"):
if is_free(x=player_pos_x+1, y=player_pos_y):
player_pos_x += 1
figures.append(make_trail())
moved = True
# ------ always ----
if moved:
# --------- move player ----
c.relocate_figure(player, player_pos_x, player_pos_y)
c.bring_figure_to_front(player)
# --------- move monsters ----
for m in Game.monsters.values():
dx,dy = m.hunt(player_pos_x, player_pos_y)
if is_free(m.x+dx, m.y+dy):
m.x +=dx
m.y +=dy
c.relocate_figure(m.figure, m.x, m.y)
#c.delete_figure(player)
#player = c.draw_rectangle(top_left=(player_pos_x,player_pos_y), bottom_right=(player_pos_x+1,player_pos_y+1), fill_color="#00FF00")
window2.close()
print("bye")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment