You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
3.0 KiB

2 years ago
import tkinter as tk
from PIL import Image,ImageTk
import random
import threading
import time
from world import World
import sys
2 years ago
RENDER_WIDTH, RENDER_HEIGHT = 640 // 32 + 1, 480 // 32 + 1
FPS = 20
class Camera:
def __init__(self, x: int, y: int):
self.x: int = x
self.y: int = y
class Renderer:
def key_press(self, event: tk.Event):
if event.keysym == "Escape":
self.running = False
self.keys[event.keysym] = True
def key_release(self, event: tk.Event):
if event.keysym in self.keys:
self.keys[event.keysym] = False
def is_down(self, key):
if not (key in self.keys):
return 0
return 1 if self.keys[key] else 0
2 years ago
def render(self):
offset_x, offset_y = self.camera.x % 32, self.camera.y % 32
index = 0
self.world.update_chunks(self.camera.x // 32, self.camera.y // 32)
for tile in self.tiles:
self.canvas.moveto(tile, 32 * (index % RENDER_WIDTH)- offset_x, 32 * (index // RENDER_WIDTH) - offset_y)
self.canvas.itemconfig(tile, image=self.sprites[self.world.get_block(
self.camera.x // 32 + index % RENDER_WIDTH,
self.camera.y // 32 + index // RENDER_WIDTH
).id])
index += 1
def update(self):
move_x = self.is_down("Right") - self.is_down("Left")
move_y = self.is_down("Down") - self.is_down("Up")
self.camera.x += move_x * 10
self.camera.y += move_y * 10
2 years ago
def update_thread(self):
while self.running:
self.update()
2 years ago
self.render()
time.sleep(1 / FPS)
def __init__(self):
self.running = True
self.window = tk.Tk()
self.window.title("MC 2D")
self.window.geometry("640x480")
self.camera = Camera(90 * 32, 90 * 32)
self.world = World(self.camera.x // 32, self.camera.y // 32)
self.keys = {}
2 years ago
self.sprites = [
"sprites/air.png",
"sprites/stone.png",
"sprites/dirt.png",
"sprites/grass.png",
"sprites/coal.png",
"sprites/iron.png",
"sprites/gold.png",
"sprites/diamond.png",
"sprites/log.png",
"sprites/leaf.png",
2 years ago
]
self.sprites = [
ImageTk.PhotoImage(Image.open(sprite)) for sprite in self.sprites
]
self.canvas = tk.Canvas(self.window, width=640, height=480, background="white")
self.canvas.pack()
self.tiles = [
self.canvas.create_image(32 * (i % RENDER_WIDTH) - 16, 32 * (i // RENDER_WIDTH) - 16, anchor="nw", image=self.sprites[random.randint(0, len(self.sprites) - 1)])
for i in range(RENDER_WIDTH * RENDER_HEIGHT)
]
self.tupdate = threading.Thread(target=self.update_thread)
self.tupdate.start()
self.window.bind("<Key>", self.key_press)
self.window.bind("<KeyRelease>", self.key_release)
2 years ago
self.window.mainloop()
self.running = False