Das spiel hat nun einige ab Änderungen bekommen zum einem ist der “Spieler” Grösser geworden um die Fläche zu symbolisieren auf der er gerade steht und zum anderen gibt es nun auch “World Borders” welche das spiel eingrenzen.
Hier der Bisherige Code:
import tkinter as tk
class MoveCharacter(tk.Canvas):
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.dx = 0
self.dy = 0
self.height = 100
self.width = 100
self.start_X = 0
self.start_Y = 0
self.x = self.start_X
self.y = self.start_Y
# Create the box (character)
self.box = self.create_rectangle(self.start_X, self.start_Y, self.height, self.width, fill="black")
# Set update interval in milliseconds
self.dt = 100
self.tick()
# Movement handler that gets called every dt milliseconds
def tick(self):
self.coordinats(self.dx, self.dy)
wall_check(self.center)
if not Dteck:
self.move(self.box, self.dx, self.dy)
if Dteck:
self.coordinats(self.dx, self.dy)
if not Dteck:
# Reset the movement after each tick
self.dx = 0
self.dy = 0
# Repeatedly call tick method to continue the movement loop
self.after(self.dt, self.tick)
# Method to change direction of movement
def change_heading(self, dx, dy):
self.dx = dx
self.dy = dy
def coordinats(self, stepx, stepy):
self.x = self.x + stepx
self.y = self.y + stepy
self.center = [self.x + 50, self.y - 50]
def main():
global root,character_canvas
# Create the main window
root = tk.Tk()
root.title("2D Game")
root.geometry("1080x720")
root.configure(bg="black")
# Create the MoveCharacter canvas (size 900x900)
character_canvas = MoveCharacter(root, width=900, height=900, bg="lightblue")
character_canvas.pack()
keybindings()
# Start the main loop
root.mainloop()
def keybindings():
global ds
# Define movement step size
ds = 100 # Smaller step for smoother movement
# Bind key presses for movement
root.bind("<KeyPress-a>", lambda _: character_canvas.change_heading(-ds, 0)) # Move left
root.bind("<KeyPress-d>", lambda _: character_canvas.change_heading(ds, 0)) # Move right
root.bind("<KeyPress-w>", lambda _: character_canvas.change_heading(0, -ds)) # Move up
root.bind("<KeyPress-s>", lambda _: character_canvas.change_heading(0, ds)) # Move down
def wall_check(coords):
global Dteck
Dteck = False
if coords[0] < 50 :
character_canvas.change_heading(0, 0)
Dteck = True
character_canvas.coordinats(100,0)
if coords[0] > 850 :
character_canvas.change_heading(0, 0)
Dteck = True
character_canvas.coordinats(-100,0)
if coords[1] > 750 :
character_canvas.change_heading(0, 0)
Dteck = True
character_canvas.coordinats(0,-100)
if coords[1] < -50 :
character_canvas.change_heading(0, 0)
Dteck = True
character_canvas.coordinats(0,100)
print(coords)
# Run the program
main()