Allow concurrent keypresses

This commit is contained in:
PAlexanderFranklin 2023-05-17 02:06:36 -07:00
parent 5c47f23479
commit 5fdeabed69

View File

@ -23,8 +23,7 @@ class Player:
self.x = x self.x = x
self.y = y self.y = y
self.color = color self.color = color
self.keys = keys commands = {
self.commands = {
"n": lambda: self.move(0,-1), "n": lambda: self.move(0,-1),
"ne": lambda: self.move(1,-1), "ne": lambda: self.move(1,-1),
"e": lambda: self.move(1,0), "e": lambda: self.move(1,0),
@ -34,53 +33,58 @@ class Player:
"w": lambda: self.move(-1,0), "w": lambda: self.move(-1,0),
"nw": lambda: self.move(-1,-1), "nw": lambda: self.move(-1,-1),
} }
self.commands = []
for key in keys:
self.commands.append((key[0], commands[key[1]]))
self.sprite = pygame.Rect((tile*x)+2,(tile*y)+2,tile-2,tile-2) self.sprite = pygame.Rect((tile*x)+2,(tile*y)+2,tile-2,tile-2)
def useKeys(self, keys):
try:
for command in self.commands:
if keys[command[0]]:
command[1]()
except:
pass
def move(self, x, y): def move(self, x, y):
self.x += x self.x += x
self.y += y self.y += y
players = [] players = []
players.append(Player(25, 20, red, { players.append(Player(25, 20, red, [
pygame.K_w: "n", (pygame.K_w, "n"),
pygame.K_e: "ne", (pygame.K_e, "ne"),
pygame.K_d: "e", (pygame.K_d, "e"),
pygame.K_c: "se", (pygame.K_c, "se"),
pygame.K_x: "s", (pygame.K_x, "s"),
pygame.K_z: "sw", (pygame.K_z, "sw"),
pygame.K_a: "w", (pygame.K_a, "w"),
pygame.K_q: "nw" (pygame.K_q, "nw"),
})) ]))
players.append(Player(25, 20, green, { players.append(Player(25, 20, green, [
pygame.K_KP_8: "n", (pygame.K_KP_8, "n"),
pygame.K_KP_9: "ne", (pygame.K_KP_9, "ne"),
pygame.K_KP_6: "e", (pygame.K_KP_6, "e"),
pygame.K_KP_3: "se", (pygame.K_KP_3, "se"),
pygame.K_KP_2: "s", (pygame.K_KP_2, "s"),
pygame.K_KP_1: "sw", (pygame.K_KP_1, "sw"),
pygame.K_KP_4: "w", (pygame.K_KP_4, "w"),
pygame.K_KP_7: "nw" (pygame.K_KP_7, "nw"),
})) ]))
game_font = pygame.font.Font("freesansbold.ttf",32) game_font = pygame.font.Font("freesansbold.ttf",32)
pygame.key.set_repeat(300, 40)
while True: while True:
for event in pygame.event.get(): for event in pygame.event.get():
if event.type == pygame.QUIT: if event.type == pygame.QUIT:
pygame.quit() pygame.quit()
sys.exit() sys.exit()
if event.type == pygame.KEYDOWN:
for player in players:
try:
player.commands[player.keys[event.key]]()
except:
pass
keys = pygame.key.get_pressed() keys = pygame.key.get_pressed()
for player in players:
player.useKeys(keys)
# Rendering # Rendering
screen.fill(bg_color) screen.fill(bg_color)
for player in players: for player in players: