我正在努力創建一個使用Python和Tkinter的小行星版本。當按下左或右箭頭鍵時,船隻需要旋轉。這艘船是Tkinter帆布上的一個三角形。我無法提出公式來調整三角形的座標。我相信這與罪與cos有關,儘管我並不確定。到目前爲止,我有兩個班,一個是船,另一個是遊戲。在船上我有按鍵的回調方法。任何幫助將不勝感激。謝謝。如何在Tkinter Canvas上的python中旋轉多邊形?
船級
import math
class Ship:
def __init__(self,canvas,x,y,width,height):
self.canvas = canvas
self.x = x - width/2
self.y = y + height/2
self.width = width
self.height = height
self.x0 = self.x
self.y0 = self.y
self.x1 = self.x0 + self.width/2
self.y1 = self.y0-self.height
self.x2 = self.x0 + self.width
self.y2 = self.y0
self.ship = self.canvas.create_polygon((self.x0, self.y0, self.x1, self.y1, self.x2, self.y2), outline="white", width=3)
def changeCoords(self):
self.canvas.coords(self.ship,self.x0, self.y0, self.x1, self.y1, self.x2, self.y2)
def rotateLeft(self, event=None):
# Should rotate one degree left.
pass
def rotateRight(self, event=None):
# Should rotate one degree right.
self.x0 = self.x0 -1
self.y0 = self.y0 - 1
self.x1 = self.x1 + 1
self.y1 = self.y1 + 1
self.x2 = self.x2 - 1
self.y2 = self.y2 + 1
self.changeCoords()
遊戲類
from Tkinter import *
from ship import *
class Game:
def __init__(self, gameWidth, gameHeight):
self.root = Tk()
self.gameWidth = gameWidth
self.gameHeight = gameHeight
self.gameWindow()
self.ship = Ship(self.canvas, x=self.gameWidth/2,y=self.gameHeight/2, width=50, height=50)
self.root.bind('<Left>', self.ship.rotateLeft)
self.root.bind('<Right>', self.ship.rotateRight)
self.root.mainloop()
def gameWindow(self):
self.frame = Frame(self.root)
self.frame.pack(fill=BOTH, expand=YES)
self.canvas = Canvas(self.frame,width=self.gameWidth, height=self.gameHeight, bg="black", takefocus=1)
self.canvas.pack(fill=BOTH, expand=YES)
asteroids = Game(600,600)
非常感謝您的幫助。你是一個學者和紳士。這正是我所期待的。 – Sam 2010-08-05 00:59:43
你很受歡迎。 – JAB 2010-08-05 13:34:32