There are classes for Location, Drunk, and Field. I was trying to have a subclass dirty field. That generates a dirty tile in the field. If a random walker moves on the dirty tile then, they keep moving.
I am getting the following error: I am hoping that y'all see something that I don't see.
edit: I have fixed the grammar errors and now when running I am getting a randint() error. When looking into randint should I change it to uniform?
KeyboardInterrupt Traceback (most recent call last)
Input In [20], in <cell line: 27>()
22 self.party[motive] =\
23 self.party[motive].move(x, y)
26 start = Location(0, 0)
---> 27 f = dirtyField()
29 homer = SouthDrunk('Homer')
30 f.addDrunk(homer, start)
Input In [20], in dirtyField.__init__(self, dirtyTiles, xRange, yRange)
6 w = 0
7 while (w < dirtyTiles):
----> 8 x = random.randint(-xRange, xRange)
9 y = random.randint(-yRange, yRange)
10 aDirtyTile = Location(x, y)
File ~\anaconda3\lib\random.py:338, in Random.randint(self, a, b)
334 def randint(self, a, b):
335 """Return random integer in range [a, b], including both end points.
336 """
--> 338 return self.randrange(a, b+1)
File ~\anaconda3\lib\random.py:314, in Random.randrange(self, start, stop, step)
312 width = istop - istart
313 if step == 1 and width > 0:
--> 314 return istart + self._randbelow(width)
315 if step == 1:
316 raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
File ~\anaconda3\lib\random.py:243, in Random._randbelow_with_getrandbits(self, n)
241 return 0
242 getrandbits = self.getrandbits
--> 243 k = n.bit_length() # don't use (n-1) here because n can be 1
244 r = getrandbits(k) # 0 <= r < 2**k
245 while r >= n:
KeyboardInterrupt:
class dirtyField(Field):
def __init__(self, dirtyTiles = 1000,
xRange = 100, yRange = 100):
Field.__init__(self)
self.dirtTile = []
w = 0
while (w < dirtyTiles):
x = random.randint(-xRange, xRange)
y = random.randint(-yRange, yRange)
aDirtyTile = Location(x, y)
self.dirtTile.append(aDirtyTile)
def moveDrunk(self, motive):
# per instructions if the axis is a dirty tile then the drunk moves until a clean tile.
# one tile at a time motive is another
Field.moveDrunk(self, motive)
while (self.party[motive] in self.dirtTiles):
self.party[motive] =\
self.party[motive].move(x, y)
x, y = motive.takeStep()
self.party[motive] =\
self.party[motive].move(x, y)
start = Location(0, 0)
f = dirtyField()
homer = SouthDrunk('Homer')
f.addDrunk(homer, start)
f.moveDrunk(homer)
print(f.getLoc(homer))
I had grammar errors and def moveDrunk was too much. I also needed w+=1 at the init
I have some Numba accelerated code in NoPython mode using numbaa.njit().
At some point I need to parse a str (or bytes) to get a float.
In pure Python, the way I would go about it is with float(), but that does not work:
import numba as nb
#nb.njit
def str2float(text):
return float(text)
str2float("1.2")
TypingError: Failed in nopython mode pipeline (step: nopython frontend)
No implementation of function Function(<class 'float'>) found for signature:
>>> float(unicode_type)
while I would like it to produce a float with value 1.2.
The following questions are somewhat related:
this question discusses parsing to int (str/bytes-to-int)
this question discusses the opposite, i.e. the conversion of a float-to-str conversion
While this is not yet supported (as of July 2022), you can implement something manually.
Below are two versions, one for str and one for bytes.
In the process of solving the task I use a str/bytes-to-int which is used to parse str that include the exponential notation e.g. 1.0e-02 and -- potentially -- a trim() function to pre-process inputs surrounded by whitespaces ("C" whitespaces: " ", "\n", "\r", "\t", "\v").
Both are presented here and only used below.
From str
import math
import numba as nb
#nb.njit
def str2float_helper(text):
sep = ord(".")
c_min = ord("0")
c_max = ord("9")
n = len(text)
valid = n > 0
# determine sign
start = n - 1
stop = -1
sign = 1
if valid:
first = ord(text[0])
if first == ord("+"):
stop = 0
elif first == ord("-"):
sign = -1
stop = 0
# parse rest
sep_pos = 0
number = 0
j = 0
for i in range(start, stop, -1):
c = ord(text[i])
if c_min <= c <= c_max:
number += (c - c_min) * 10 ** j
j += 1
elif c == sep and sep_pos == 0:
sep_pos = j
else:
valid = False
break
return sign * number, sep_pos, valid
#nb.njit
def str2float(text):
if text == "nan" or text == "NAN" or text == "NaN":
return math.nan
exp_chars = b"eE"
exp_pos = -1
for exp_char in exp_chars:
for i, c in enumerate(text[::-1]):
c = ord(c)
if c == exp_char:
exp_pos = i
break
if exp_pos > -1:
break
if exp_pos > 0:
exp_number = str2int(text[-exp_pos:])
if exp_number is None:
exp_number = 0
number, sep_pos, valid = str2float_helper(text[:-exp_pos-1])
result = number / 10.0 ** (sep_pos - exp_number) if valid else None
else:
number, sep_pos, valid = str2float_helper(text)
result = number / 10.0 ** sep_pos if valid else None
return result
This should work similarly to float_() (defined below) which is a helper function that returns None instead of raising in case of parsing failure:
def float_(x):
try:
return float(x)
except ValueError:
return None
def is_close(x, y):
if x and not y or not x and y:
return False
else:
return x == y or math.isclose(x, y) or math.isnan(x) and math.isnan(y)
numbers = (
"", "NaN", "10", "32.1", "4123.43214e+05", "4123.43214E+05", "4123.43214e-05",
"-31", "-12.3", "-4123.43214e+05", "-4123.43214E+05", "-4123.43214e-05",
" 1321.432 \t ", "1+2", "1-2", "1e", "e1",
)
k = 24
for number in numbers:
print(f"{number!r:{k}} {float_(number)!s:{k}} {str2float(number)!s:{k}} {is_close(float_(number), str2float(number))}")
# '' None None True
# 'NaN' nan nan True
# '10' 10.0 10.0 True
# '32.1' 32.1 32.1 True
# '4123.43214e+05' 412343214.0 412343214.0 True
# '4123.43214E+05' 412343214.0 412343214.0 True
# '4123.43214e-05' 0.0412343214 0.0412343214 True
# '-31' -31.0 -31.0 True
# '-12.3' -12.3 -12.3 True
# '-4123.43214e+05' -412343214.0 -412343214.0 True
# '-4123.43214E+05' -412343214.0 -412343214.0 True
# '-4123.43214e-05' -0.0412343214 -0.0412343214 True
# ' 1321.432 \t ' 1321.432 None False
# '1+2' None None True
# '1-2' None None True
# '1e' None None True
# 'e1' None None True
# '1.1e-200' 1.1e-200 1.0999999999999995e-200 True
# '1.1e+200' 1.1e+200 1.1000000000000005e+200 True
(except for the trimming whitespaces part which can be added if needed).
Timewise, this is some 12x slower than pure Python:
%timeit -n 32 -r 32 [str2float(number) for number in numbers]
# 32 loops, best of 32: 80.3 µs per loop
%timeit -n 32 -r 32 [float_(number) for number in numbers]
# 32 loops, best of 32: 6.55 µs per loop
and hence only useful if this is needed as part of a more complex njit()-ed code.
From bytes
This is essentially a rewrite of the above to work with bytes (which typically only require skipping some ord(), because iterating bytes provides the integer representation directly) or defining a == operator because that is not available for bytes.
#nb.njit
def bytes2float_helper(text):
sep = ord(".")
c_min = ord("0")
c_max = ord("9")
n = len(text)
valid = n > 0
# determine sign
start = n - 1
stop = -1
sign = 1
if valid:
first = text[0]
if first == ord("+"):
stop = 0
elif first == ord("-"):
sign = -1
stop = 0
# parse rest
sep_pos = 0
number = 0
j = 0
for i in range(start, stop, -1):
c = text[i]
if c_min <= c <= c_max:
number += (c - c_min) * 10 ** j
j += 1
elif c == sep and sep_pos == 0:
sep_pos = j
else:
valid = False
break
return sign * number, sep_pos, valid
#nb.njit
def eqb(text_a, text_b):
len_a = len(text_a)
len_b = len(text_b)
if len_a == len_b:
for i in range(len_a):
if text_a[i] != text_b[i]:
return False
return True
else:
return False
#nb.njit
def bytes2float(text):
if eqb(text, b"nan") or eqb(text, b"NAN") or eqb(text, b"NaN"):
return math.nan
exp_chars = b"eE"
exp_pos = -1
for exp_char in exp_chars:
for i, c in enumerate(text[::-1]):
if c == exp_char:
exp_pos = i
break
if exp_pos > -1:
break
if exp_pos > 0:
exp_number = bytes2int(text[-exp_pos:])
if exp_number is None:
exp_number = 0
number, sep_pos, valid = bytes2float_helper(text[:-exp_pos-1])
result = number / 10.0 ** (sep_pos - exp_number) if valid else None
else:
number, sep_pos, valid = bytes2float_helper(text)
result = number / 10.0 ** sep_pos if valid else None
return result
The interesting bit it of this is that this has comparable speed (albeit marginally slower by some 15%) as the pure Python counterpart:
numbers = (
b"", b"NaN", b"10", b"32.1", b"4123.43214e+05", b"4123.43214E+05", b"4123.43214e-05",
b"-31", b"-12.3", b"-4123.43214e+05", b"-4123.43214E+05", b"-4123.43214e-05",
b" 1321.432 ", b"1+2", b"1-2", b"1e", b"e1", b"1.1e-200", b"1.1e+200",
)
k = 24
for number in numbers:
print(f"{number!s:{k}} {float_(number)!s:{k}} {bytes2float(number)!s:{k}} {is_close(float_(number), bytes2float(number))}")
# b'' None None True
# b'NaN' nan nan True
# b'10' 10.0 10.0 True
# b'32.1' 32.1 32.1 True
# b'4123.43214e+05' 412343214.0 412343214.0 True
# b'4123.43214E+05' 412343214.0 412343214.0 True
# b'4123.43214e-05' 0.0412343214 0.0412343214 True
# b'-31' -31.0 -31.0 True
# b'-12.3' -12.3 -12.3 True
# b'-4123.43214e+05' -412343214.0 -412343214.0 True
# b'-4123.43214E+05' -412343214.0 -412343214.0 True
# b'-4123.43214e-05' -0.0412343214 -0.0412343214 True
# b' 1321.432 ' 1321.432 None False
# b'1+2' None None True
# b'1-2' None None True
# b'1e' None None True
# b'e1' None None True
# b'1.1e-200' 1.1e-200 1.0999999999999995e-200 True
# b'1.1e+200' 1.1e+200 1.1000000000000005e+200 True
%timeit -n 32 -r 32 [bytes2float(number) for number in numbers]
# 32 loops, best of 32: 8.84 µs per loop
%timeit -n 32 -r 32 [float_(number) for number in numbers]
# 32 loops, best of 32: 7.66 µs per loop
I am trying to parse a bunch of color values from various files, perform lightness changes, and write them back into the files. I have to put this in a PKGBUILD for the Arch User Repository and would love to avoid any dependencies.
I have written the simple class below, and it works sometimes. The test function at the bottom of the snippet makes an iterable of Color instances from a decent number of test values, converts them to HSL, and then back to RGB. It then compares each with the original, to check if they match.
Sometimes the script exits successfully, but more often times not. I randomly see huge discrepancies, such as RGB #c7c7c7 -> HSL -> RGB #be3841. This doesn't make sense to me, how can it be this far off? There has to be an issue with my math, but I have checked that against Wikipedia so many times that I have come to the conclusion that it is simply a rounding error due to the precision of a 64-bit float, which Python uses by default on my platform.
I simply do not understand the randomness. I have tried using gmpy2 with 128-bit precision to no avail, it fails just as often. And if I use Decimal, the interpreter complains that I am accessing local variables before assignment which means that the comparison operators in the algorithms are not working as I would expect.
If you quickly run the script a few times, eventually there won't be an error.
https://www.online-python.com/ujtET97ZxQ
class Color:
def __init__(self, rgba):
rgba = rgba.lstrip("#")
if len(rgba) > 8:
raise Exception("Expected up to 8 hexadecimal characters")
self._red = int(rgba[0:2], 16)
self._green = int(rgba[2:4], 16)
self._blue = int(rgba[4:6], 16)
if len(rgba) == 8:
self.alpha = int(rgba[6:8], 16)
else:
self.alpha = None
self._rgb_changed = True
self._hsl_changed = False
def __repr__(self):
return self.hex()
def __hash__(self):
return hash(self.hex())
def __eq__(self, other):
return self.__class__ is other.__class__ and self.__hash__() == other.__hash__()
def hex(self):
return "#{:02x}{:02x}{:02x}".format(self.red, self.green, self.blue) + ("{:02x}".format(self.alpha) if self.alpha else "")
def hsl(self):
if self._hsl_changed:
raise Exception(
"Cannot convert from RGB when the last modified value was of HSL")
rp = self._red / 255
gp = self._green / 255
bp = self._blue / 255
cmax = max(rp, gp, bp)
cmin = min(rp, gp, bp)
delta = cmax - cmin
if delta == 0:
self._hue = 0
elif cmax == rp:
self._hue = 60 * ((gp - bp) / delta % 6)
elif cmax == gp:
self._hue = 60 * ((bp - rp) / delta + 2)
elif cmax == bp:
self._hue = 60 * ((rp - gp) / delta + 4)
self._lightness = (cmax + cmin) / 2
if delta == 0:
self._saturation = 0
else:
self._saturation = delta / (1 - abs(2 * self._lightness - 1))
self._rgb_changed = False
return (self._hue, self._saturation, self._lightness)
def rgb(self):
if self._rgb_changed:
raise Exception(
"Cannot convert from HSL when the last modified value was of RGB")
c = (1 - abs(2 * self._lightness - 1)) * self._saturation
x = c * (1 - abs((self._hue / 60) % 2 - 1))
m = self._lightness - c / 2
if self._hue >= 0 and self._hue < 60:
(rp, gp, bp) = (c, x, 0)
elif self._hue >= 60 and self._hue < 120:
(rp, gp, bp) = (x, c, 0)
elif self._hue >= 120 and self._hue < 180:
(rp, gp, bp) = (0, c, x)
elif self._hue >= 180 and self._hue < 240:
(rp, gp, bp) = (0, x, c)
elif self._hue >= 240 and self._hue < 300:
(rp, gp, bp) = (x, 0, c)
elif self._hue >= 300 and self._hue < 360:
(rp, gp, bp) = (c, 0, x)
self._red = round((rp + m) * 255)
self._green = round((gp + m) * 255)
self._blue = round((bp + m) * 255)
self._hsl_changed = False
return (self._red, self._green, self._blue)
#property
def red(self):
if self._hsl_changed:
self.rgb()
return self._red
#property
def green(self):
if self._hsl_changed:
self.rgb()
return self._green
#property
def blue(self):
if self._hsl_changed:
self.rgb()
return self._blue
#red.setter
def red(self, red):
self._red = red
self._rgb_changed = True
#green.setter
def green(self, green):
self._green = green
self._rgb_changed = True
#blue.setter
def blue(self, blue):
self._blue = blue
self._rgb_changed = True
#property
def hue(self):
if self._rgb_changed:
self.hsl()
return self._hue
#property
def saturation(self):
if self._rgb_changed:
self.hsl()
return self._saturation
#property
def lightness(self):
if self._rgb_changed:
self.hsl()
return self._lightness
#hue.setter
def hue(self, hue):
self._hue = hue
self._hsl_changed = True
#saturation.setter
def saturation(self, saturation):
self._saturation = saturation
self._hsl_changed = True
#lightness.setter
def lightness(self, lightness):
self._lightness = lightness
self._hsl_changed = True
def __test(colors):
from copy import deepcopy
colors = set(Color(color) for color in colors)
colors_mutated = deepcopy(colors)
for color in colors_mutated:
color.hsl()
color.rgb()
for (color_a, color_b) in zip(colors, colors_mutated):
if color_a != color_b:
raise AssertionError(
"Colors do not match! ({}, {})".format(color_a, color_b))
print("{} == {}".format(color_a, color_b))
if __name__ == "__main__":
colors = set("#353b48, #666666, #444852, #fcfcfc, #434343, #90939b, #353537, #2b303b, #b6b8c0, #241f31, #303440, #000000, #9398a2, #dfdfdf, #f0f1f2, #cfcfcf, #d3d8e2, #505666, #808080, #8a939f, #282b36, #afb8c6, #383838, #4dadd4, #353a48, #838383, #202229, #7a7f8a, #7a7f8b, #2e3340, #70788d, #66a1dc, #17191f, #d7d7d7, #545860, #39404d, #161a26, #be3841, #3c4049, #2f3a42, #f0f2f5, #4e4eff, #262934, #1d1f26, #404552, #353945, #383c45, #8f939d, #f7ef45, #a4aab7, #b2cdf1, #444a58, #bac3cf, #ff00ff, #f46067, #5c6070, #c7cacf, #525762, #ff0b00, #323644, #f75a61, #464646, #ecedf0, #171717, #e01b24, #1b1b1b, #797d87, #15171c, #8c919d, #4d4f52, #5b627b, #728495, #454c5c, #4080fb, #e2e2e2, #d1d3da, #c0e3ff, #3580e4, #b7c0d3, #232428, #2d323f, #6e6e6e, #dcdcdc, #b9bcc2, #cc575d, #a1a1a1, #52555e, #353a47, #7c818c, #979dac, #2f343f, #dde3e9, #828282, #c5dcf7, #001aff, #722563, #afb8c5, #222529, #8abfdd, #666a74, #f68086, #edf5fb, #4b5162, #a9acb2, #786613, #c7c7c7, #eeeff1, #2b2e37, #f70505, #292c36, #3e434f, #5c616c, #f57900, #2d303b, #f5f6f7, #5f697f, #2e3436, #808791, #f08437, #cbd2e3, #e5a50a, #eeeeee, #252932, #e7e8eb, #3e4350, #ff1111, #ef2929, #fc4138, #fcfdfd, #7a7a7a, #21242b, #bebebe, #ffffff, #252a35, #5252ff, #767b87, #535353, #3e3e3e, #aa5555, #5f6578, #c4c7cc, #383c4a, #102b68, #21252b, #f3af0b, #cfd6e6, #d7787d, #ff7a80, #fdfdfd, #398dd3, #a51d2d, #73d216, #f8f8f9, #262932, #2f343b, #2b2e39, #2d3036, #f04a50, #006098, #3f4453, #ad4242, #1b1c21, #b9bfce, #ff1616, #e5e5e5, #ed686f, #eaebed, #fbfcfc, #398cd3, #262933, #5294e2, #0000ff, #d7d8dd, #2b2f3b, #f13039, #999999, #1f1f1f, #50dbb5, #525252, #ff2121, #f27835, #91949c, #adafb5, #3b3c3e, #d3d4d8, #525d76, #434652, #cacaca, #2d323d, #f9fafb, #617c95, #ededed, #1a1a1a, #d8354a, #90949e, #313541, #a8a8a8, #dbdfe3, #cecece, #0f0f0f, #1d242a, #b8babf, #0f1116, #eef4fc, #e2e7ef, #d3dae3".split(", "))
__test(colors)
I've been trying to code the snake game with pyglet and I have everything worked out except for one problem, and that problem is that I can't figure out how to have the snake actually turn instead of just rotate 90 degrees. My current code makes the snake always move the direction the head is facing, however, when you turn the snake, it makes a full 90 degree turn instead of doing what the snake normally does in for example the google doodle snake game, and I can't figure out why. Does anyone have any ideas? (FYI I am pretty new to python, so my code may be very ugly.)
# Modules
import pyglet as pyg
import random
import math
from pyglet.window import key
from time import sleep
# Creating the window, sprites, and labels
window = pyg.window.Window(800,600)
snake_head_image = pyg.image.load('snake_head.png')
snake_head_image.anchor_x = 12
snake_head_image.anchor_y = 12
snake_body_image = pyg.image.load('snake_body.png')
snake_body_image.anchor_x = 12
snake_body_image.anchor_y = 12
snake_head = pyg.sprite.Sprite(snake_head_image,x=400,y=300)
snake_bodies = [pyg.sprite.Sprite(snake_body_image,x=snake_head.x,y=snake_head.y-25),pyg.sprite.Sprite(snake_body_image,x=snake_head.x,y=snake_head.y)]
apple = pyg.shapes.Circle(x=random.randint(10,790),y=random.randint(10,590),radius=10,color=(255,0,0))
keys = key.KeyStateHandler()
window.push_handlers(keys)
score = pyg.text.Label(f"Score: {len(snake_bodies)}",font_size=12,x=760,y=590,anchor_x='center',anchor_y='center')
end = pyg.text.Label("",font_size=36,x=400,y=300,anchor_x='center',anchor_y='center')
#window.event
def on_draw():
window.clear()
apple.draw()
snake_head.draw()
snake_bodies[0].draw()
for z in range(len(snake_bodies)):
snake_bodies[z].draw()
score.draw()
end.draw()
# Rotating the snake on key press
#window.event
def on_key_press(symbol,modifiers):
if (symbol == pyg.window.key.LEFT) and snake_head.rotation != 90:
snake_head.rotation = 270
snake_bodies[0].rotation = 270
snake_bodies[0].y = snake_head.y
snake_bodies[0].x = snake_head.x + 25
elif (symbol == pyg.window.key.RIGHT) and snake_head.rotation != 270:
snake_head.rotation = 90
snake_bodies[0].rotation = 90
snake_bodies[0].y = snake_head.y
snake_bodies[0].x = snake_head.x - 25
elif (symbol == pyg.window.key.UP) and snake_head.rotation != 180:
snake_head.rotation = 0
snake_bodies[0].rotation = 0
snake_bodies[0].y = snake_head.y - 25
snake_bodies[0].x = snake_head.x
elif (symbol == pyg.window.key.DOWN) and snake_head.rotation != 0:
snake_head.rotation = 180
snake_bodies[0].rotation = 180
snake_bodies[0].y = snake_head.y + 25
snake_bodies[0].x = snake_head.x
# Always making the snake move forward
#window.event
def moveSnake(dt):
if snake_head.rotation == 270:
snake_head.x -= 3
snake_bodies[0].x -= 3
for z in range(len(snake_bodies)):
if z != 0:
snake_bodies[z].x = snake_bodies[z-1].x + 25
snake_bodies[z].y = snake_bodies[z-1].y
snake_bodies[z].rotation = snake_bodies[0].rotation
else:
pass
elif snake_head.rotation == 90:
snake_head.x += 3
snake_bodies[0].x += 3
for z in range(len(snake_bodies)):
if z != 0:
snake_bodies[z].x = snake_bodies[z-1].x - 25
snake_bodies[z].y = snake_bodies[z-1].y
snake_bodies[z].rotation = snake_bodies[0].rotation
else:
pass
elif snake_head.rotation == 0:
snake_head.y += 3
snake_bodies[0].y += 3
for z in range(len(snake_bodies)):
if z != 0:
snake_bodies[z].x = snake_bodies[z-1].x
snake_bodies[z].y = snake_bodies[z-1].y - 25
snake_bodies[z].rotation = snake_bodies[0].rotation
else:
pass
elif snake_head.rotation == 180:
snake_head.y -= 3
snake_bodies[0].y -= 3
for z in range(len(snake_bodies)):
if z != 0:
snake_bodies[z].x = snake_bodies[z-1].x
snake_bodies[z].y = snake_bodies[z-1].y + 25
snake_bodies[z].rotation = snake_bodies[0].rotation
else:
pass
# Collisions with the apple and the borders
distance_x_apple = snake_head.x - apple.x
distance_y_apple = snake_head.y - apple.y
distance_x_upper_border = snake_head.x - window.width
distance_y_upper_border = snake_head.y - window.height
distance_x_lower_border = snake_head.x - 0
distance_y_lower_border = snake_head.y - 0
if 10 >= abs(distance_x_apple) and 10 >= abs(distance_y_apple):
apple.x = random.randint(10,790)
apple.y = random.randint(10,590)
if snake_head.rotation == 270:
snake_bodies.append(pyg.sprite.Sprite(snake_body_image,x=snake_bodies[len(snake_bodies)-1].x-25,y=snake_bodies[len(snake_bodies)-1].y))
snake_bodies[-1].rotation = 270
elif snake_head.rotation == 90:
snake_bodies.append(pyg.sprite.Sprite(snake_body_image,x=snake_bodies[len(snake_bodies)-1].x+25,y=snake_bodies[len(snake_bodies)-1].y))
snake_bodies[-1].rotation = 90
elif snake_head.rotation == 180:
snake_bodies.append(pyg.sprite.Sprite(snake_body_image,x=snake_bodies[len(snake_bodies)-1].x,y=snake_bodies[len(snake_bodies)-1].y-25))
snake_bodies[-1].rotation = 180
elif snake_head.rotation == 0:
snake_bodies.append(pyg.sprite.Sprite(snake_body_image,x=snake_bodies[len(snake_bodies)-1].x,y=snake_bodies[len(snake_bodies)-1].y+25))
snake_bodies[-1].rotation = 0
score.text = f"Score: {len(snake_bodies)}"
if 5 >= abs(distance_x_upper_border) or 5 >= abs(distance_y_upper_border) or 5 >= abs(distance_x_lower_border) or 5>= abs(distance_y_lower_border):
snake_head.visible = False
for z in range(len(snake_bodies)):
snake_bodies[z].visible = False
sleep(0.3)
end.text = f"Game Over!\nScore: {len(snake_bodies)}"
pyg.clock.schedule_interval(moveSnake, 1 / 60)
pyg.app.run()
You have probably already done it, except because everything doesn't move in cells, and there is no time between snake's head and snake's body updating and moving, it is turning itself so fast that you cannot see it. You can either keep it without cells and make time intervals in between turning, or create cells and it makes everything much easier.
Either that your you have your turning done wrong. I am not sure if your code is doing this already, but if you keep it without cells you need to 1. save position of head on turning and 2. iterate through the body pieces and make the the last one follow the next piece.
I will probably try to fix the code and post it here later.
(I cannot comment because I have less than 50 reputation, even though this should have been a comment. Hope this helped in some way)
hello I try to make an app- personality test, but i have a problem with evaluation,..
there is a dificult evaluation of test but in short in theese reduce version you just write some values into a given variable, and i want to delete every 0 value from list as a result.. I tried it (programe after # but there is an error), could anybody please help me?
error
File "C:/Users/Stanko/PycharmProjects/pythonProjectDISK/main.py", line 73, in dele
self._data[self.item.key]= list(filter(lambda num: num != 0, self._data[self.item.key]))
AttributeError: 'Test' object has no attribute 'item'
here is a reduce program
class Empty(Exception):
pass
class PriorityVal(ABC):
class _Item:
def __init__(self, key, value):
self.key, self.value = key, value
def __lt__(self, other):
return self.key < other.key
def __repr__(self):
return str((self.key, self.value))
#abstractmethod
def add(self, key, value):
pass
#abstractmethod
def max(self):
pass
#abstractmethod
def min(self):
pass
#abstractmethod
def remove_min(self):
pass
class Test(PriorityVal):
def __init__(self):
self._data = []
def add(self, key, value):
self._data.append(self._Item(key, value))
def max(self):
index = self.find_max()
item = self._data[index]
return item.key, item.value
def find_max(self):
index = 0
for i in range(1, len(self._data)):
if self._data[index] < self._data[i]:
index = i
return index
def _find_min(self):
index = 0
for i in range(1, len(self._data)):
if self._data[i] < self._data[index]:
index = i
return index
def min(self):
index = self._find_min()
item = self._data[index]
return item.key, item.value
def remove_min(self):
index = self._find_min()
item = self._data.pop(index)
return item.key, item.value
def dele(self):
self._data[self.item.key]= list(filter(lambda num: num != 0, self._data[self.item.key]))
test = str(input("test name"))
test = Test()
dzadane = int(input("input d"))
if dzadane <= 0:
dh = 0
elif 0 < dzadane <= 4:
dh = 60
elif 4 < dzadane <= 7:
dh = 70
elif 7 < dzadane <= 12:
dh = 80
elif 12 < dzadane <= 15:
dh = 90
else:
dh = 100
test.add(dh, "d")
izadane = int(input("input i"))
if izadane <= -1:
ih = 0
elif -1 < izadane <= 1:
ih = 60
elif 1 < izadane <= 3:
ih = 70
elif izadane == 4:
ih = 75
elif 4 < izadane <= 6:
ih = 80
elif izadane == 7:
ih = 85
elif 7 < izadane <= 9:
ih = 90
else:
dh = 100
test.add(ih, "i")
szadane = int(input("input s"))
if szadane <= -2:
sh = 0
elif -2 < szadane <= 0:
sh = 60
elif 0 < szadane <= 3:
sh = 70
elif 4 < szadane <= 7:
sh = 80
elif szadane == 8:
sh = 85
elif 8 < szadane <= 10:
sh = 90
else:
sh = 100
test.add(sh, "s")
kzadane = int(input("input k"))
if kzadane <= -3:
kh = 0
elif -3 < kzadane <= 1:
kh = 60
elif -1 < kzadane <= 1:
kh = 70
elif 1 < kzadane <= 4:
kh = 80
elif 4 < kzadane <= 7:
kh = 90
else:
kh = 100
test.add(kh, "k")
nzadane = int(input("input n"))
nh = 0
test.add(nh, "n")
print(dzadane, izadane, szadane, kzadane, nzadane, )
print("test", test._data)
print('max=', test.max())
print( "del all 0", test.dele())
print("test", test._data)
You could try
self._data = [value for value in self._data if value.key != 0]