Skip to content

Instantly share code, notes, and snippets.

@iminurnamez
Created January 30, 2016 00:48
Show Gist options
  • Save iminurnamez/64bf7d3c31613434ba46 to your computer and use it in GitHub Desktop.
Save iminurnamez/64bf7d3c31613434ba46 to your computer and use it in GitHub Desktop.
import pygame
import sys
from pygame.locals import *
def move(x, y, direction, matrix):
steps = [0, 0]
vx = directs[direction][0]
vy = directs[direction][1]
try:
cell = matrix[y + vy][x + vx]
if cell == "f":
steps[0] += vx
steps[1] += vy
elif cell == "i":
while matrix[y + steps[1] + vy][x + steps[0] + vx] == "i":
steps[0] += vx
steps[1] += vy
else:
if matrix[y + steps[1] + vy][x + steps[0] + vx] == "f":
steps[0] -= vx
steps[1] -= vy
except IndexError:
return [0, 0]
return steps
data = []
matrix = []
with open("data.txt") as file:
for line in file:
data.append(line)
ymatrix = int(data[0][0:2])
xmatrix = int(data[0][3:5])
del data[0]
starty = int(data[0][0:2])
startx = int(data[0][3:5])
del data[0]
charx = startx
chary = starty
#this will hold the distance the player should move
char_movement = [0, 0]
pygame.init()
setdisplay = pygame.display.set_mode((xmatrix*16, ymatrix*16))
pygame.display.set_caption ("game")
background = pygame.image.load("background.png")
char = pygame.image.load("char.png")
fps = 30
fpsTime = pygame.time.Clock()
for line in data:
matrix.append(line.strip().split(" "))
move_keys = {K_UP: "up",
K_DOWN: "down",
K_LEFT: "left",
K_RIGHT: "right"}
directs = {"up": (0, -1),
"down": (0, 1),
"left": (-1, 0),
"right": (1, 0)}
while True:
setdisplay.blit(background, (0, 0))
setdisplay.blit(char, (charx * 16, chary * 16))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key in move_keys:
#if player isn't already moving
if not any(char_movement):
direction = move_keys[event.key]
steps = move(charx, chary, direction, matrix)
#bank the amount the player shopuld move instead of
#moving all at once
char_movement[0] += steps[0]
char_movement[1] += steps[1]
#amount to move this frame on each axis
#possible values will be -1, 0, and 1
dx, dy = 0, 0
if char_movement[0]:
dx = char_movement[0] / abs(char_movement[0])
if char_movement[1]:
dy = char_movement[1] / abs(char_movement[1])
#subtract movement from the "bank"
char_movement[0] -= dx
char_movement[1] -= dy
#and spend it on moving the character
charx += dx
chary += dy
pygame.display.update()
fpsTime.tick(fps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment