This question already has answers here:
Not letting the character move out of the window
(2 answers)
Closed 1 year ago.
When my player hits one of the boundaries with the value 0 it is perfectly fine and can move freely throughout the world. But when my player hits a boundary with the value 485, it fine until you try and move up. Then depending on the boundary you hit it will get stuck at playerX = 249 or playerY = 249
import pygame
import time
pygame.init()
playerX = 250 # Player X locale
playerY = 250 # Players Y locale
playerSpeed = 2
backgroundX = 0 # Background X locale
backgroundY = 0 # Background Y locale
### LOADS PLAYER IMAGES ###
playerFrontImg = pygame.image.load("Images/Player Images/playerBackOne.png")
playerBackImg = pygame.image.load("Images/Player Images/playerFrontOne.png")
playerLeftImg = pygame.image.load("Images/Player Images/playerLeftOne.png")
playerRightImg = pygame.image.load("Images/Player Images/playerRightOne.png")
playerCurrentImg = playerFrontImg
### LOADS PLAYER IMAGES ###
### LOADS MAP IMAGES ###
testMap = pygame.image.load("Images/Map Images/TEST_MAP.png")
### LOADS MAP IMAGES ###
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
### KEYBOARD INPUTS AND MOVEMENTS ###
keys = pygame.key.get_pressed() # gets pressed keys and assigns it TRUE or FALSE
if keys[pygame.K_w]: # Checks if "w" is pressed
playerCurrentImg = playerFrontImg # Changes current image to correct image
if playerY == 250:
if backgroundY < 0:
backgroundY += playerSpeed
if backgroundY >= 0 or playerY > 250:
playerY -= playerSpeed
if playerY <= 0:
playerY = 0
if keys[pygame.K_s]: # Checks if "s" is pressed
playerCurrentImg = playerBackImg # Changes current image to correct image
if playerY == 250:
if backgroundY > -500:
backgroundY -= playerSpeed
if backgroundY <= -500 or playerY < 250:
playerY += playerSpeed
if playerY >= 485:
playerY = 485 # THIS SEEMS TO BE WHERE THE ISSUE IS
if keys[pygame.K_a]:
playerCurrentImg = playerLeftImg # Changes current image to correct image
if playerX == 250:
if backgroundX < 0:
backgroundX += playerSpeed
if backgroundX >= 0 or playerX > 250:
playerX -= playerSpeed
if playerX <= 0:
playerX = 0
if keys[pygame.K_d]:
playerCurrentImg = playerRightImg # Changes current image to correct image
if playerX == 250:
if backgroundX > -500:
backgroundX -= playerSpeed
if backgroundX <= -500 or playerX < 250:
playerX += playerSpeed
if playerX >= 485:
playerX = 485
if keys[pygame.K_f]: # TROUBLE SHOOTING KEY
print(playerX, playerY, "\n", backgroundX, backgroundY)
time.sleep(1)
### KEYBOARD INPUTS AND MOVEMENTS ###
screen.blit(testMap, (backgroundX, backgroundY))
screen.blit(playerCurrentImg, (playerX, playerY))
pygame.display.update()
pygame.quit()
quit()
A case of a single symbol.
The critical code is this:
if keys[pygame.K_w]: # Checks if "w" is pressed
playerCurrentImg = playerFrontImg # Changes current image to correct image
if playerY == 250:
if backgroundY < 0:
backgroundY += playerSpeed
if backgroundY >= 0 or playerY > 250:
playerY -= playerSpeed
if playerY <= 0:
playerY = 0
It is meant to be playerY <= 250 and it is also best pratices to use and instead of nested ifs. Your code should look like this.
if keys[pygame.K_w]: # Checks if "w" is pressed
playerCurrentImg = playerFrontImg # Changes current image to correct image
if playerY <= 250 and backgroundY < 0:
backgroundY += playerSpeed
if backgroundY >= 0 or playerY > 250:
playerY -= playerSpeed
if playerY <= 0:
playerY = 0
Related
I'm kind of new to this site and pygame and I was hoping for a bit of help. So I made this space invader clone which is about 180 lines right, when I run it on Pycharm, it works fine. So I decided to try testing it out further and tried converting it into an .exe file which is where my troubles began. Every time I try running the .exe, this message appears
Traceback (most recent call last):
File "main.py", line 62, in <module>
font = pygame.font.Font('freesansbold.ttf',32)
TypeError: expected str, bytes or os.PathLike object, not BytesIO
I used freeCodeCamp.org's template and applied my own customs, here's a video incase you're interested: https://www.youtube.com/watch?v=FfWpgLFMI7w&t=7041s
Here's the code as well:
import math
import random
import pygame
from pygame import mixer
# Initialize the pygame
pygame.init()
# Create the screen
screen = pygame.display.set_mode((600, 400))
# Background Sound
mixer.music.load('Here he comes.mp3')
mixer.music.play(-1)
# Title and icon
pygame.display.set_caption("Defender of The Blue")
icon = pygame.image.load("Submarine of Vengeance.png")
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('Protagonist.png')
playerX = 250
playerY = 300
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('Antagonist.png'))
enemyX.append(random.randint(0, 500))
enemyY.append(random.randint(10, 100))
enemyX_change.append(0.1)
enemyY_change.append(20)
# Energy Blast
# Ready - You can't see the bullet state on the screen
# Fire - The blast is currently moving
energyblastImg = pygame.image.load('energy-blasts.png')
energyblastX = 0
energyblastY = 300
energyblastX_change = 0
energyblastY_change = 1
energyblast_state = "ready"
# score
score_value = 0
font = pygame.font.Font('freesansbold.ttf',32)
textX = 10
textY = 10
game_over_font = pygame.font.Font('freesansbold.ttf',50)
# Game Over Text
def show_score(x,y):
score = font.render("Score :" + str(score_value),True, (250,100,0))
screen.blit(score, (x, y))
def game_over_text():
game_over_text = game_over_font.render("GAME OVER",True, (250,0,0))
screen.blit(game_over_text, (150, 100))
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y))
def fire_energyblast(x, y):
global energyblast_state
energyblast_state = "fire"
screen.blit(energyblastImg, (x + -1, y + 10))
def isCollison(enemyX, enemyY, energyblastX, energyblastY):
distance = math.sqrt((math.pow(enemyX - energyblastX, 2)) + (math.pow(enemyY - energyblastY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
running = True
while running:
# RGB = Red, Green, Blue
screen.fill((0, 0, 128))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -1
if event.key == pygame.K_RIGHT:
playerX_change = 1
if event.key == pygame.K_SPACE:
if energyblast_state is "ready":
energyblast_sound = mixer.Sound('Energy Blast.mp3')
energyblast_sound.play()
# Get the current x coordinate of the submarine
energyblastX = playerX
fire_energyblast(energyblastX, energyblastY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# 5 = 5 + -0.1 -> 5 = 5 - 0.1
# 5 = 5 + 0.1
# Checking for boundaries of submarine so it doesn't go out of bounds
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 500:
playerX = 500
# enemy movement
for i in range(num_of_enemies):
# Game Over
if enemyY[i] > 272:
for j in range(num_of_enemies):
enemyY[j] = 2000
game_over_text()
break
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 1
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 500:
enemyX_change[i] = -1
enemyY[i] += enemyY_change[i]
# Collision
collison = isCollison(enemyX[i], enemyY[i], energyblastX, energyblastY)
if collison:
explosion_Sound = mixer.Sound('Explode.mp3')
explosion_Sound.play()
energyblastY = 300
energyblast_state = "ready"
score_value += 50
enemyX[i] = random.randint(0, 500)
enemyY[i] = random.randint(10, 100)
enemy(enemyX[i],enemyY[i], i)
# energy blast movement
if energyblastY <= 0:
energyblastY = 300
energyblast_state = "ready"
if energyblast_state is "fire":
fire_energyblast(energyblastX, energyblastY)
energyblastY -= energyblastY_change
player(playerX, playerY)
show_score(textX,textY)
pygame.display.update()
I'm not quite sure what BytesIO is. Is it like having something used twice and cancels out? How can I change this?
Are you certain that "freesansbold.ttf" is downloaded and in the same directory as the code youre trying to run, if this isnt possible for whatever reason you should be able to replace the
font = pygame.font.Font('freesansbold.ttf',32)
with
font = pygame.font.Font('(file path)freesansbold.ttf',32)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Here is a source code of my space-arcade pygame. It's a quite simple one and doesn't shoots bullets. Only that we can move the player with the obstacles being moved as well. However, the limit for the spaceship (player) to move in the screen has been set from x = 0 to x = 765 and from y = 200 to y = 480. But the spaceship somehow cross the limit for y-axis i.e it can move beyond y = 0 and y = 600, but only at some specific x-axis like when x is 10 and 590 something. How can i fix this gap in the following python code:
import random
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("space-invaders.png")
pygame.display.set_icon(icon)
background = pygame.image.load("background.png")
player_image = pygame.image.load("space-invaders.png")
playerX = 370
playerY = 480
playerX_change = 0
playerY_change = 0
def player(x, y):
screen.blit(player_image, (x, y))
obs_image = pygame.image.load("cave-painting (1).png")
obsX = random.randint(0, 800)
obsY = random.randint(0, 100)
obsX_change = 2
obsY_change = 0.3
def obstacle(x, y):
screen.blit(obs_image, (x, y))
running = True
while running:
screen.fill( (0, 0,0) )
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -4
if event.key == pygame.K_RIGHT:
playerX_change = 4
if event.key == pygame.K_UP:
playerY_change = -4
if event.key == pygame.K_DOWN:
playerY_change = 4
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerX += playerX_change
playerY += playerY_change
# Stopping our player beyond screen:
if playerX <= 0:
playerX = 0
elif playerX >= 765:
playerX = 765
elif playerY <= 200:
playerY = 200
elif playerY >= 480:
playerY = 480
obsX += obsX_change
obsY += obsY_change
# Movement mechanics for obstacles:
if obsX <= 0:
obsX_change = 3
obsY += obsY_change
elif obsX >= 736:
obsX_change = -3
obsY += obsY_change
player(playerX, playerY)
obstacle(obsX, obsY)
pygame.display.update()```
Here are the source pictures used in the aforementioned code:
[background][1]
[cave-painting (1)][2]
[space-invaders][3]
[1]: https://i.stack.imgur.com/EZFLs.png
[2]: https://i.stack.imgur.com/CxNs4.png
[3]: https://i.stack.imgur.com/Z97n7.png
Don't use elif. You're code says (pseudocode):
If x is beyond or equal to 0 then go back to zero
If x is not beyond or equal to 0 but x is beyond or equal to 765 then go back to 765
If none of the above are true but y is beyond or equal to 200 then go back to 200
Do you see the problem? If x is equal to 0, then the y-checks never occur. Change the third elif to if to fix this issue. Here's the fixed code:
if playerX <= 0:
playerX = 0
elif playerX >= 765:
playerX = 765
if playerY <= 200:
playerY = 200
elif playerY >= 480:
playerY = 480
These comparisons should be independent from each other.
By chaining then in a single if/elif/elif/... block, the checks
beyond the first only take place if the first check fails, and so on.
Given the nature of your problem, this is likely the cause.
Just replace the elif statements by plain ifs: each check will
run independently and fix the limits it should guard:
# Stopping our player beyond screen:
if playerX <= 0:
playerX = 0
elif playerX >= 765:
playerX = 765
elif playerY <= 200:
playerY = 200
elif playerY >= 480:
playerY = 480
You can simplify you code. Use pygame.key.get_pressed() to move the player smoothly, rather than the keyboard events KEYDOWN and KEYDUP. pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False:
keys = pygame.key.get_pressed()
playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 4
playerY += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 4
Use pygame.Rect objects and pygame.Rect.clamp() respectively pygame.Rect.clamp_ip() to limit the position of the player to a rectangular area.
border_rect = pygame.Rect(0, 200, 800, 312)
player_rect = player_image.get_rect(topleft = (playerX, playerY))
player_rect.clamp_ip(border_rect)
playerX, playerY = player_rect.topleft
Or even shorter:
keys = pygame.key.get_pressed()
playerX, playerY = player_image.get_rect(topleft = (playerX, playerY)) \
.move((keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 4, \
(keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 4) \
.clamp((0, 200, 800, 312)).topleft
Example code:
running = True
while running:
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * 4
playerY += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * 4
border_rect = pygame.Rect(0, 200, 800, 312)
player_rect = player_image.get_rect(topleft = (playerX, playerY))
player_rect.clamp_ip(border_rect)
playerX, playerY = player_rect.topleft
obsX += obsX_change
obsY += obsY_change
# Movement mechanics for obstacles:
if obsX <= 0:
obsX_change = 3
obsY += obsY_change
elif obsX >= 736:
obsX_change = -3
obsY += obsY_change
player(playerX, playerY)
obstacle(obsX, obsY)
pygame.display.update()
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Im following a tutorial to code a game, as far as i can tell, my code is the same as the one in the tutorial, ive been working at this for about 45mins, and checked over the code twice, but here is the code
import pygame
import math
import random
# Intialize the Pygame
pygame.init()
# Create the Screen
screen = pygame.display.set_mode((800, 600))
# Background
background = pygame.image.load("space.png")
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("alien.png")
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load("player.png")
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load("enemy.png"))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(30)
# Bullet
# Ready - You can't see the bullet on the screen
# Fire_ The bullet is currently moving
bulletImg = pygame.image.load("bullet.png")
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 15
bullet_state = "ready"
score = 0
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 16, y + 10))
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2))
if distance < 27:
return True
else:
return False
# Game Loop
running = True
while running:
# RGB - Red, Green, Blue
screen.fill((0, 0, 0))
# Background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Checking for boundaries for space ship
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy movement
for i in range(num_of_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 4
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 736:
enemyX_change[i] = -4
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
pygame.display.update()
Here is the error im getting:
line 70
if distance < 27:
^
SyntaxError: invalid syntax
Process finished with exit code 1
Im new to python, so it might be something stupid that i forgot, but i cannot figure this out.
You miss a close bracket:
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
I am making a space invader like game, everything works fine, but ever since I added multiple enemies using a list, their images/sprites disappeared and only reappear once hit for a second and than disappear once more.
I've checked, the image file is fine, and as far as I can see nothing unusual is happening behind the since as well, and the score adds up fine whenever an enemy is hit.
What might be the issue?
import pygame
import random
import math
# Initializing pygame
pygame.init()
# Screen creation and config
screen = pygame.display.set_mode((1024, 600))
# Background
background = pygame.image.load('court_level_bg.jpg')
# Title and Icon
pygame.display.set_caption("Space Invaders")
# Player config
player_img = pygame.image.load('Mini_Bibi.png')
playerX = 430
playerY = 480
playerX_change = 0
# Enemy config
enemy_img = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_enemies = 5
for i in range(num_enemies):
enemy_img.append(pygame.image.load('Enemy1.png'))
enemyX.append(random.randint(0, 1024))
enemyY.append(random.randint(5, 150))
enemyX_change.append(1.5)
enemyY_change.append(40)
# Bullet config
bullet_img = pygame.image.load('Weapon.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 6
bullet_state = "ready"
score = 0
# Create player
def player(x, y):
screen.blit(player_img, (x, y))
# Create enemy
def enemy(x, y, i):
screen.blit(enemy_img[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bullet_img, (x + 16, y + 10))
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
scrn_stat = True
while scrn_stat:
# Screen RGB color config
screen.fill((0, 0, 0))
# Background image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
scrn_stat = False
# X axis Keystroke listening
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -4
if event.key == pygame.K_RIGHT:
playerX_change = 4
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
# Player boundaries
if playerX <= 0:
playerX_change = 0;
elif playerX >= 945:
playerX_change = 0;
# Enemy movement
for i in range(num_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 3
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 945:
enemyX_change[i] = -3
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 945)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "ready"
if bullet_state is "fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
pygame.display.update()
enemy() has to be called for each enemy in every frame, rather than in case of a collision only. It is an Indentation issue:
for i in range(num_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 0:
enemyX_change[i] = 3
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 945:
enemyX_change[i] = -3
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = "ready"
score += 1
print(score)
enemyX[i] = random.randint(0, 945)
enemyY[i] = random.randint(50, 150)
#<--|
enemy(enemyX[i], enemyY[i], i)
I'm trying to make a basic roguelike and following this tutorial: http://www.roguebasin.com/index.php?title=Complete_Roguelike_Tutorial,_using_python3%2Blibtcod,_part_1
I tried to make a character respond to mouse movements using libtcod. I followed the tutorial and all was going well, my character appeared on the screen, but for some reason the program crashes when I try to execute a movement command. For reference, my code is here:
import libtcodpy as tcod
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
LIMIT_FPS = 20
font_path = 'arial10x10.png' # this will look in the same folder as this script
font_flags = tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD # the layout may need to change with a different font file
tcod.console_set_custom_font(font_path, font_flags)
window_title = 'Python 3 libtcod tutorial'
fullscreen = False
tcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, window_title, fullscreen)
playerx = SCREEN_WIDTH // 2
playery = SCREEN_HEIGHT // 2
def handle_keys():
# movement keys
key = tcod.console_check_for_keypress()
if tcod.console_is_key_pressed(tcod.KEY_UP):
playery = playery - 1
elif tcod.console_is_key_pressed(tcod.KEY_DOWN):
playery = playery + 1
elif tcod.console_is_key_pressed(tcod.KEY_LEFT):
playerx = playerx - 1
elif tcod.console_is_key_pressed(tcod.KEY_RIGHT):
playerx = playerx + 1
while not tcod.console_is_window_closed():
tcod.console_set_default_foreground(0, tcod.white)
tcod.console_put_char(0, playerx, playery, '#', tcod.BKGND_NONE)
tcod.console_flush()
exit = handle_keys()
if exit:
break
I posted the question to another forum and they said I should define playerx and playery as global, so I added that to the handle_keys() function but then it just crashes on startup.
Here is the fix, in the handle_keys function:
You were missing a global assignment as well, and using an incorrect check for key values
def handle_keys():
global playerx, playery
# movement keys
key = tcod.console_check_for_keypress()
if key.vk == tcod.KEY_UP:
playery = playery - 1
elif key.vk == tcod.KEY_DOWN:
playery = playery + 1
elif key.vk == tcod.KEY_LEFT:
playerx = playerx - 1
elif key.vk == tcod.KEY_RIGHT:
playerx = playerx + 1
By the way, there is now an updated python3 tutorial here: http://rogueliketutorials.com