I'm writing a roguelike with libtcodpy. It works, but when I run this listing: http://kooneiform.wordpress.com/2009/03/29/241/ at the bottom of the page is a full listing and a few others I've tried, I get errors such as this:
FYI I'm on Windows and do have the libtcodpy.py, SDL.dll, libtcod-mingw.dll files and they do work when following the tutorial that is most popular for libtcodpy.
For the listing above I receive this specific error:
$ python roguelike_practice2.py
Traceback (most recent call last):
File "roguelike_practice2.py", line 165, in <module>
draw()
File "roguelike_practice2.py", line 98, in draw
libtcod.console_set_foreground_color(0, libtcod.white)
AttributeError: 'module' object has no attribute 'console_set_foreground_color'
I also on that same program encounter the exact same issue with console_set_background_color, console_print_left. None work. All with the same error.
For other listings such as this one:
#!/usr/bin/python
###imports###
import os
import libtcodpy as libtcod
###utility functions###
def get_key(key):
if key.vk == libtcod.KEY_CHAR:
return chr(key.c)
else:
return key.vk
###global constants and variables###
window_width = 46
window_height = 20
first = True
fov_px = 9
fov_py = 10
fov_recompute = True
fov_map = None
fov_colors = {
'dark wall' : libtcod.Color(0, 0, 100),
'light wall' : libtcod.Color(130, 110, 50),
'dark ground' : libtcod.Color(50, 50, 150),
'light ground' : libtcod.Color(200, 180, 50)
}
fov_init = False
fov_radius = 4
do = {
'up' : (0, -1),
'down' : (0, 1),
'right' : (1, 0),
'left' : (-1, 0)
}
keys = {
'i' : do['up'],
'k' : do['down'],
'j' : do['left'],
'l' : do['right'],
libtcod.KEY_UP : do['up'],
libtcod.KEY_KP8 : do['up']
}
smap = ['##############################################',
'####################### #################',
'##################### # ###############',
'###################### ### ###########',
'################## ##### ####',
'################ ######## ###### ####',
'############### #################### ####',
'################ ###### ##',
'######## ####### ###### # # # ##',
'######## ###### ### ##',
'######## ##',
'#### ###### ### # # # ##',
'#### ### ########## #### ##',
'#### ### ########## ###########=##########',
'#### ################## ##### #####',
'#### ### #### ##### #####',
'#### # #### #####',
'######## # #### ##### #####',
'######## ##### ####################',
'##############################################',
]
###drawing###
def draw():
global fov_px, fov_py, fov_map, first
global fov_init, fov_recompute, smap
if first:
wh = window_height
ww = window_width
first = False
libtcod.console_clear(0)
libtcod.console_set_fore(0, ww, wh, libtcod.white)
libtcod.console_print_left(0, 1, 1, libtcod.BKGND_NONE,
"IJKL : move around")
libtcod.console_set_fore(0, ww, wh, libtcod.black)
libtcod.console_put_char(0, fov_px, fov_py, '#',
libtcod.BKGND_NONE)
for y in range(window_height):
for x in range(window_width):
if smap[y][x] == '=':
libtcod.console_put_char(0, x, y,
libtcod.CHAR_DHLINE,
libtcod.BKGND_NONE)
if not fov_init:
fov_init = True
fov_map = libtcod.map_new(window_width, window_height)
for y in range(window_height):
for x in range(window_width):
if smap[y][x] == ' ':
libtcod.map_set_properties(fov_map, x, y, True, True)
elif smap[y][x] == '=':
libtcod.map_set_properties(fov_map, x, y, True, False)
if fov_recompute:
fov_recompute = False
libtcod.map_compute_fov(fov_map, fov_px, fov_py, fov_radius, True)
for y in range(window_height):
for x in range(window_width):
affect, cell = 'dark', 'ground'
if libtcod.map_is_in_fov(fov_map, x, y):
affect = 'light'
if (smap[y][x] == '#'):
cell = 'wall'
color = fov_colors['%s %s' % (affect, cell)]
libtcod.console_set_back(0, x, y, color, libtcod.BKGND_SET)
###game state updates###
def update(key):
global fov_py, fov_px, fov_recompute, smap
key = get_key(key)
if key in keys:
dx, dy = keys[key]
if smap[fov_py+dy][fov_px+dx] == ' ':
libtcod.console_put_char(0, fov_px, fov_py, ' ',
libtcod.BKGND_NONE)
fov_px = fov_px + dx
fov_py = fov_py + dy
libtcod.console_put_char(0, fov_px, fov_py, '#',
libtcod.BKGND_NONE)
fov_recompute = True
###initialization and main loop###
font = os.path.join('fonts', 'arial12x12.png')
libtcod.console_set_custom_font(font, libtcod.FONT_LAYOUT_TCOD | libtcod.FONT_TYPE_GREYSCALE)
libtcod.console_init_root(window_width, window_height, 'Python Tutorial', False)
while not libtcod.console_is_window_closed():
draw()
libtcod.console_flush()
key = libtcod.console_wait_for_keypress(True)
update(key)
if key.vk == libtcod.KEY_ESCAPE:
break
I receive the following errors, again I have all the needed files in the folder and am on Windows.
Error for listing 2:
Traceback (most recent call last):
File "roguelike_practice1.py", line 167, in <module>
draw()
File "roguelike_practice1.py", line 100, in draw
libtcod.console_set_fore(0, ww, wh, libtcod.white)
File "c:\Users\cshenkan\CloudStation\Programming\Libtcod\Project 2\libtcodpy.p
y", line 764, in console_set_fore
_lib.TCOD_console_set_fore(con, x, y, col)
File "c:\Python27\lib\ctypes\__init__.py", line 378, in __getattr__
func = self.__getitem__(name)
File "c:\Python27\lib\ctypes\__init__.py", line 383, in __getitem__
func = self._FuncPtr((name_or_ordinal, self))
AttributeError: function 'TCOD_console_set_fore' not found
I run into this TCOD_console_set_fore error a bunch. But say I comment that out, I get the same error but with another function such as TCOD_console_set_back, and others.
Not sure why I'm getting these errors. Using Python 2.7.9 32 bit, and libtcod 1.5.1 I believe. Running Windows 7 64 bit. Keep in mind I can get other programs to run that don't require any of those set_foreground and variation functions, or the print_left function or whatever other functions aren't working. But I'm sure it one or two issues affecting all the functions that wont work. \
If anyone has any ideas, I've spent a ton of time looking online to no avail for info. And the forum for libtcod takes days for administrator approval to join - lame.
Anyway thanks in advance! Ask me any questions or if you need clarification.
TCOD 1.5.1 renamed some functions, so that is why your two listings are crashing.
Version 1.5.1 renamed console_set_foreground_color to console_set_default_foreground,console_set_background_color to console_set_default_background, console_set_fore and console_set_back to console_set_char_foreground and console_set_char_background respectively, and console_wait_for_keypress has been replaced with sys_wait_for_event.
Also, console_print_left has been replaced by console_print_ex, which has an extra 'alignment' parameter between background and the string to print.
It appears that those functions were deprecated in 1.5.1. I can find them in 1.5.0, but neither in 1.5.1 nor 1.5.2. I think you would have to use console_print_ex or console_print_rect_ex instead.
Otherwise you could off course switch back to 1.5.0.
Related
The programming is displaying web cam footage to a monitor. I am trying to add a webserver to the program via flask. When I try to run the flask app it throws a GPIO device busy error. I had the webserver running separate from this code.
https://github.com/hall488/lockedin
Terminal Connected to Coral Dev Board
<me/mendel/lockedin$ python3 -m edgetpuvision.detect \
> --source /dev/video1:YUY2:864x480:20/1 \
> --model ${TEST_DATA}/ssd_mobilenet_v2_face_quant_postprocess_edgetpu.tflite
* Serving Flask app 'edgetpuvision.apps' (lazy loading)
* Environment: development
* Debug mode: on
* Running on all addresses (0.0.0.0)
WARNING: This is a development server. Do not use it in a production deployme
nt.
* Running on http://127.0.0.1:3000
* Running on http://128.46.192.239:3000 (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 623, in
_reopen
fcntl.ioctl(self._chip_fd, CdevGPIO._GPIO_GET_LINEHANDLE_IOCTL, request)
OSError: [Errno 16] Device or resource busy
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/mnt/home/mendel/lockedin/edgetpuvision/detect.py", line 50, in <module>
in1 = GPIO("/dev/gpiochip2", 9, "out") #pin 17
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 496, in
__init__
self._open(path, line, direction, edge, bias, drive, inverted, label)
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 547, in
_open
self._reopen(direction, edge, bias, drive, inverted)
File "/usr/local/lib/python3.7/dist-packages/periphery/gpio.py", line 625, in
_reopen
raise GPIOError(e.errno, "Opening output line handle: " + e.strerror)
periphery.gpio.GPIOError: [Errno 16] Opening output line handle: Device or resou
rce busy
mendel#elusive-mole:/mnt/home/mendel/lockedin$
Detect.py file where trying to implement webserver
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A demo which runs object detection on camera frames.
export TEST_DATA=/usr/lib/python3/dist-packages/edgetpu/test_data
Run face detection model:
python3 -m edgetpuvision.detect \
--model ${TEST_DATA}/mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite
Run coco model:
python3 -m edgetpuvision.detect \
--model ${TEST_DATA}/mobilenet_ssd_v2_coco_quant_postprocess_edgetpu.tflite \
--labels ${TEST_DATA}/coco_labels.txt
"""
import argparse
import colorsys
import itertools
import time
import sys
from flask import Flask, render_template, request
app = Flask(__name__)
from pycoral.adapters import detect
from pycoral.utils import edgetpu
from periphery import GPIO
from periphery import PWM
from . import svg
from . import utils
from .apps import run_app
#google "Coral GPIO"
in1 = GPIO("/dev/gpiochip2", 9, "out") #pin 17
in2 = GPIO("/dev/gpiochip4", 10, "out") #pin 18
pwm1 = PWM(0, 0) #pin32
in3 = GPIO("/dev/gpiochip0", 7, "out") #pin 29
in4 = GPIO("/dev/gpiochip0", 8, "out") #pin 31
pwm2 = PWM(1, 0) #pin33
CSS_STYLES = str(svg.CssStyle({'.back': svg.Style(fill='black',
stroke='black',
stroke_width='0.5em'),
'.bbox': svg.Style(fill_opacity=0.0,
stroke_width='0.1em')}))
def size_em(length):
return '%sem' % str(0.6 * (length + 1))
def color(i, total):
return tuple(int(255.0 * c) for c in colorsys.hsv_to_rgb(i / total, 1.0, 1.0))
def make_palette(keys):
return {key : svg.rgb(color(i, len(keys))) for i, key in enumerate(keys)}
def make_get_color(color, labels):
if color:
return lambda obj_id: color
if labels:
palette = make_palette(labels.keys())
return lambda obj_id: palette[obj_id]
return lambda obj_id: 'white'
def overlay(title, objs, get_color, labels, inference_time, inference_rate, layout):
x0, y0, width, height = layout.window
font_size = 0.03 * height
defs = svg.Defs()
defs += CSS_STYLES
doc = svg.Svg(width=width, height=height,
viewBox='%s %s %s %s' % layout.window,
font_size=font_size, font_family='monospace', font_weight=500)
doc += defs
# if len(objs) == 0:
# in1.write(False)
# in2.write(False)
# pwm1.frequency = 1e3
# pwm1.duty_cycle = .75
# pwm1.enable()
# in3.write(False)
# in4.write(False)
# pwm2.frequency = 1e3
# pwm2.duty_cycle = .75
# pwm2.enable()
for obj in objs:
color = get_color(obj.id)
inference_width, inference_height = layout.inference_size
bbox = obj.bbox.scale(1.0 / inference_width, 1.0 / inference_height).scale(*layout.size)
x, y, w, h = bbox.xmin, bbox.ymin, bbox.width, bbox.height
percent = int(100 * obj.score)
if labels:
caption = '%d%% %d %d %s' % (percent, bbox.xmin, bbox.ymin, labels[obj.id])
else:
caption = '%d %d' % (x + w/2, y + h/2)
motor_IO(x, y, w, h)
doc += svg.Rect(x=x, y=y, width=w, height=h,
style='stroke:%s' % color, _class='bbox')
doc += svg.Rect(x=x, y=y+h ,
width=size_em(len(caption)), height='1.2em', fill=color)
t = svg.Text(x=x, y=y+h, fill='black')
t += svg.TSpan(caption, dy='1em')
doc += t
ox = x0 + 20
oy1, oy2 = y0 + 20 + font_size, y0 + height - 20
# Title
if title:
doc += svg.Rect(x=0, y=0, width=size_em(len(title)), height='1em',
transform='translate(%s, %s) scale(1,-1)' % (ox, oy1), _class='back')
doc += svg.Text(title, x=ox, y=oy1, fill='white')
# Info
lines = [
'Objects: %d' % len(objs),
'Inference time: %.2f ms (%.2f fps)' % (inference_time * 1000, 1.0 / inference_time)
]
for i, line in enumerate(reversed(lines)):
y = oy2 - i * 1.7 * font_size
doc += svg.Rect(x=0, y=0, width=size_em(len(line)), height='1em',
transform='translate(%s, %s) scale(1,-1)' % (ox, y), _class='back')
doc += svg.Text(line, x=ox, y=y, fill='white')
return str(doc)
def motor_IO(x, y, w, h):
if x + w/2 > 400 :
in1.write(True)
in2.write(False)
pwm1.frequency = 1e3
pwm1.duty_cycle = .75
pwm1.enable()
else :
in1.write(False)
in2.write(True)
pwm1.frequency = 1e3
pwm1.duty_cycle = .75
pwm1.enable()
if y + h/2 > 400 :
in3.write(True)
in4.write(False)
pwm2.frequency = 1e3
pwm2.duty_cycle = .75
pwm2.enable()
else :
in3.write(False)
in4.write(True)
pwm2.frequency = 1e3
pwm2.duty_cycle = .75
pwm2.enable()
def print_results(inference_rate, objs):
print('\nInference (rate=%.2f fps):' % inference_rate)
for i, obj in enumerate(objs):
print(' %d: %s, area=%.2f' % (i, obj, obj.bbox.area))
def render_gen(args):
fps_counter = utils.avg_fps_counter(30)
interpreters, titles = utils.make_interpreters(args.model)
assert utils.same_input_image_sizes(interpreters)
interpreters = itertools.cycle(interpreters)
interpreter = next(interpreters)
labels = utils.load_labels(args.labels) if args.labels else None
filtered_labels = set(l.strip() for l in args.filter.split(',')) if args.filter else None
get_color = make_get_color(args.color, labels)
draw_overlay = True
width, height = utils.input_image_size(interpreter)
yield width, height
output = None
while True:
tensor, layout, command = (yield output)
inference_rate = next(fps_counter)
if draw_overlay:
start = time.monotonic()
edgetpu.run_inference(interpreter, tensor)
inference_time = time.monotonic() - start
objs = detect.get_objects(interpreter, args.threshold)[:args.top_k]
if labels and filtered_labels:
objs = [obj for obj in objs if labels[obj.id] in filtered_labels]
objs = [obj for obj in objs \
if args.min_area <= obj.bbox.scale(1.0 / width, 1.0 / height).area <= args.max_area]
if args.print:
print_results(inference_rate, objs)
title = titles[interpreter]
output = overlay(title, objs, get_color, labels, inference_time, inference_rate, layout)
else:
output = None
if command == 'o':
draw_overlay = not draw_overlay
elif command == 'n':
interpreter = next(interpreters)
def add_render_gen_args(parser):
parser.add_argument('--model',
help='.tflite model path', required=True)
parser.add_argument('--labels',
help='labels file path')
parser.add_argument('--top_k', type=int, default=50,
help='Max number of objects to detect')
parser.add_argument('--threshold', type=float, default=0.1,
help='Detection threshold')
parser.add_argument('--min_area', type=float, default=0.0,
help='Min bounding box area')
parser.add_argument('--max_area', type=float, default=1.0,
help='Max bounding box area')
parser.add_argument('--filter', default=None,
help='Comma-separated list of allowed labels')
parser.add_argument('--color', default=None,
help='Bounding box display color'),
parser.add_argument('--print', default=False, action='store_true',
help='Print inference results')
##app.route("/")
def main():
app.run(host='0.0.0.0', port=3000, debug=True)
run_app(add_render_gen_args, render_gen)
#templateData = {
#}
# Pass the template data into the template main.html and return it to the user
#return render_template('main.html', **templateData)
##app.route("/<changePin>/<action>")
#def action(changePin, action):
# print("yo")
if __name__ == '__main__':
main()
It looks like Flask's multithreading interferes with Periphery's GPIO interactions. If you create one python process for managing GPIO via Periphery and a second python process for the webserver, then you shouldn't hit this error.
Around 2020, Flask started defaulting its server to multithreaded. Older versions were synchronous and single threaded -- but allowed for multiple processes for handling multiple clients. This older configuration might not interfere with Periphery either.
I want to make a simple physical game with balls on Python using pygame and Box2D, but when I try to get the speed of the ball using a well-known method, I get this error. What might be the problem?
class Ball:
def __init__(self, x, y, radius, world, color, fric=0.3, maxspeed=20, density=0.01, restitution=0.5):
self.x = x
self.y = y
self.radius = radius
self.fric = fric
self.maxspeed = maxspeed
self.density = density
self.restitution = restitution
self.color = color
#body
self.bodyDef = box2d.b2BodyDef()
self.bodyDef.type = box2d.b2_dynamicBody
self.bodyDef.position = (x, y)
self.body = world.CreateBody(self.bodyDef)
#shape
self.sd = box2d.b2CircleShape()
self.sd.radius = radius
#fixture
self.fd = box2d.b2FixtureDef()
self.fd.shape = self.sd
#phys params
self.fd.density = density
self.fd.friction = fric
self.fd.restitution = restitution
self.body.CreateFixture(self.fd)
player = Ball(width / 3, height / 2, 30, world, (150, 150, 150))
v = player.body.GetLinearVelocity()
The Error:
Traceback (most recent call last):
File "D:\projs\box2d\bonk\main.py", line 60, in <module>
keyIsDown(pygame.key.get_pressed())
File "D:\projs\box2d\bonk\main.py", line 35, in keyIsDomn
v = player.body.GetLinearVelocity()
AttributeError: 'b2Body' Object has no attribute 'GetLinearVelocity'
screenshot of error
It looks like the GetLinearVelocity method is only available in the C library. The Python wrapper just uses linearVelocity:
v = player.body.linearVelocity
For the future, if you want to know what the variable type is and what methods\properties are available, you can use the type and dir functions:
print(type(player.body)) # class name # <class 'Box2D.Box2D.b2Body'>
print(dir(player.body)) # all methods and properties # ['ApplyAngularImpulse', 'ApplyForce',....,'linearVelocity',...]
I'm currently working on a game with pygame, in python 3.7.2.
I got a strange error when I run my program :
This is the full traceback :
hello from the 1st lign of this code :D
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\-------\----------\---------\WIP\newfile.py", line 69, in <module>
Window('load')
File "C:\Users\-------\----------\---------\WIP\newfile.py", line 52, in Window
bg32 = pygame.load('sprites/bg32.png').convert_alpha()
AttributeError: module 'pygame' has no attribute 'load'
It's really strange because 'load' function is a really basic and import function of pygame...
So this is my code ( full ), i still don't understand what's wrong here :
print('hello from the 1st lign of this code :D')
import time
spb = time.time()
import pygame
import os, sys
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
Very_Dark_Blue = ( 0, 0, 64)
barPos = (0, 0)
barSize = (400, 40)
borderColor = ( 0, 0, 0,)
max_a = 10000
a=0
screen=pygame.display.set_mode((1,1), pygame.NOFRAME)
def text(show_text, show_size, show_color, show_x, show_y):
fontObj = pygame.font.Font('Display_Font.ttf',show_size)
Load_text = fontObj.render(show_text,True,show_color,None)
render_text = Load_text.get_rect()
render_text.center = (show_x,show_y)
screen.blit(Load_text,render_text)
def image(name,x,y):
screen.blit(name,(x,y))
def DrawBar(pos, size, borderC, barC, progress):
global screen
pygame.draw.rect(screen, borderC, (*pos, *size), 1)
innerPos = (pos[0]+3, pos[1]+3)
innerSize = ((size[0]-6) * progress, size[1] - 6)
pygame.draw.rect(screen, barC, (*innerPos, *innerSize))
def Window(w):
global screen,a,max_a,barPos,barSize,Very_Dark_Blue,borderColor
if w == 'load':
screen=pygame.display.set_mode((400,40), pygame.NOFRAME)
bg32 = pygame.load('sprites/bg32.png').convert_alpha()
while w == 'load':
image(bg32,0,0)
DrawBar(barPos, barSize, borderColor, Very_Dark_Blue, a/max_a)
pygame.display.update()
a = a + 1
if a == max_a:
Window('main')
if w == 'main':
pygame.quit
screen=pygame.display.set_mode((1920,1080), pygame.NOFRAME)
while w == 'main':
image(background,0,0)
image(title,100,0)
pygame.display.update()
Window('load')
background = pygame.image.load('sprites/Background.png').convert_alpha()
title = pygame.image.load('sprites/Title.png').convert_alpha()
So I hope someone will find the problem :D
Thank for anyone who will try to help me !
As Rabbid76 already said in a comment, the load function is part of the image module, so you'll have to use pygame.image.load(...) instead of pygame.load(...).
I have a problem with my pixel_at function in my code. Here are all necessary code snippets.
Here is my Helper module:
import gtk.gdk
def pixel_at(x, y):
gtk.gdk
rw = gtk.gdk.get_default_root_window()
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 1, 1)
pixbuf = pixbuf.get_from_drawable(rw, rw.get_colormap(), x, y, 0, 0, 1, 1)
return tuple(pixbuf.pixel_array[0, 0])
Here is the Controller class for initilaizing:
import Sensors as sensor
import Scanner as sc
import pyautogui
import time
class GameController(object):
COLOR_DINOSAUR = (83, 83, 83)
def __init__(self):
self.offset = (230, 270) #hardcoded Offset
self.width = 600 # hardcoded but alwways the same
# Stores points (jumps)
self.points = 0
#Listeners
self.onGameEnd = None
self.onGameStart = None
self.onSensorData = None
#Game State
self.gameState = 'OVER'
self.sensor = sensor.Sensors()
self.Scanner = sc.Scanner()
Here is my main function:
import pyautogui
import Helper
import GameController as GC
def main():
print Helper.pixel_at(25, 5)
Controller = GC.GameController()
# Just test values for this function
Controller.Scanner.scanUntil([75, 124],
(-2, 0),
(83, 83, 83),
75 / 2)
Here is the code for the Scanner:
import pyautogui
import Helper
def scanUntil(self, start, step, matchColor, iterLimit):
iterations = 0
current = self.makeInBounds(start)
if step[X] == 0 and step[Y] == 0:
return None
while not self.isOutOfBound(current):
color = Helper.pixel_at(current[X], current[Y])
# to slow color = pyautogui.pixel(current[X], current[Y])
if color == matchColor: # Tuple comparison
return current
current[X] += step[X]
current[Y] += step[Y]
iterations += 1
if iterations > iterLimit:
return None
return None
This line color = Helper.pixel_at(current[X], current[Y]) in the Scanner throws the error: Fatal IO error 0 (Success) on X server :0. But the print Helper.pixel_at(25, 5)call in main() returns me the correct RGB tuple.
The error is thrown at pixbuf = pixbuf.get_from_drawable(rw, rw.get_colormap(), x, y, 0, 0, 1, 1) in the pixel_at(x,y) so I think it has something to do with this.
From the documentation at http://www.pygtk.org/pygtk2reference/class-gdkpixbuf.html#method-gdkpixbuf--get-from-drawable I got this clue: In other words, copies image data from a server-side drawable to a client-side RGB(A) buffer.
But I donĀ“t understand this server-side and client side and why is it working in my first print call but not for color = Helper.pixel_at(current[X], current[Y])?
This question already has answers here:
Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items?
(7 answers)
Closed 2 years ago.
first of all, sorry if this is already answered I've looked through past Q's but no luck.
My problem is: I've gone through the Python+libtcod tutorial on Roguebasin once and doing it again while making my own modifications.
I'm trying to make a hardcoded map instead of a randomly generated one.
The code so far will not show a window or anything I'm just running and hope it closes with no errors. BUT, I keep getting this:
Traceback (most recent call last):
File "superrogue.py", line 85, in <module>
make_map()
File "superrogue.py", line 68, in make_map
if MAP_FILE[x][y] in TILE_NAMES: #Find the tile's name---
IndexError: string index out of range
The whole "string index out of range" is what I've been beating my head against the wall all afternoon and evening.
Here's the code so far:
#---Imports-------------------------------------------------------------
import libtcodpy as libtcod
#---Program Labelings---------------------------------------------------
TITLE = 'Roguetest'
VERSION = '0.01a'
#---Setup Variables-----------------------------------------------------
SCREEN_WIDTH = 80
SCREEN_HEIGHT = 50
LIMIT_FPS = 20
#MAP_FILE = open('Maps/Test.txt', 'r')
#MAP_FILE = MAP_FILE.readlines()
MAP_FILE = ['XXXX',
'X==X',
'X..X',
'X..X',
'X==X',
'XXXX',
]
MAP_WIDTH = len(MAP_FILE[0])
print MAP_WIDTH
MAP_HEIGHT = len(MAP_FILE)
print MAP_HEIGHT
#---Dictionaries--------------------------------------------------------------
COLORS = {
'dark_new' : libtcod.Color(255, 0, 255),
'light_new' : libtcod.Color(255, 0, 255),
'dark_pavement' : libtcod.Color(20, 20, 20),
'light_pavement' : libtcod.Color(50, 50, 50),
'dark_sidewalk' : libtcod.Color(80, 80, 80),
'light_sidewalk' : libtcod.Color(120, 120, 120),
'dark_wall' : libtcod.Color(100, 100, 100),
'light_wall' : libtcod.Color(180, 180, 180)
}
TILE_NAMES = {
'X' : 'wall',
'.' : 'pavement',
'=' : 'sidewalk'
}
#---Classes-------------------------------------------------------------
class Tile:
def __init__(self, name):
self.name = name
self.darkcolor = COLORS['dark_' + self.name]
self.lightcolor = COLORS['light_' + self.name]
self.blocks = False
self.blocks_sight = False
self.inside = False
#---Functions-----------------------------------------------------------
def make_map():
map = [[ Tile(name='new')
for x in range(MAP_WIDTH) ]
for y in range(MAP_HEIGHT) ]
for x in range(MAP_WIDTH):
for y in range(MAP_HEIGHT):
print (x, y)
if MAP_FILE[x][y] in TILE_NAMES: #Find the tile's name---
map[x][y].name = TILE_NAMES[MAP_FILE[x][y]]
map[x][y].darkcolor = COLORS['dark_' + map[x][y].name]
map[x][y].lightcolor = COLORS['light_' + map[x][y].name]
if MAP_FILE[x][y] == 'X': #The WALL tile------------------
map[x][y].blocked = True
map[x][y].block_sight = True
elif MAP_FILE[x][y] == '.': #The PAVEMENT tile--------------
map[x][y].blocked = False
map[x][y].block_sight = False
elif MAP_FILE[x][y] == '=': #The SIDEWALK tile--------------
map[x][y].block_sight = False
map[x][y].ped_walkable = True
make_map()
Thanks.
y is getting up to len(MAP_HEIGHT) - 1 (because of the range call); MAP_HEIGHT = len(MAP_FILE); MAP_FILE is a list with six elements.
Thus y will take the values 0, 1, 2, 3, 4, 5. However, the string only has four values, so trying to access the fifth or sixth character will fail.
I think you've tangled map height and map width (it's indexed by [y][x] and you access it by [x][y]).