Using lists in classes

56 views Asked by At

I'm trying to make a game in python 3.5 using the canvas. I have a list of the coordinates of the triangle in a list. I'm using a class to make an object which is suppose to be the player. When I tried to implement a movement system I thought of using a list so that I can quickly change the coordinates using a for loop, however when I run the code and press the button it gives me this:

"TypeError: list indices must be integers or slices, not float"

Here's the code (sorry if it's primitive, it's my first time using both canvas and class and I typed this up in three hours)

import sys
from tkinter import*


w = 600
h = 400

gui = Tk()
gui.geometry('1000x650')
canvas = Canvas(gui,width=w,height=h,bg='black')
canvas.place(relx=0.5,rely=0.35,anchor=CENTER)
class player():
    def __init__(self,x,y,a):
        self.x1 = x
        self.y1 = y
        self.x2 = x-a/2
        self.y2 = y+a
        self.x3 = x+a/2
        self.y3 = y+a
        self.coords = [self.x1,self.y1,self.x2,self.y2,self.x3,self.y3]
    def display(self):
        canvas.create_polygon(self.x1,self.y1,self.x2,self.y2,self.x3,self.y3,outline='white')
    def move(self,pos):
        if pos == True:
            thrust = 5
        else:
            thrust = -5
        while thrust > 0.1:
            for i in self.coords:
                self.coords[i]=self.coords[i]+thrust
            thrust-=1

up_arrow = Button(gui,text='^',command=lambda:p1.move(True))
up_arrow.place(relx=0.5,rely=0.7,anchor=CENTER)

p1 = player(w/2,h/2,50)
p1.display()
1

There are 1 answers

0
Max On BEST ANSWER

for i in self.coords:

this is going to set i to each item in self.coords in turn, not the indices of the items.

That means that when you wrote self.coords[i]=self.coords[i]+thrust was likely not what you wanted. (Since i is not an index, but an item in self.coords)

You will have to use the range() function to give i the value you want.

for i in range(len(self.coords)):
    self.coords[i]=self.coords[i]+thrust

You might think that this would work

for i in self.coords:
    i = i + thrust

but it does not work because i is the value at that position in self.coords. It is not a reference to it. Changing it will not change self.coords. It is temporary.