Why won't this work
Asked Answered
S

5

0

when each if statement has 1 city it works, but when I add more than one then it doesn't work.

Systematist answered 4/12, 2023 at 19:36 Comment(0)
S
0

Systematist Comparison operators have precedence over logical operators and a non-empty string always evaluates to true.

Spasmodic answered 4/12, 2023 at 19:52 Comment(0)
S
1

Found how to fix it but I don't know if it's the best fix

`func process(delta):
var city = Globals.CityType

if city == 'New York' or city == 'Beijing' or city == 'Riga':
	$TextureRect.texture = load("res://Images/office.png")
elif city == 'Chicago' or city == 'Shanghai' or city == 'Jelgava':
	$TextureRect.texture = load("res://Images/sunny.png")
elif city == 'San Diego' or city == 'Chongqing' or city == 'Daugavpils':
	$TextureRect.texture = load("res://Images/realistic sunny.png")

`

Systematist answered 4/12, 2023 at 20:3 Comment(0)
S
0

Systematist Great, but this is not really scalable. Should you decide to add more cities and more images in the future your code might become spaghettified. Better to put all this into an appropriate data structure that maps cities to corresponding images. This way you can avoid excessive if-ing altogether and make your code more readable and easier to manage.

Spasmodic answered 4/12, 2023 at 20:9 Comment(0)
C
0

Alys At the very least you should learn match instead of if elif when comparing many things to one variable.

	match city:
		"New York", "Beijing", "Riga":
			$TextureRect.texture = load("res://Images/office.png")
		"Chicago", "Shanghai", "Jelgava":
			$TextureRect.texture = load("res://Images/sunny.png")
		"San Diego", "Chongqing", "Daugavpils":
			$TextureRect.texture = load("res://Images/realistic sunny.png")
Cryptozoic answered 4/12, 2023 at 22:2 Comment(0)
R
0

an appropriate data structure that maps cities to corresponding images

Example:

var city_image: Dictionary = {
       "New York": "office.png",
       "Beijing": "office.png",
       "Riga": "office.png",
        ...
}

if city_image.has(city):
        $TextureRect.texture = load("res://Images/" + city_image[city])
else:
        print_debug("no image for city '%s'" % city)
Rolo answered 4/12, 2023 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.