Currently I am trying to teach myself more about functions with parameters and return values that connects with one to another.
In this code I created a square object with graphics.py that moves to a direction in loop whenever you press an arrow key.
from graphics import *
import keyboard, time
width = 200
height = 200
win = GraphWin("MOVEMENTS", width, height)
win.setBackground(color_rgb(25,25,25))
key = ""
def movement(key):
if keyboard.is_pressed("Right"):
key = "d"
if keyboard.is_pressed("Left"):
key = "a"
if keyboard.is_pressed("Down"):
key = "s"
if keyboard.is_pressed("Up"):
key = "w"
return key
def horizontal_movement(x):
global key
key = movement(key)
if key == "d":
x += 20
elif key == "a":
x -= 20
return x
def vertical_movement(y):
global key
key = movement(key)
if key == "s":
y += 20
elif key == "w":
y -= 20
return y
def main():
x = 0
y = 0
radius = 10
player = Rectangle(Point((width/2)-radius+x,(height/2)-radius+y), Point((width/2)+radius+x, (height/2)+radius+y))
while(True):
player.undraw()
player = Rectangle(Point((width/2)-radius+x,(height/2)-radius+y), Point((width/2)+radius+x,(height/2)+radius+y))
player.setFill("green")
player.setWidth(2)
player.draw(win)
x = horizontal_movement(x)
y = vertical_movement(y)
update(10)
main()
I want to know if there is a better code design that can move the movement(key) function into the horizontal_movement(x) and vertical_movement(y) function because right now I feel like I have typed some unecessary coding (the movement function and global key) into the script and I want it be as efficient as possible.
If there is an alternative that makes the script more efficient or perform better, please let me know so I can improve further.