Why does the collide happen many times? - python

I'm using openGL with Pyglet which is a python package. I have to use this language and this package, it is for an assignment. I have a basic Brickbreaker style game that is basically a keep it up game.
I create a ball and a paddle.
I separately create a bounding box class that will be used to create the hit boxes for each object.
class BoundBox:
def __init__ (self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
Then I create the boxes themselves
paddleBox = BoundBox(200, 20, [0,0])
ballBox = BoundBox(40, 40, [236, 236])
In the update function which is running # pyglet.clock.schedule_interval(update,1/100.0) I call the checkcollide() function which checks if there was a collision:
def checkForCollide():
global collides
if overlap(ballBox, paddleBox):
vel = 1.05
ballVel[0] = ballVel[0]*vel #Ball speeds up when collide happens
ballVel[1] = ballVel[1]*vel
ballVel[1] = -ballVel[1] #Change direction on collision
ballPos[1] = -ballPos[1]
collides += 1 #counts how many collides happen
The overlap function is returning a boolean if there's an overlap in hit boxes:
def overlap(box1, box2):
return (box1.pos[0] <= box2.width + box2.pos[0]) and(box1.width + box1.pos[0] >= box2.pos[0]) and(box1.pos[1] <= box2.height + box2.pos[1]) and(box1.height + box1.pos[1] >= box2.pos[1])
pos[0] is the minimum x
width is the maximum x
pos[1] is the minimum y
height is the maximum y
When I run the game and the ball hits the paddle it flickers about 15 times and increments the collides counter every time it detects a hit. Collides then prints in the console. Why does this flicker happen? How do I stop it?
Here is the program's full code (you must have pyglet installed to run it):
import sys, time, math
from pyglet.gl import *
from euclid import *
from pyglet.window import key
from pyglet.clock import *
window = pyglet.window.Window(512,512)
quadric = gluNewQuadric()
ballPos = Vector2(256,256)
ballVel = Vector2(200,145)
x1 = 0
bar = pyglet.graphics.vertex_list(4, ('v2f', [0,0, 0,20, 200,0, 200,20]))
startTime = time.clock()
collides = 0
#pos is minx, miny
class BoundBox:
def __init__ (self, width, height, pos):
self.width = width
self.height = height
self.pos = pos
def overlap(box1, box2):
return (box1.pos[0] <= box2.width + box2.pos[0]) and(box1.width + box1.pos[0] >= box2.pos[0]) and(box1.pos[1] <= box2.height + box2.pos[1]) and(box1.height + box1.pos[1] >= box2.pos[1])
paddleBox = BoundBox(200, 20, [0,0])
ballBox = BoundBox(40, 40, [236, 236])
#window.event
def on_draw():
glClear(GL_COLOR_BUFFER_BIT)
glPushMatrix()
glPushMatrix()
glColor3f(1,1,1)
glTranslatef(x1, 0, 0)
bar.draw(GL_TRIANGLE_STRIP)
glPopMatrix()
glTranslatef(ballPos[0], ballPos[1], 0)
glColor3f(1,0,0)
gluDisk(quadric, 0, 20, 32, 1)
glPopMatrix()
#window.event
def on_key_press(symbol, modifiers):
global x1
dist = 30
if symbol == key.RIGHT:
#print "right"
x1 += dist
elif symbol == key.LEFT:
#print "left"
x1 -= dist
def checkForBounce():
if ballPos[0] > 512.0:
ballVel[0] = -ballVel[0]
ballPos[0] = 512.0 - (ballPos[0] - 512.0)
elif ballPos[0] < 0.0:
ballVel[0] = -ballVel[0]
ballPos[0] = -ballPos[0]
if ballPos[1] > 512.0:
ballVel[1] = -ballVel[1]
ballPos[1] = 512.0 - (ballPos[1] - 512.0)
elif ballPos[1] < -100.0:
gameOver()
def gameOver():
global collides
'''global startTime
elapsed = (time.time() - startTime)
score = elapsed * .000000001
finalscore = '%.1f' % round(score, 1)'''
gostr = "GAME OVER"
print gostr
str = "Your score = "
print str
print collides
pyglet.app.exit()
def checkForCollide():
global collides
if overlap(ballBox, paddleBox):
vel = 1.05
ballVel[0] = ballVel[0]*vel #Ball speeds up when collide happens
ballVel[1] = ballVel[1]*vel
ballVel[1] = -ballVel[1] #Change direction on collision
ballPos[1] = -ballPos[1]
collides += 1 #counts how many collides happen
print collides
#glscale(0.5, 1, 1)
def update(dt):
global ballPos, ballVel, ballBox, x1, paddleBox
ballBox = BoundBox(40, 40, [ballPos[0], ballPos[1]])
paddleBox = BoundBox(200, 20, [x1,0])
#print paddleBox.pos
#print ballBox.pos
ballPos += ballVel * dt
checkForBounce()
checkForCollide()
pyglet.clock.schedule_interval(update,1/100.0)
pyglet.app.run()

I don't think you wanted to invert the position here:
def checkForCollide():
global collides
if overlap(ballBox, paddleBox):
vel = 1.05
ballVel[0] = ballVel[0]*vel #Ball speeds up when collide happens
ballVel[1] = ballVel[1]*vel
ballVel[1] = -ballVel[1] #Change direction on collision
ballPos[1] = -ballPos[1]
collides += 1 #counts how many collides happen
What were you trying to do with this line?
ballPos[1] = -ballPos[1]
I suspect that is why you are flickering.

Related

How do I alter my code so that the projectile is able to move? (using python and tkinter)

Seen below is the code i have written for a maze game where the user controls a green square which they move around the maze using wasd, where they also have a projectile they can shoot using M1 and aiming the mouse cursor, However I am currently having issues with the moving of the projectile and I am not sure how i will be able to fix this problem.
import random
import tkinter as tk
import time
# Set the size of the maze
maze_width = 800
maze_height = 500
#Creating the character size
character_size = 20
maze = tk.Tk()
canvas = tk.Canvas(maze, width = maze_width, height = maze_height)
canvas.pack()
# Create the game over screen, making it red with text displaying that the game is over
game_over_screen = canvas.create_rectangle(0, 0, maze_width, maze_height, fill='red')
game_over_text = canvas.create_text(maze_width/2, maze_height/2, text='GAME OVER!', font=('Arial', 30), fill='white')
# Hide the game over screen so that it is only displayed when the player dies
canvas.itemconfig(game_over_screen, state='hidden')
canvas.itemconfig(game_over_text, state='hidden')
# Create the victory screen which will be siaplayed when the user escapes the maze
victory_screen = canvas.create_rectangle(0, 0, maze_width, maze_height, fill='green')
victory_text = canvas.create_text(maze_width/2, maze_height/2, text='YOU ESCAPED THE MAZE!', font=('Arial', 30), fill='white')
canvas.itemconfig(victory_screen, state='hidden')
canvas.itemconfig(victory_text, state='hidden')
# Create a 2D array to represent the whole maze
maze_array = [[0 for x in range(maze_width//20)] for y in range(maze_height//20)]
# Generate the maze, ensuring that every 20 units of the maze, there is a 50% chance of a wall being created, storing the walls as 1s and the 0 representing free space
for x in range(0, maze_width, 20):
for y in range(0, maze_height, 20):
if x == 0 or x == maze_width - 20 or y == 0 or y == maze_height - 20:
canvas.create_rectangle(x, y, x + 20, y + 20, fill='black', tags='wall')
maze_array[y//20][x//20] = 1
elif random.random() > 0.6:
canvas.create_rectangle(x, y, x + 20, y + 20, fill='black', tags='wall')
maze_array[y//20][x//20] = 1
# Making sure the path starts at the entrance point of the maze in the top left corner
x, y = 20, 20
path = [(x, y)]
# Stating the amount of vertical and horizontal units the path should move by
move_across = 37
move_down = 22
# Move the path sideways by the amount of units stated earlier
for i in range(move_across):
x += 20
path.append((x, y))
maze_array[y//20][x//20] = 0
# Move the path down by the amount of units stated earlier
for i in range(move_down):
y += 20
path.append((x, y))
maze_array[y//20][x//20] = 0
# Place squares over the path to simulate creating a path
for point in path:
x, y = point
#Fill the path using the hexadecimal colour value of the navigable part of the maze
canvas.create_rectangle(x, y, x + 20, y + 20, outline='#d9d9d9',fill='#d9d9d9')
# Adding a black square to the top right corner of the maze, so that the path is less obvious
canvas.create_rectangle(maze_width - 40, 20, maze_width - 20, 40, fill='black', tags='wall')
# Create the entrance and exit
# Change coordinates of the entrance and exit so they move one square in the diagonal direction
canvas.create_rectangle(20, 20, 40, 40, fill='blue')
exit_ = canvas.create_rectangle(maze_width - 40, maze_height - 40, maze_width -20, maze_height -20, fill='blue')
entrance = (20, 20) # top-left corner of the maze
exit = (750, 450)
projectile_x, projectile_y = (entrance)
# Algorithm for aiming the projectile with the mouse pointer
def aim_projectile(direction):
global projectile_direction
x,y = direction.x, direction.y
if x > player_x + character_size:
projectile_direction = 'right'
elif x < player_x:
projectile_direction = 'left'
elif y < player_y:
projectile_direction = 'up'
elif y > player_y + character_size:
projectile_direction = 'down'
# Define projectile so it can be called upon in the fire_projectile function
projectile = None
# Algorithm to fire the projectile
def fire_projectile(event):
global projectile
# Make it so the projectile is deleted if the user tries spawning multiple on the screen
if projectile is not None:
canvas.delete(projectile)
x1,y1,x2,y2 = canvas.coords(player)
center_x = (x1+x2) / 2
center_y = (y1 + y2) / 2
global projectile_x, projectile_y
#Shoot the projectile in the direction that has previously been stated in the movement algorithm
if projectile_direction is not None:
projectile = canvas.create_oval(center_x - 5,center_y - 5, center_x + 5,center_y + 5, fill='red')
if projectile_direction == 'up':
canvas.move(projectile, 0, -20)
projectile_y -= 20
elif projectile_direction == 'down':
canvas.move(projectile, 0, 20)
projectile_y += 20
elif projectile_direction == 'left':
canvas.move(projectile, -20, 0)
projectile_x -= 20
elif projectile_direction == 'right':
canvas.move(projectile, 20, 0)
projectile_x += 20
# Move the projectile after 1/4 seconds
maze.after(250, fire_projectile)
# Bind the canvas to the aim_projectile function
canvas.bind("<Motion>", aim_projectile)
# Bind the left mouse button to the fire_projectile function
canvas.bind("<Button-1>",fire_projectile)
# Create the player model which will be spawned at the entrance of the maze
player_x, player_y = 20, 20
player = canvas.create_rectangle(player_x, player_y, player_x+20, player_y+20, fill='green')
def check_enemy_collision():
# get player and enemy coordinates
player_coords = canvas.coords(player)
enemy_coords = canvas.coords(enemy)
# check if player and enemy coordinates align
if (player_coords[0] == enemy_coords[0] and player_coords[2] == enemy_coords[2]) and (player_coords[1] == enemy_coords[1] and player_coords[3] == enemy_coords[3]):
# Display the game over screen
canvas.itemconfigure(game_over_screen, state='normal')
canvas.itemconfigure(game_over_text, state='normal' )
# Ensure that the game over screen and text are displayed over the walls
canvas.tag_raise(game_over_screen)
canvas.tag_raise(game_over_text)
def check_exit_collision():
# Gather the coordinates of the player and of the exit to the maze
player_x1, player_y1, player_x2, player_y2 = canvas.coords(player)
exit_x1, exit_y1, exit_x2, exit_y2 = canvas.coords(exit_)
# Compare these values, and if they all match up, then the victory screen should be displayed
if player_x1 >= exit_x1 and player_x2 <= exit_x2 and player_y1 >= exit_y1 and player_y2 <= exit_y2:
# Display the victory screen
canvas.itemconfig(victory_screen, state='normal')
canvas.itemconfig(victory_text, state='normal')
#Ensure the text will be displayed over the walls
canvas.tag_raise(victory_screen)
canvas.tag_raise(victory_text)
# Delete the player once they reach the exit
canvas.delete(player)
# Algorithm for moving the player as well as adding collision to the walls of the maze
def move_player(event):
# Calls upon the previously stated x and y values of the player so they can be modified
global player_x, player_y
x1, y1, x2, y2 = canvas.coords(player)
new_x, new_y = player_x, player_y
if event.char == 'w':
new_y -= 20
elif event.char == 's':
new_y += 20
elif event.char == 'a':
new_x -= 20
elif event.char == 'd':
new_x += 20
x1,y1,x2,y2 = canvas.coords(player)
player_x, player_y = int((x1+x2)/2), int((y1+y2)/2)
# Convert new_x and new_y to indexes and store them as integers
new_x_index = int(new_x // 20)
new_y_index = int(new_y // 20)
# Check if the new position would put the player inside any of the walls
if maze_array[new_y_index][new_x_index] == 1:
# If player aligns with the maze walls do not allow them to move
return
# If there is no collision, allow the player to move
canvas.move(player, new_x - player_x, new_y - player_y)
player_x, player_y = new_x, new_y
# Check for collision between the player, enemy and exit every time the player moves
check_enemy_collision()
check_exit_collision()
#bind the 'w','a','s','d' keys to the move_player function
canvas.bind("<KeyPress-w>", move_player)
canvas.bind("<KeyPress-a>", move_player)
canvas.bind("<KeyPress-s>", move_player)
canvas.bind("<KeyPress-d>", move_player)
canvas.focus_set()
# Create the enemy at the exit of the maze
exit = (maze_width-40,maze_height-40)
enemy = canvas.create_rectangle(exit[0], exit[1], exit[0]+20, exit[1]+20, fill='red')
# Function to move the enemy towards the player
def move_enemy():
global player_x, player_y
# Gather the coordinates of the player so the enemy is able to make its way towards the user
x1,y1,x2,y2 = canvas.coords(player)
player_x, player_y = (x1+x2)/2, (y1+y2)/2
global enemy_x, enemy_y
x1,y1,x2,y2 = canvas.coords(enemy)
enemy_x, enemy_y = (x1+x2)/2, (y1+y2)/2
# Finds where the player is and appropriately moves the enemy towards this position
if player_x > enemy_x:
canvas.move(enemy, 20, 0)
elif player_x < enemy_x:
canvas.move(enemy, -20, 0)
if player_y > enemy_y:
canvas.move(enemy, 0, 20)
elif player_y < enemy_y:
canvas.move(enemy, 0, -20)
# Update the new position of the enemy coordinates
x1,y1,x2,y2 = canvas.coords(enemy)
enemy_x, enemy_y = int((x1+x2)/2), int((y1+y2)/2)
# Move the enemy towards the player once every second
maze.after(500, move_enemy)
#Check for collision between the player and the enemy every time the enemy moves
check_enemy_collision()
move_enemy()
# Create the timer text in the top right corner
timer_text = canvas.create_text(maze_width - 20, 20, text='0', font=('Arial', 20), fill='yellow')
def update_timer():
# Increment the timer value
global timer
# Increment the timer by a value of 1
timer += 1
# Update the timer text on the canvas
canvas.itemconfig(timer_text, text=timer)
# Make it so the timer updates after 1 second
canvas.after(1000, update_timer)
# Start the timer and initialise the value as 0, calling upon the funciton to update it
timer = 0
update_timer()
# Initialise the score as 0 and make it so this is displayed in the top left of the screen
score = 0
# Create the text that will be shown at the top of the screen displaying score
score_text = canvas.create_text(80, 20, text='Score: {}'.format(score), font=('Arial', 20), fill='yellow')
def update_score():
# Increase the score by 1
global score
score += 5
# Update the score text on the canvas
canvas.itemconfig(score_text, text='Score: {}'.format(score))
# Schedule the next score update
canvas.after(1000, update_score)
update_score()
# Find the player and exit coordinates and assign them values so the extra points can be assigned
player_x1, player_y1, player_x2, player_y2 = canvas.coords(player)
exit_x1, exit_y1, exit_x2, exit_y2 = canvas.coords(exit_)
# Compare these values, and if they all match up, then the victory screen should be displayed
if player_x1 >= exit_x1 and player_x2 <= exit_x2 and player_y1 >= exit_y1 and player_y2 <= exit_y2:
# Give the user an extra 1000 points if they escape the maze
score += 1000
canvas.itemconfig(score_text, text='Score: {}'.format(score))
maze.mainloop()
Seen below is the code that is problematic, as when I click M1, a projectile is spawned, however it does not move after it has been shot, and the following error message appears:
Traceback (most recent call last):
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 1892, in __call__
return self.func(*args)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/tkinter/__init__.py", line 814, in callit
func(*args)
TypeError: fire_projectile() missing 1 required positional argument: 'event'
Is there any way I can fix this, as other solutions i have found elsewhere when implemented have not actually been able to properly solve my problem. Thanks to anyone who helps
projectile_x, projectile_y = (entrance)
# Algorithm for aiming the projectile with the mouse pointer
def aim_projectile(direction):
global projectile_direction
x,y = direction.x, direction.y
if x > player_x + character_size:
projectile_direction = 'right'
elif x < player_x:
projectile_direction = 'left'
elif y < player_y:
projectile_direction = 'up'
elif y > player_y + character_size:
projectile_direction = 'down'
# Define projectile so it can be called upon in the fire_projectile function
projectile = None
# Algorithm to fire the projectile
def fire_projectile(event):
global projectile
# Make it so the projectile is deleted if the user tries spawning multiple on the screen
if projectile is not None:
canvas.delete(projectile)
x1,y1,x2,y2 = canvas.coords(player)
center_x = (x1+x2) / 2
center_y = (y1 + y2) / 2
global projectile_x, projectile_y
#Shoot the projectile in the direction that has previously been stated in the movement algorithm
if projectile_direction is not None:
projectile = canvas.create_oval(center_x - 5,center_y - 5, center_x + 5,center_y + 5, fill='red')
if projectile_direction == 'up':
canvas.move(projectile, 0, -20)
projectile_y -= 20
elif projectile_direction == 'down':
canvas.move(projectile, 0, 20)
projectile_y += 20
elif projectile_direction == 'left':
canvas.move(projectile, -20, 0)
projectile_x -= 20
elif projectile_direction == 'right':
canvas.move(projectile, 20, 0)
projectile_x += 20
# Move the projectile after 1/4 seconds
maze.after(250, fire_projectile)
# Bind the canvas to the aim_projectile function
canvas.bind("<Motion>", aim_projectile)
# Bind the left mouse button to the fire_projectile function
canvas.bind("<Button-1>",fire_projectile)

python kivy collision detection isn't working

Im trying to create a game with Python's Kivy but my collision detection system isnt working i've tried many different methods on youtube but still no success it either does detect anything or just gives me error messages
def collides(self, player, ball2):
r1x = player.pos[0]
r1y = player.pos[1]
r2x = ball2.pos[0]
r2y = ball2.pos[1]
r1w = player.size[0]
r1h = player.size[1]
r2w = ball2.size[0]
r2h = ball2.size[1]
if r1x < r2x + r2w and r1x + r1w > r2x and r1y < r2y + r2h and r1y + r1h > r2y:
print("True")
return True
else:
return False
print('False')
Your code in collides seems OK but rest of code (in repo) doesn't look good.
I took code from repo and first I made many changes to make it cleaner - I made class Sprite similar to pygame.Sprite
And next I tried use collisions and they work for me.
I keep all balls on list so I can use for-loop to work with all ball. And I can add more balls and it will still works the same. And I can remove ball from list when it is "killed".
I also run all with one schedule_interval. When I click button then I only change speed vx without running another schedule_interval. And this way in update() I can first I make calculation, next I can check collisions and at the end I can move rect on canvas - and this way rect doesn't blik when I have to move it back to previous position (ie. when I detect collision with border).
from kivy.app import App
from kivy.graphics import Ellipse, Rectangle, Color
from kivy.metrics import dp
from kivy.properties import Clock, ObjectProperty, NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
# How to play the game: Click left and right to move along the 'x' axis to stop click button to move in the opposite
# direction once, to go faster just repeatedly click the direction you want to go BUT there's a catch the faster
# you are going the harder it is to stop sp be carefull. you can teleport to the other side of the screen but only from
# the right side to the left side
# Objective: Dodge all incoming enemies until you reach the next level
# Level layout: Lvl 1: Space invaders type mode Lvl 2: Platform runner type mode Lvl 3: undecided...
# Goal: Make this game playable both on mobile and pc
class Sprite():
def __init__(self, x, y, size, color, vx, vy):
'''Set all values.'''
self.start_x = x
self.start_y = y
self.x = x
self.y = y
self.size = size
self.color = color
self.vx = vx
self.vy = vy
self.rect = None
#self.alive = True
def create_rect(self):
'''Execute it in `with canvas:` in `on_size()`.'''
Color(*self.color)
self.rect = Rectangle(pos=(self.x, self.y), size=(self.size, self.size))
def set_start_pos(self, center_x, center_y):
'''Move to start position.'''
self.x = center_x + self.start_x
self.y = center_y + self.start_y
def move(self):
'''Calculate new position without moving object on `canvas`.'''
self.x += self.vx
self.y += self.vy
def draw(self):
'''Move object on canvas.'''
self.rect.pos = (self.x, self.y)
def check_collision_circle(self, other):
distance = (((self.x-other.x)**2) + ((self.y-other.y)**2)) ** 0.5
#if distance < (self.size + other.size)/2:
# print(True)
# return True
#else:
# return False
return distance < (self.size + other.size)/2:
def check_collision_rect(self, other):
# code `... and ...` gives `True` or `False`
# and it doesn't need `if ...: return True else: return False`
return (
(other.x <= self.x + self.size) and
(self.x <= other.x + other.size) and
(other.y <= self.y + self.size) and
(self.y <= other.y + other.size)
)
class MainCanvas(Widget):
rec_x = NumericProperty(0)
inc = dp(3)
ball_size = dp(35)
my_player = ObjectProperty(Rectangle)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.player = Sprite(x=-self.ball_size/2, y=145, size=dp(15), vx=dp(0), vy=dp(0), color=(1, .3, .5))
self.balls = [
Sprite(x=0, y=-2000, size=dp(15), vx=dp(0), vy=dp(8), color=(1, 0, 0)),
Sprite(x=100, y=-1000, size=dp(15), vx=dp(0), vy=dp(5), color=(1, 1, 0)),
Sprite(x=-200, y=-1000, size=dp(30), vx=dp(0), vy=dp(5), color=(1, 1, 1)),
Sprite(x=300, y=-600, size=dp(15), vx=dp(0), vy=dp(5), color=(1, 1, 1)),
]
with self.canvas:
for ball in self.balls:
ball.create_rect()
self.player.create_rect()
Clock.schedule_interval(self.update, 1/60)
def on_size(self, *args):
print(f'on_size : {self.width}x{self.height}')
for ball in self.balls:
ball.set_start_pos(self.center_x, self.center_y)
self.player.set_start_pos(self.center_x, self.center_y)
self.rec_x = self.player.x
def update(self, dt):
# all in one function to control if it check collision after move, and draw only after all calculations
# --- moves (without draws) ---
self.player_move(dt)
# move green rectangle below player
self.rec_x = self.player.x
self.ball_move(dt)
# --- collisions (without draws) ---
live_balls = []
for ball in self.balls:
if self.player.check_collision_rect(ball):
#if self.player.check_collision_circle(ball):
print('killed')
# hide
#ball.set_start_pos(self.center_x, self.center_y)
#ball.draw()
# or remove from canvas
self.canvas.remove(ball.rect)
else:
live_balls.append(ball)
self.balls = live_balls
# --- draws ---
self.player.draw()
for ball in self.balls:
ball.draw()
def on_left_click(self):
print('Left Clicked')
self.player.vx -= self.inc
def on_right_click(self):
print('Right Clicked')
self.player.vx += self.inc
def ball_move(self, dt):
for ball in self.balls:
ball.move()
if ball.y + ball.size > self.height:
ball.set_start_pos(self.center_x, self.center_y)
def player_move(self, dt):
self.player.move()
# moving left and stop on screen border
if self.player.vx < 0 and self.player.x < 0:
self.player.x = 0
self.player.vx = 0
# moving right and jump to left side when leave screen
if self.player.vx > 0 and self.width < self.player.x:
self.player.x = 0
class TheFalling(App):
pass
app = TheFalling()
app.run()
#app.stop()
app.root_window.close()

How to limit the amount of times a button is pressed

I am trying to make a game where you can shoot bullets to kill emojis. However, i can't manage to figure out how to stop spamming the space key to shoot bullets. If you keep on spamming, the game would be too easy. I am not exactly sure if what command I should use. Please help! thanks!
Here is my code:
# import everything from turtle
from turtle import *
import random
import math
#create a link to the object (creates the environment)
screen = Screen()
speed1 = 1.3
ht()
amountOfEmojis = 11
#set a boundary for screen, if touches end, goes to the other side
screenMinX = -screen.window_width()/2
screenMinY = -screen.window_height()/2
screenMaxX = screen.window_width()/2
screenMaxY = screen.window_height()/2
#establish important data for screen environment
screen.setworldcoordinates(screenMinX,screenMinY,screenMaxX,screenMaxY)
screen.bgcolor("black")
#turtle setup
penup()
ht()
speed(0)
goto(0, screenMaxY - 50)
color('white')
write("Welcome to Emoji Run!", align="center", font=("Courier New",26))
goto(0, screenMaxY - 70)
write("Use the arrow keys to move and space to fire. The point of the game is to kill the emojis", align="center")
goto(0, 0)
color("red")
emojis = ["Poop_Emoji_7b204f05-eec6-4496-91b1-351acc03d2c7_grande.png", "1200px-Noto_Emoji_KitKat_263a.svg.png",
"annoyningface.png", "Emoji_Icon_-_Sunglasses_cool_emoji_large.png"]
class Bullet(Turtle):
#constructor, object for a class, pass in information
def __init__(self,screen,x,y,heading):
#create a bullet
Turtle.__init__(self)#clones bullet
self.speed(0)
self.penup()
self.goto(x,y)
self.seth(heading)#pointing to itself
self.screen = screen
self.color('yellow')
self.max_distance = 500
self.distance = 0
self.delta = 20
self.shape("bullet")
#logic to move bullet
def move(self):
self.distance = self.distance + self.delta#how fast it's going to move
self.forward(self.delta)
if self.done():
self.reset()
def getRadius(self):
return 4#collision detection helper function
def blowUp(self):
self.goto(-300,0)#function that makes something go off the screen
def done(self):
return self.distance >= self.max_distance # append to list
class Asteroid(Turtle):
def __init__(self,screen,dx,dy,x,y,size,emoji):#spawn asteroid randomly
Turtle.__init__(self)#clone itself
self.speed(0)
self.penup()
self.goto(x,y)
self.color('lightgrey')
self.size = size
self.screen = screen
self.dx = dx
self.dy = dy
r = random.randint(0, len(emoji) - 1)
screen.addshape(emojis[r])
self.shape(emojis[r])
#self.shape("rock" + str(size)) #sets size and shape for asteroid
def getSize(self):#part of collision detection
return self.size
#getter and setter functions
def getDX(self):
return self.dx
def getDY(self):
return self.dy
def setDX(self,dx):
self.dx = dx
def setDY(self,dy):
self.dy = dy
def move(self):
x = self.xcor()
y = self.ycor()
#if on edge of screen. go to opposite side
x = (self.dx + x - screenMinX) % (screenMaxX - screenMinX) + screenMinX
y = (self.dy + y - screenMinY) % (screenMaxY - screenMinY) + screenMinY
self.goto(x,y)
def blowUp(self):
self.goto(-300,0)#function that makes something go off the screen
def getRadius(self):
return self.size * 10 - 5
class SpaceShip(Turtle):
def __init__(self,screen,dx,dy,x,y):
Turtle.__init__(self)
self.speed(0)
self.penup()
self.color("white")
self.goto(x,y)
self.dx = dx
self.dy = dy
self.screen = screen
self.bullets = []
self.shape("turtle")
def move(self):
x = self.xcor()
y = self.ycor()
x = (self.dx + x - screenMinX) % (screenMaxX - screenMinX) + screenMinX
y = (self.dy + y - screenMinY) % (screenMaxY - screenMinY) + screenMinY
self.goto(x,y)
#logic for collision
def powPow(self, asteroids):
dasBullets = []
for bullet in self.bullets:
bullet.move()
hit = False
for asteroid in asteroids:
if intersect(asteroid, bullet):#counts every asteroid to see if it hits
asteroids.remove(asteroid)
asteroid.blowUp()
bullet.blowUp()
hit = True
if (not bullet.done() and not hit):
dasBullets.append(bullet)
self.bullets = dasBullets
def fireBullet(self):
self.bullets.append(Bullet(self.screen, self.xcor(), self.ycor(), self.heading()))
def fireEngine(self):#how turtle moves
angle = self.heading()
x = math.cos(math.radians(angle))
y = math.sin(math.radians(angle))
self.dx = self.dx + x#how it rotates
self.dy = self.dy + y
self.dx = self.dx / speed1
self.dy = self.dy / speed1
#extra function
def turnTowards(self,x,y):
if x < self.xcor():
self.left(7)
if x > self.xcor():
self.right(7)
def getRadius(self):
return 10
def getDX(self):
return self.dx
def getDY(self):
return self.dy
#collision detection
def intersect(object1,object2):
dist = math.sqrt((object1.xcor() - object2.xcor())**2 + (object1.ycor() - object2.ycor())**2)
radius1 = object1.getRadius()
radius2 = object2.getRadius()
# The following if statement could be written as
# return dist <= radius1+radius2
if dist <= radius1+radius2:
return True
else:
return False
#adds object to screen
screen.register_shape("rock3",((-20, -16),(-21, 0), (-20,18),(0,27),(17,15),(25,0),(16,-15),(0,-21)))
screen.register_shape("rock2",((-15, -10),(-16, 0), (-13,12),(0,19),(12,10),(20,0),(12,-10),(0,-13)))
screen.register_shape("rock1",((-10,-5),(-12,0),(-8,8),(0,13),(8,6),(14,0),(12,0),(8,-6),(0,-7)))
screen.register_shape("ship",((-10,-10),(0,-5),(10,-10),(0,10)))
screen.register_shape("bullet",((-2,-4),(-2,4),(2,4),(2,-4)))
#ship spawn exactly the middle everytime
ship = SpaceShip(screen,0,0,(screenMaxX-screenMinX)/2+screenMinX,(screenMaxY-screenMinY)/2 + screenMinY)
#randomize where they spawn
asteroids = []
for k in range(amountOfEmojis):
dx = random.random() * 6 - 3
dy = random.random() * 6 - 3
x = random.randrange(10) * (screenMaxX - screenMinX) + screenMinX
y = random.random() * (screenMaxY - screenMinY) + screenMinY
asteroid = Asteroid(screen,dx,dy,x,y,random.randint(1,3), emojis)
asteroids.append(asteroid)
def play():
# Tell all the elements of the game to move
ship.move()
gameover = False
for asteroid in asteroids:
r = random.randint(0, 1)
if r == 1:
asteroid.right(50)
else:
asteroid.left(20)
asteroid.move()
if intersect(ship,asteroid):
write("You Got Killed :(",font=("Verdana",25),align="center")
gameover = True
ship.powPow(asteroids)
screen.update()
if not asteroids:
color('green')
write("You Killed the Emojis!!",font=("Arial",30),align="center")
ht()
if not gameover:
screen.ontimer(play, 30)
bullets = []
#controls
def turnLeft():
ship.left(7)
def turnRight():
ship.right(7)
def go():
ship.fireEngine()
def fire():
ship.fireBullet()
ht()
screen.tracer(0);
screen.onkey(turnLeft, 'left')
screen.onkey(turnRight, 'right')
screen.onkey(go, 'up')
screen.onkey(fire, 'space')
screen.listen()
play()
You can use a threaded timer to prevent the method to be called everytime you click the button, and just two attributes in your SpaceShip class.
Everytime the method fireBullet is called, a check is made on the variable can_shoot. If it's true, the bullet is spawned like you did and then a timer runs (with a thread, for not blocking the main flow) that just put can_shoot to False, sleep for any amount of ms you want, and then put can_shoot to True and the method is callable again.
import time
import threading
def __init__(self):
# your stuff
self.wait_between_fire = 300 / 1000 # amount of ms / 1000 to convert in seconds
self.can_shoot = True
class TimerThread(threading.Thread):
def __init__(self, ref):
threading.Thread.__init__(self)
self.ref = ref
def run():
self.ref.can_shoot = False
time.sleep(ref.wait_between_fire)
self.ref.can_shoot = True
def set_timer(self):
TimerThread(self).start()
def fireBullet(self):
if self.can_shoot:
self.bullets.append(Bullet(self.screen, self.xcor(), self.ycor(), self.heading()))
self.set_timer()
We don't need to introduce time nor threading to solve this. We can use turtle's own timer events to control the rate of fire:
def fire():
screen.onkey(None, 'space')
ship.fireBullet()
screen.ontimer(lambda: screen.onkey(fire, 'space'), 250)
Here I've limited the rate of fire to 4 rounds per second. (250 / 1000 milliseconds.) Adjust as you see fit. Below is a rework of your program with this modification as well as other fixes and style tweaks:
from turtle import Screen, Turtle
from random import random, randint, randrange, choice
from math import radians, sin as sine, cos as cosine
class Bullet(Turtle):
MAX_DISTANCE = 500
DELTA = 20
RADIUS = 4
def __init__(self, position, heading):
super().__init__(shape="bullet")
self.hideturtle()
self.penup()
self.goto(position)
self.setheading(heading)
self.color('yellow')
self.showturtle()
self.distance = 0
def move(self):
self.distance += self.DELTA
self.forward(self.DELTA)
if self.done():
self.reset()
def getRadius(self):
''' collision detection helper method '''
return self.RADIUS
def blowUp(self):
''' method that makes something go off the screen '''
self.hideturtle()
def done(self):
return self.distance >= self.MAX_DISTANCE
class Asteroid(Turtle):
def __init__(self, dx, dy, position, size, emoji):
super().__init__()
self.hideturtle()
self.penup()
self.goto(position)
self.color('lightgrey')
emoji = choice(emojis)
# screen.addshape(emoji) # for StackOverflow debugging
self.shape(emoji)
self.showturtle()
self.size = size
self.dx = dx
self.dy = dy
def move(self):
x, y = self.position()
# if on edge of screen. go to opposite side
x = (self.dx + x - screenMinX) % (screenMaxX - screenMinX) + screenMinX
y = (self.dy + y - screenMinY) % (screenMaxY - screenMinY) + screenMinY
self.goto(x, y)
def blowUp(self):
''' method that makes something go off the screen '''
self.hideturtle()
def getRadius(self):
return self.size * 10 - 5
class SpaceShip(Turtle):
RADIUS = 10
def __init__(self, screen, dx, dy, x, y):
super().__init__(shape='turtle')
self.hideturtle()
self.penup()
self.color("white")
self.goto(x, y)
self.showturtle()
self.dx = dx
self.dy = dy
self.screen = screen
self.bullets = []
def move(self):
x, y = self.position()
x = (self.dx + x - screenMinX) % (screenMaxX - screenMinX) + screenMinX
y = (self.dy + y - screenMinY) % (screenMaxY - screenMinY) + screenMinY
self.goto(x, y)
def powPow(self, asteroids):
''' logic for collision '''
dasBullets = []
for bullet in self.bullets:
bullet.move()
hit = False
for asteroid in asteroids:
if intersect(asteroid, bullet): # counts every asteroid to see if it hits
asteroids.remove(asteroid)
asteroid.blowUp()
hit = True
if not bullet.done() and not hit:
dasBullets.append(bullet)
else:
bullet.blowUp()
self.bullets = dasBullets
def fireBullet(self):
bullet = Bullet(self.position(), self.heading())
self.bullets.append(bullet)
def fireEngine(self):
angle = self.heading() # how turtle moves
x = cosine(radians(angle))
y = sine(radians(angle))
self.dx = self.dx + x # how it rotates
self.dy = self.dy + y
self.dx = self.dx / speed1
self.dy = self.dy / speed1
def getRadius(self):
return self.RADIUS
def turnLeft(self):
self.left(7)
def turnRight(self):
self.right(7)
def intersect(object1, object2):
''' collision detection '''
return object1.distance(object2) <= object1.getRadius() + object2.getRadius()
def play():
# Tell all the elements of the game to move
ship.move()
gameover = False
for asteroid in asteroids:
r = randint(0, 1)
if r == 1:
asteroid.right(50)
else:
asteroid.left(20)
asteroid.move()
if intersect(ship, asteroid):
turtle.write("You Got Killed :(", font=("Verdana", 25), align="center")
gameover = True
ship.powPow(asteroids)
screen.update()
if not asteroids:
turtle.color('green')
turtle.write("You Killed the Emojis!!", font=("Arial", 30), align="center")
if not gameover:
screen.ontimer(play, 30)
# controls
def fire():
screen.onkey(None, 'space')
ship.fireBullet()
screen.ontimer(lambda: screen.onkey(fire, 'space'), 250)
# create a link to the object (creates the environment)
speed1 = 1.3
amountOfEmojis = 11
# establish important data for screen environment
screen = Screen()
screen.bgcolor("black")
# set a boundary for screen, if touches end, goes to the other side
screenMinX = -screen.window_width()/2
screenMinY = -screen.window_height()/2
screenMaxX = screen.window_width()/2
screenMaxY = screen.window_height()/2
screen.setworldcoordinates(screenMinX, screenMinY, screenMaxX, screenMaxY)
# adds object to screen
screen.register_shape("rock3", ((-20, -16), (-21, 0), (-20, 18), (0, 27), (17, 15), (25, 0), (16, -15), (0, -21)))
screen.register_shape("rock2", ((-15, -10), (-16, 0), (-13, 12), (0, 19), (12, 10), (20, 0), (12, -10), (0, -13)))
screen.register_shape("rock1", ((-10, -5), (-12, 0), (-8, 8), (0, 13), (8, 6), (14, 0), (12, 0), (8, -6), (0, -7)))
screen.register_shape("ship", ((-10, -10), (0, -5), (10, -10), (0, 10)))
screen.register_shape("bullet", ((-2, -4), (-2, 4), (2, 4), (2, -4)))
screen.tracer(0)
# turtle setup
turtle = Turtle()
turtle.hideturtle()
turtle.penup()
turtle.goto(0, screenMaxY - 50)
turtle.color('white')
turtle.write("Welcome to Emoji Run!", align="center", font=("Courier New", 26))
turtle.goto(0, screenMaxY - 70)
turtle.write("Use the arrow keys to move, and space to fire. The point of the game is to kill the emojis.", align="center", font=("Courier New", 13))
turtle.goto(0, 0)
turtle.color("red")
emojis = [
"Poop_Emoji_7b204f05-eec6-4496-91b1-351acc03d2c7_grande.png",
"1200px-Noto_Emoji_KitKat_263a.svg.png",
"annoyningface.png",
"Emoji_Icon_-_Sunglasses_cool_emoji_large.png"
]
emojis = ['rock1', 'rock2', 'rock3'] # for StackOverflow debugging purposes
# ship spawn exactly the middle everytime
ship = SpaceShip(screen, 0, 0, (screenMaxX - screenMinX)/2 + screenMinX, (screenMaxY - screenMinY)/2 + screenMinY)
# randomize where they spawn
asteroids = []
for k in range(amountOfEmojis):
dx, dy = random() * 6 - 3, random() * 6 - 3
x = randrange(10) * (screenMaxX - screenMinX) + screenMinX
y = random() * (screenMaxY - screenMinY) + screenMinY
asteroid = Asteroid(dx, dy, (x, y), randint(1, 3), emojis)
asteroids.append(asteroid)
screen.onkey(ship.turnLeft, 'Left')
screen.onkey(ship.turnRight, 'Right')
screen.onkey(ship.fireEngine, 'Up')
screen.onkey(fire, 'space')
screen.listen()
screen.update()
play()
screen.mainloop()
Something to consider is that turtles are global entities that don't get garbage collected. So, you might want to collect your spent bullets in a list to reuse, only creating new ones when you need them.

Elastic collision between moving particles in python: why is kinetic energy not conserved?

I am trying to code a particle simulation in pygame but am having trouble coding the collisions between particles. All the collisions are elastic so kinetic energy should be conserved. However, I am experiencing two main problems:
Particles speed up and up until they get out of control
Particles clump together and stop moving
I would really appreciate any insight to help solve these problems.
I used this document (http://www.vobarian.com/collisions/2dcollisions2.pdf) to help calculate the new velocities of the particles after the collision. The mass of all the particles is the same so I have ignored their mass in my calculations.
Here is my code so far:
import pygame
pygame.init()
import random
import numpy
HEIGHT = 500
WIDTH = 500
NUM_BALLS = 2
#setup
win = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Simulation")
class Particle(object):
def __init__(self, x, y , radius):
self.x = x
self.y = y
self.radius = radius
self.xvel = random.randint(1,5)
self.yvel = random.randint(1,5)
def Draw_circle(self):
pygame.draw.circle(win, (255,0,0), (self.x, self.y), self.radius)
def redrawGameWindow():
win.fill((0,0,0))
for ball in balls:
ball.Draw_circle()
pygame.display.update()
balls = []
for turn in range(NUM_BALLS):
balls.append(Particle(random.randint(20,WIDTH-20),random.randint(20,HEIGHT-20),20))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for ball in balls:
if (ball.x + ball.radius) <= WIDTH or (ball.x - ball.radius) >= 0:
ball.x += ball.xvel
if (ball.x + ball.radius) > WIDTH or (ball.x - ball.radius) < 0:
ball.xvel *= -1
ball.x += ball.xvel
if (ball.y + ball.radius) <= HEIGHT or (ball.y - ball.radius) >= 0:
ball.y += ball.yvel
if (ball.y + ball.radius) > HEIGHT or (ball.y - ball.radius) < 0:
ball.yvel *= -1
ball.y += ball.yvel
#code for collision between balls
for ball in balls:
for i in range(len(balls)):
for j in range (i+1, len(balls)):
d = (balls[j].x-balls[i].x)**2 + (balls[j].y-balls[i].y)**2
if d < (balls[j].radius + balls[i].radius)**2:
print("collision")
n = (balls[i].x-balls[j].x, balls[i].y-balls[j].y) #normal vector
un = n/ numpy.sqrt((balls[i].x-balls[j].x)**2 + (balls[i].y-balls[j].y)**2) #unit normal vector
ut = numpy.array((-un[1],un[0])) #unit tangent vector
u1n = numpy.vdot(un, (balls[j].xvel, balls[j].yvel)) #initial velocity in normal direction for first ball
v1t = numpy.vdot(ut, (balls[j].xvel, balls[j].yvel)) #initial velocity in tangent direction (remains unchanged)
u2n = numpy.vdot(un, (balls[i].xvel, balls[i].yvel)) #second ball
v2t = numpy.vdot(ut, (balls[i].xvel, balls[i].yvel))
v1n = u2n
v2n = u1n
v1n *= un
v2n *= un
v1t *= ut
v2t *= ut
v1 = v1n + v1t #ball 1 final velocity
v2 = v2n + v2t #ball 2 final velocity
balls[j].xvel = int(numpy.vdot(v1, (1,0))) #splitting final velocities into x and y components again
balls[j].yvel = int(numpy.vdot(v1, (0,1)))
balls[i].xvel = int(numpy.vdot(v2, (1,0)))
balls[i].yvel = int(numpy.vdot(v2, (0,1)))
redrawGameWindow()
pygame.time.delay(20)
pygame.quit()
In v1 = v1n + v1t, v1n is a vector, but v1t is a scalar.
So, the value v1t gets added to both components of the v1n vector, which causes the error.
You want to add the tangential velocity as a vector, so you should do just like you did for the normal velocities:
v1n *= un
v2n *= un
v1t *= ut
v2t *= ut
Note that using the same variable for two very different things, the vector and its norm, makes your code more difficult to understand and can lead to errors - as it just did. You should probably rename your variables in a more consistent way, in order to make the differences clearer.
Also, ut must be a numpy array, but you made it a tuple. Consider the difference:
With a tuple
>>> t = (3, 4)
>>> 3*t
(3, 4, 3, 4, 3, 4)
With a np.array:
>>> t = np.array((3, 4))
>>> 3*t
array([ 9, 12])
So, you have to change
ut = (-un[1],un[0])
into
ut = numpy.array((-un[1],un[0]))
The problem where the things would stick together is simple, even though you always checked for collision, the time where it would actually recognise it would be when the circles would be past touching but slightly into each other. The circles now bounce and move a little. However they have not moved enough to completely to not be touching, this mean the bounce again and it goes in a loop. I made code that fixes this, but you have to change the bounce function and use your code, as mine is not that perfect, but functional.
import pygame
pygame.init()
import random
import numpy
HEIGHT = 500
WIDTH = 500
NUM_BALLS = 2
#setup
win = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("Simulation")
class Particle(object):
def __init__(self, x, y , radius):
self.x = x
self.y = y
self.radius = radius
self.xvel = random.randint(1,5)
self.yvel = random.randint(1,5)
self.colideCheck = []
def Draw_circle(self):
pygame.draw.circle(win, (255,0,0), (int(self.x), int(self.y)), self.radius)
def redrawGameWindow():
win.fill((0,0,0))
for ball in balls:
ball.Draw_circle()
pygame.display.update()
def bounce(v1,v2, mass1 = 1, mass2 = 1):
#i Tried my own bouncing mechanism, but doesn't work completly well, add yours here
multi1 = mass1/(mass1+mass2)
multi2 = mass2/(mass1+mass2)
deltaV2 = (multi1*v1[0]-multi2*v2[0],multi1*v1[1]-multi2*v2[1])
deltaV1 = (multi2*v2[0]-multi1*v1[0],multi2*v2[1]-multi1*v1[1])
print("preVelocities:",v1,v2)
return deltaV1,deltaV2
def checkCollide(circ1Cord,circ1Rad,circ2Cord,circ2Rad):
tryDist = circ1Rad+circ2Rad
actualDist = dist(circ1Cord,circ2Cord)
if dist(circ1Cord,circ2Cord) <= tryDist:
return True
return False
def dist(pt1,pt2):
dX = pt1[0]-pt2[0]
dY = pt1[1]-pt2[1]
return (dX**2 + dY**2)**0.5
balls = []
for turn in range(NUM_BALLS):
balls.append(Particle(random.randint(60,WIDTH-60),random.randint(60,HEIGHT-60),60))
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for ball in balls:
if (ball.x + ball.radius) <= WIDTH and (ball.x - ball.radius) >= 0:
ball.x += ball.xvel
else:
ball.xvel *= -1
ball.x += ball.xvel
if (ball.y + ball.radius) <= HEIGHT and (ball.y - ball.radius) >= 0:
ball.y += ball.yvel
else:
ball.yvel *= -1
ball.y += ball.yvel
for ball in balls:
for secBallCheck in balls:
if secBallCheck not in ball.colideCheck and ball!= secBallCheck and checkCollide((ball.x,ball.y),ball.radius,(secBallCheck.x,secBallCheck.y),secBallCheck.radius):
print("COLLIDE")
vel1,vel2 = bounce((ball.xvel,ball.yvel),(secBallCheck.xvel,secBallCheck.yvel))
print(vel1,vel2)
ball.xvel = vel1[0]
ball.yvel = vel1[1]
ball.colideCheck.append(secBallCheck)
secBallCheck.xvel = vel2[0]
secBallCheck.yvel = vel2[1]
secBallCheck.colideCheck.append(ball)
elif not checkCollide((ball.x,ball.y),ball.radius,(secBallCheck.x,secBallCheck.y),secBallCheck.radius):
if ball in secBallCheck.colideCheck:
secBallCheck.colideCheck.remove(ball)
ball.colideCheck.remove(secBallCheck)
redrawGameWindow()
pygame.time.delay(20)
pygame.quit()

Sprite moving faster left than right pygame

I think I'm having a rounding problem causing my sprite to move faster/jump farther while moving left.
My sprites update method is calling move, which calls move_single_axis for each axis. Inside this I'm doing some collision detection where I rely on pygame's rect class to both detect the collision, and set the new position.
I think this is the problem but I'm uncertain how to get around the rounding issue because pygame's rect uses integers under the hood.
Here's the update code:
def update(self, dt, game):
self.calc_grav(game, dt)
self.animate(dt, game)
self._old_position = self._position[:]
self.move(dt, game)
self.rect.topleft = self._position
def move(self, dt, game):
# Move each axis separately. Note that this checks for collisions both times.
dx = self.velocity[0]
dy = self.velocity[1]
if dx != 0:
self.move_single_axis(dx, 0, dt)
if dy != 0:
self.move_single_axis(0, dy, dt)
def move_single_axis(self, dx, dy, dt):
#print("hero_destination: ({}, {})".format(dx *dt, dy *dt))
self._position[0] += dx * dt
self._position[1] += dy * dt
#print("Game walls: {}".format(game.walls))
self.rect.topleft = self._position
body_sensor = self.get_body_sensor()
for wall in game.walls:
if body_sensor.colliderect(wall.rect):
if dx > 0: # Moving right; Hit the left side of the wall
#print(" -- Moving right; Hit the left side of the wall")
self.rect.right = wall.rect.left
if dx < 0: # Moving left; Hit the right side of the wall
#print(" -- Moving left; Hit the right side of the wall")
self.rect.left = wall.rect.right - self.COLLISION_BOX_OFFSET
if dy > 0: # Moving down; Hit the top side of the wall
#print(" -- Moving down; Hit the top side of the wall")
self.rect.bottom = wall.rect.top
if dy < 0: # Moving up; Hit the bottom side of the wall
#print(" -- Moving up; Hit the bottom side of the wall")
self.rect.top = wall.rect.bottom
self._position[0] = self.rect.topleft[0]
self._position[1] = self.rect.topleft[1]
Here is the whole source(https://github.com/davidahines/python_sidescroller):
import os.path
import pygame
from pygame.locals import *
from pytmx.util_pygame import load_pygame
import pyscroll
import pyscroll.data
from pyscroll.group import PyscrollGroup
# define configuration variables here
RESOURCES_DIR = 'data'
HERO_JUMP_HEIGHT = 180
HERO_MOVE_SPEED = 200 # pixels per second
GRAVITY = 1000
MAP_FILENAME = 'maps/dungeon_0.tmx'
# simple wrapper to keep the screen resizeable
def init_screen(width, height):
screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
return screen
# make loading maps a little easier
def get_map(filename):
return os.path.join(RESOURCES_DIR, filename)
# make loading images a little easier
def load_image(filename):
return pygame.image.load(os.path.join(RESOURCES_DIR, filename))
class Hero(pygame.sprite.Sprite):
""" Our Hero
The Hero has three collision rects, one for the whole sprite "rect" and
"old_rect", and another to check collisions with walls, called "feet".
The position list is used because pygame rects are inaccurate for
positioning sprites; because the values they get are 'rounded down'
as integers, the sprite would move faster moving left or up.
Feet is 1/2 as wide as the normal rect, and 8 pixels tall. This size size
allows the top of the sprite to overlap walls. The feet rect is used for
collisions, while the 'rect' rect is used for drawing.
There is also an old_rect that is used to reposition the sprite if it
collides with level walls.
"""
def __init__(self, map_data_object):
pygame.sprite.Sprite.__init__(self)
self.STATE_STANDING = 0
self.STATE_WALKING = 1
self.STATE_JUMPING = 2
self.FRAME_DELAY_STANDING =1
self.FRAME_DELAY_WALKING = 1
self.FRAME_DELAY_JUMPING = 1
self.FACING_RIGHT = 0
self.FACING_LEFT = 1
self.MILLISECONDS_TO_SECONDS = 1000.0
self.COLLISION_BOX_OFFSET = 8
self.time_in_state = 0.0
self.current_walking_frame = 0
self.current_standing_frame = 0
self.current_jumping_frame = 0
self.load_sprites()
self.velocity = [0, 0]
self.state = self.STATE_STANDING
self.facing = self.FACING_RIGHT
self._position = [map_data_object.x, map_data_object.y]
self._old_position = self.position
self.rect = pygame.Rect(8, 0, self.image.get_rect().width - 8, self.image.get_rect().height)
def set_state(self, state):
if self.state != state:
self.state = state
self.time_in_state = 0.0
def load_sprites(self):
self.spritesheet = Spritesheet('data/art/platformer_template_g.png')
standing_images = self.spritesheet.images_at((
pygame.Rect(0, 0, 32, 32),
), colorkey= (0,255,81))
self.standing_images = []
for standing_image in standing_images:
self.standing_images.append(standing_image.convert_alpha())
self.image = self.standing_images[self.current_standing_frame]
#property
def position(self):
return list(self._position)
#position.setter
def position(self, value):
self._position = list(value)
def get_floor_sensor(self):
return pygame.Rect(self.position[0]+self.COLLISION_BOX_OFFSET, self.position[1]+2, self.rect.width -self.COLLISION_BOX_OFFSET, self.rect.height)
def get_ceiling_sensor(self):
return pygame.Rect(self.position[0]+self.COLLISION_BOX_OFFSET, self.position[1]-self.rect.height, self.rect.width, 2)
def get_body_sensor(self):
return pygame.Rect(self.position[0]+self.COLLISION_BOX_OFFSET, self.position[1], self.rect.width -self.COLLISION_BOX_OFFSET, self.rect.height)
def calc_grav(self, game, dt):
""" Calculate effect of gravity. """
floor_sensor = self.get_floor_sensor()
collidelist = floor_sensor.collidelist(game.walls)
hero_is_airborne = collidelist == -1
if hero_is_airborne:
if self.velocity[1] == 0:
self.velocity[1] = GRAVITY * dt
else:
self.velocity[1] += GRAVITY * dt
def update(self, dt, game):
self.calc_grav(game, dt)
self._old_position = self._position[:]
self.move(dt, game)
def move(self, dt, game):
# Move each axis separately. Note that this checks for collisions both times.
dx = self.velocity[0]
dy = self.velocity[1]
if dx != 0:
self.move_single_axis(dx, 0, dt)
if dy != 0:
self.move_single_axis(0, dy, dt)
self.rect.topleft = self._position
def move_single_axis(self, dx, dy, dt):
#print("hero_destination: ({}, {})".format(dx *dt, dy *dt))
self._position[0] += dx * dt
self._position[1] += dy * dt
#print("Game walls: {}".format(game.walls))
self.rect.topleft = self._position
body_sensor = self.get_body_sensor()
for wall in game.walls:
if body_sensor.colliderect(wall.rect):
if dx > 0: # Moving right; Hit the left side of the wall
self.rect.right = wall.rect.left
if dx < 0: # Moving left; Hit the right side of the wall
self.rect.left = wall.rect.right - self.COLLISION_BOX_OFFSET
if dy > 0: # Moving down; Hit the top side of the wall
self.rect.bottom = wall.rect.top
if dy < 0: # Moving up; Hit the bottom side of the wall
self.rect.top = wall.rect.bottom
self._position[0] = self.rect.topleft[0]
self._position[1] = self.rect.topleft[1]
class Wall(pygame.sprite.Sprite):
"""
A sprite extension for all the walls in the game
"""
def __init__(self, map_data_object):
pygame.sprite.Sprite.__init__(self)
self._position = [map_data_object.x, map_data_object.y]
self.rect = pygame.Rect(
map_data_object.x, map_data_object.y,
map_data_object.width, map_data_object.height)
#property
def position(self):
return list(self._position)
#position.setter
def position(self, value):
self._position = list(value)
class Spritesheet(object):
def __init__(self, filename):
try:
self.sheet = pygame.image.load(filename).convert()
except pygame.error:
print ('Unable to load spritesheet image: {}').format(filename)
raise SystemExit
# Load a specific image from a specific rectangle
def image_at(self, rectangle, colorkey = None):
"Loads image from x,y,x+offset,y+offset"
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size).convert()
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
# Load a whole bunch of images and return them as a list
def images_at(self, rects, colorkey = None):
"Loads multiple images, supply a list of coordinates"
return [self.image_at(rect, colorkey) for rect in rects]
class QuestGame(object):
""" This class is a basic game.
It also reads input and moves the Hero around the map.
Finally, it uses a pyscroll group to render the map and Hero.
This class will load data, create a pyscroll group, a hero object.
"""
filename = get_map(MAP_FILENAME)
def __init__(self):
# true while running
self.running = False
self.debug = False
# load data from pytmx
self.tmx_data = load_pygame(self.filename)
# setup level geometry with simple pygame rects, loaded from pytmx
self.walls = list()
self.npcs = list()
for map_object in self.tmx_data.objects:
if map_object.type == "wall":
self.walls.append(Wall(map_object))
elif map_object.type == "guard":
print("npc load failed: reimplement npc")
#self.npcs.append(Npc(map_object))
elif map_object.type == "hero":
self.hero = Hero(map_object)
# create new data source for pyscroll
map_data = pyscroll.data.TiledMapData(self.tmx_data)
# create new renderer (camera)
self.map_layer = pyscroll.BufferedRenderer(map_data, screen.get_size(), clamp_camera=True, tall_sprites=1)
self.map_layer.zoom = 2
self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=3)
# add our hero to the group
self.group.add(self.hero)
def draw(self, surface):
# center the map/screen on our Hero
self.group.center(self.hero.rect.center)
# draw the map and all sprites
self.group.draw(surface)
if(self.debug):
floor_sensor_rect = self.hero.get_floor_sensor()
ox, oy = self.map_layer.get_center_offset()
new_rect = floor_sensor_rect.move(ox * 2, oy * 2)
pygame.draw.rect(surface, (255,0,0), new_rect)
def handle_input(self, dt):
""" Handle pygame input events
"""
poll = pygame.event.poll
event = poll()
while event:
if event.type == QUIT:
self.running = False
break
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
self.running = False
break
# this will be handled if the window is resized
elif event.type == VIDEORESIZE:
init_screen(event.w, event.h)
self.map_layer.set_size((event.w, event.h))
event = poll()
# using get_pressed is slightly less accurate than testing for events
# but is much easier to use.
pressed = pygame.key.get_pressed()
floor_sensor = self.hero.get_floor_sensor()
floor_collidelist = floor_sensor.collidelist(self.walls)
hero_is_airborne = floor_collidelist == -1
ceiling_sensor = self.hero.get_ceiling_sensor()
ceiling_collidelist = ceiling_sensor.collidelist(self.walls)
hero_touches_ceiling = ceiling_collidelist != -1
if pressed[K_l]:
print("airborne: {}".format(hero_is_airborne))
print("hero position: {}, {}".format(self.hero.position[0], self.hero.position[1]))
print("hero_touches_ceiling: {}".format(hero_touches_ceiling))
print("hero_is_airborne: {}".format(hero_is_airborne))
if hero_is_airborne == False:
#JUMP
if pressed[K_SPACE]:
self.hero.set_state(self.hero.STATE_JUMPING)
# stop the player animation
if pressed[K_LEFT] and pressed[K_RIGHT] == False:
# play the jump left animations
self.hero.velocity[0] = -HERO_MOVE_SPEED
elif pressed[K_RIGHT] and pressed[K_LEFT] == False:
self.hero.velocity[0] = HERO_MOVE_SPEED
self.hero.velocity[1]= -HERO_JUMP_HEIGHT
elif pressed[K_LEFT] and pressed[K_RIGHT] == False:
self.hero.set_state(self.hero.STATE_WALKING)
self.hero.velocity[0] = -HERO_MOVE_SPEED
elif pressed[K_RIGHT] and pressed[K_LEFT] == False:
self.hero.set_state(self.hero.STATE_WALKING)
self.hero.velocity[0] = HERO_MOVE_SPEED
else:
self.hero.state = self.hero.STATE_STANDING
self.hero.velocity[0] = 0
def update(self, dt):
""" Tasks that occur over time should be handled here
"""
self.group.update(dt, self)
def run(self):
""" Run the game loop
"""
clock = pygame.time.Clock()
self.running = True
from collections import deque
times = deque(maxlen=30)
try:
while self.running:
dt = clock.tick(60) / 1000.
times.append(clock.get_fps())
self.handle_input(dt)
self.update(dt)
self.draw(screen)
pygame.display.flip()
except KeyboardInterrupt:
self.running = False
if __name__ == "__main__":
pygame.init()
pygame.font.init()
screen = init_screen(800, 600)
pygame.display.set_caption('Test Game.')
try:
game = QuestGame()
game.run()
except:
pygame.quit()
raise
I ripped out everything except for the hero and the QuestGame class and could see the incorrect movement, so the problem was not caused by pyscroll (unless there are more issues).
The reason for the movement problems is that you set the self._position in the update method of the hero to the topleft coords of the rect.
self._position[0] = self.rect.topleft[0]
self._position[1] = self.rect.topleft[1]
pygame.Rects can only store integers and truncate floats that you assign to them, so you shouldn't use them to update the actual position of the hero. Here's a little demonstration:
>>> pos = 10
>>> rect = pygame.Rect(10, 0, 5, 5)
>>> pos -= 1.4 # Move left.
>>> rect.x = pos
>>> rect
<rect(8, 0, 5, 5)> # Truncated the actual position.
>>> pos = rect.x # Pos is now 8 so we moved 2 pixels.
>>> pos += 1.4 # Move right.
>>> rect.x = pos
>>> rect
<rect(9, 0, 5, 5)> # Truncated.
>>> pos = rect.x
>>> pos # Oops, we only moved 1 pixel to the right.
9
The self._position is the exact position and should only be set to one of the rect's coords if the hero collides with a wall or another obstacle (because the rect is used for the collision detection).
Move the two mentioned lines into the if body_sensor.colliderect(wall.rect): clause in the wall collision for loop and it should work correctly.
for wall in game.walls:
if body_sensor.colliderect(wall.rect):
if dx > 0: # Moving right; Hit the left side of the wall
self.rect.right = wall.rect.left
self._position[0] = self.rect.left
if dx < 0: # Moving left; Hit the right side of the wall
self.rect.left = wall.rect.right - self.COLLISION_BOX_OFFSET
self._position[0] = self.rect.left
if dy > 0: # Moving down; Hit the top side of the wall
self.rect.bottom = wall.rect.top
self._position[1] = self.rect.top
if dy < 0: # Moving up; Hit the bottom side of the wall
self.rect.top = wall.rect.bottom
self._position[1] = self.rect.top

Categories