How to make scoreborad in tkinter - class

I would like to implement a scoreboard using a tkinter.
and i want make if the distance between the object bullet and the object enemy is less than 10, I want to increase the score by 10.
How do I add code?
Thank you in advance.
from tkinter import *
import time
import random
WIDTH = 800
HEIGHT = 800
class Ball:
def __init__(self, canvas, color, size, x, y, xspeed, yspeed):
self.canvas = canvas
self.color = color
self.size = size
self.x = x
self.y = y
self.xspeed = xspeed
self.yspeed = yspeed
self.id = canvas.create_oval(x, y, x+size, y+size, fill=color)
def move(self):
self.canvas.move(self.id, self.xspeed, self.yspeed)
(x1, y1, x2, y2) = self.canvas.coords(self.id)
(self.x, self.y) = (x1, y1)
if x1 <= 0 or x2 >= WIDTH:
self.xspeed = - self.xspeed
if y1 <= 0 or y2 >= HEIGHT:
self.yspeed = - self.yspeed
bullets = []
def fire(event):
bullets.append(Ball(canvas, "red", 10, 150, 250, 10, 0))
def up(event):
spaceship.yspeed-=1
def down(event):
spaceship.yspeed+=1
window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT)
canvas.pack()
canvas.bind("<Button-1>", fire)
window.bind("<Up>",up)
window.bind("<Down>",down)
spaceship = Ball(canvas, "green", 100, 100, 200, 0, 0)
enemy = Ball(canvas, "red", 100, 500, 200, 5, 0)
while True:
for bullet in bullets:
bullet.move()
if (bullet.x+bullet.size) >= WIDTH:
canvas.delete(bullet.id)
bullets.remove(bullet)
enemy.move()
spaceship.move()
window.update()
time.sleep(0.03)

There are many ways to improve your program but I will concentrate on the collision aspect only.
Tkinter canvas has several methods; find_closest, find_enclosed and find_overlapping (See here) to allow you to detect where objects are in relation to each other. find_closest would be my first choice.
find_closest should take the x, y coordinates of the 'enemy' and a 'halo distance' (your less than 10 pixels). This will return the id's of objects nearby. If one of those objects is a bullet, then add 10 points to the score.
Some other things to fix/work on
You don't have a tkinter.mainloop. You should
Your method for moving the spaceship by changing the speed rather than the xy coords is poor and ends up with a very fast moving spaceship.

Related

Pymunk dynamic object overlapping static object

I am starting out with pymunk and have a static floor with a dynamic object (ball). When the ball falls onto the floor there is an initial overlap where the ball is absorbed into the floor before slowly being pushed back up.
Why does this happen? Is this normal?
import pygame
import pymunk
import pymunk.pygame_util
pygame.init()
#game window
SCREEN_WIDTH, SCREEN_HEIGHT = 600, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
#pymunk space
space = pymunk.Space()
space.gravity = (0, 981)
clock = pygame.time.Clock()
fps = 60
dt = 1/60
draw_options = pymunk.pygame_util.DrawOptions(screen)
def create_floor(space, width, height, pos):
body = pymunk.Body(body_type = pymunk.Body.STATIC)
body.position = pos
shape = pymunk.Poly.create_box(body, (width, height))
space.add(body, shape)
def create_ball(space, radius, mass):
body = pymunk.Body()
body.position = (300, 250)
shape = pymunk.Circle(body, radius)
shape.mass = mass
shape.color = (255, 0, 0, 100)
space.add(body, shape)
return shape
ball = create_ball(space, 30, 10)
create_floor(space, SCREEN_WIDTH, 20, (SCREEN_WIDTH / 2, SCREEN_HEIGHT - 10))
run = True
while run:
clock.tick(fps)
space.step(dt)
screen.fill((255, 255, 255))
space.debug_draw(draw_options)
#event handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()
Yes, this is normal. There are however things that can be done to minimize this behavior:
The easiest method is to call space.step() with a smaller timestep (and instead call it more times). Replace space.step(dt) with something like this:
for _ in range(10):
space.step(dt/10)
Its also possible to limit the maximum speed that objects move with. The slower they move, the less overlap there will be. Finally, you can also try to adjust the collision_bias parameter on the space.

Change dimension of cube using MatrixTransform in vispy

import numpy as np
from vispy import app, scene
from vispy.visuals import transforms
canvas = scene.SceneCanvas(keys='interactive', show=True)
vb = canvas.central_widget.add_view()
vb.camera = 'turntable'
vb.camera.rect = (-10, -10, 20, 20)
box = scene.visuals.Box(width=1, height=2, depth=3, color=(0, 0, 1, 0.3),
edge_color='green')
vb.add(box)
# Define a scale and translate transformation :
box.transform = transforms.STTransform(translate=(0., 0., 0.),
scale=(1., 1., 1.))
#canvas.events.key_press.connect
def on_key_press(ev):
tr = np.array(box.transform.translate)
sc = np.array(box.transform.scale)
if ev.text in '+':
tr[0] += .1
elif ev.text == '-':
tr[0] -= .1
elif ev.text == '(':
sc[0] += .1
elif ev.text == ')':
sc[0] -= .1
box.transform.translate = tr
box.transform.scale = sc
print('Translate (x, y, z): ', list(tr),
'\nScale (x, y, z): ', list(sc), '\n')
if __name__ == '__main__':
import sys
if sys.flags.interactive != 1:
app.run()
In the above code if I add a MatrixTransform, and rotate the cube and then apply scaling, the cube becomes a Rhombus
What I would like to achieve is to rotate the cube in a canvas and scale it only in X direction, without other dimensions getting affected
I think we covered this in a vispy repository bug report. The solution was to swap the order of the matrix transform and st transform in your multiplication. If this is still an issue, could you provide your code when you are using the matrix and we'll continue debugging this. Thanks.

How to store a list of multiple Swift files and execute them independently

I am trying to create a small tutorial project for improving the coding style in Swift. Each lesson will contain two code examples, one for before and one for after.
So in total, I will have around 20 files that I would like to run individually and independently of the others.
Any suggestions on how to store all these?
Ideally, they should all belong to a project, but I am not figuring out how to run them separately.
Thank you
Here is an example of "before" (bad) code:
//a flying saucer
struct X {
var x: Float //the horizontal coordinate of the center of the flying saucer
var y: Float //the vertical coordinate of the center of the flying saucer
var r: Float //the radius of the starship
}
//function finding out if two flying saucers colided
func collision(x: X, y: X) -> Bool {
return abs(x.x - y.x) < x.r + y.r
}
//testing code
let x = X(x: 10, y: 10, r: 10)
let y = X(x: 12, y: 13, r: 5)
let z = X(x: 100, y: 50, r: 20)
print(collision(x: x, y: y))
print(collision(x: x, y: z))
print(collision(x: x, y: z))

Swift plot coordinates on uiimageview with world map

I am trying to plot some coordinates on the earth on an UIImage which contains a map of the world. (I don't want to use maps)
See an example of the UIImageView below below:
As you see it's working out pretty well but the mapping from coordinates and X Y are incorrect!
Amsterdam's coordinates are: (52.36666489, 4.883333206) and the Center's are (0,0).
I've done the following things to try to make this happen but unfortunately this isn't working out:
I've tried first to 'normalize' the coordinates since latitude ranges from -90 to 90 and latitude -180 to 180. This is done by adding 90 to the real latitude and 180 to the real longitude which yiels the 'normalized' versions:
let normalizedLat = location.coordinate.latitude + 90.0.
let normalizedLng = location.coordinate.longitude + 180.0
After that I've calculated the scale factor where the normalizedLat and normalizedLng should scale with:
let heightScaleFactor = mapImageView.frame.height / 180.0
let widthScaleFActor = mapImageView.frame.width / 360.0
And 3. After that i've got the scaling factors I finally can calculate the coordinates by:
let x = Double(widthScaleFActor * CGFloat(normalizedLng))
let y = Double(heightScaleFactor * CGFloat(normalizedLat))
dot.frame = CGRect(x: x, y: y, width: Double(dot.frame.width), height: Double(dot.frame.height))
But for some strange reason Amsterdam is not on the Amsterdam spot and the Center is not on the Center spot.
I am quite sure that my calculations has gone wrong. Any ideas?
Remember, in iOS the origin is in the top-left, not the bottom-left. Positive-y goes down, not up.
You need to factor that in.
dot.frame = CGRect(x: x, y: mapImageView.frame.height - y, width: Double(dot.frame.width), height: Double(dot.frame.height))
Also note that the equator in your image is not in the middle. It's lower in the image so you need to add an additional offset in your calculation of the y value based on the equator's offset in the image.
dot.frame = CGRect(x: x, y: mapImageView.frame.height - y + equatorOffset, width: Double(dot.frame.width), height: Double(dot.frame.height))
It's also possible that your map projection doesn't have a simple linear latitude scale. 0-10 degrees might be 12 pixels while 10-20 degrees might be 11 pixels, etc. and 80-90 is only 3 pixels (or whatever).

Robot arm programming, transformation of coordinate system

I have a project in which i need make a matlab based simulation of a robotic arm.
img http://img845.imageshack.us/img845/4512/l5mx.png
The first part sits in the origin, and can rotate around the Z axis in the world coordinate system. This joint is called joint1. The next joint, joint2 is displaced 0.8m in the Z direction of the coordinate system of part 1. It will rotate around the Y axis of the coordinate system of part2. Joint3 is displaced 0.6m in the Z direction of the csystem of part2. It will rotate around the y axis of the csystem of part3. The end of part3 is displaced 0.7m in the Z direction of csystem of part3.
Now, lets try to do some matrices of this. I'm quite sure i'm doing something wrong with these. The coordinates will be in homogenous form, so v = [v,1].
T_Wto1 = [cos(alpha(1)), -sin(alpha(1)), 0 , 0;
sin(alpha(1)), cos(alpha(1)), 0 , 0;
0, 0, 1 , 0.8;
0, 0, 0, 1];
T_1to2 = [cos(alpha(2)), 0, sin(alpha(2)), 0;
0, 1, 0, 0;
-sin(alpha(2)), 0, cos(alpha(2)), 0.6;
0, 0, 0, 1];
T_2to3 = [cos(alpha(3)), 0, sin(alpha(3)), 0;
0, 1, 0, 0;
-sin(alpha(3)), 0, cos(alpha(3)), 0.7;
0, 0, 0, 1];
For alpha(1) = 0, alpha(2) = alpha(3) = pi/2
First of all. If i use p1 = T_Wto1*[0,0,0,1]', i get [0,0,0.8,1]', so far so good. Then, T_1to2*[0,0,0.8,1]' gives [0.8,0,0.6,1]' (it is now displaced 0.8 in the X direction, which is really 0.8 in the Z direction, because of the rotation). Now, say that i want to transform this back to world coordinates. It should say [0.6,0,0.8], but i'm unsure on how to do that. If you just take the inverse of the matrix T_Wto2 (a product of T_Wto1 and T_1to2), you just get the origin [0,0,0,1] back. What are you supposed to do to make it back into world coordinates again?
Also, are the transformation matrices correct?