I can not figure out how to generate the food for the snake to eat. I know the position of the snake at line 97 and 98, I have created a class to generate a pixel where I want to draw a peace of food at line 22 (EDIT: should probably be a function, commented #def (?) in the code). All I have to do is add 15 pixels at the x and y coordinates from the position that is randomly allocated and print it to get a block.
The problem is to check if I eat it or not. It should be something like:
if x >= x_food && x <= x_food + 15 || y >= y_food && y <= y_food + 15:
...add a point and make snake longer...
The problem is putting it all together for some reason.. Can some one give me a hint or solve how I should write this class so I can continue with other problems? Thank you!
import pygame
import random
#Global variables
#Color
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
#Start length of snake
snake_length = 3
#Set the width of the segments of the snake
segment_width = 15
segment_height = 15
# Margin within each segment
segment_margin = 3
#Set initial speed
x_change = segment_width + segment_margin
y_change = 0
#def (?)
class Food():
#Class to print food
x_food = random.randint(0, 785)
y_food = random.randint(0, 585)
class Segment(pygame.sprite.Sprite):
""" Class to represent the segment of the snake. """
# Methods
# Constructer function
def __init__(self, x, y):
#Call the parents constructor
super().__init__()
#Set height, width
self.image = pygame.Surface([segment_width, segment_height])
self.image.fill(WHITE)
#Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
#Call this function so the Pygame library can initialize itself
pygame.init()
#Create an 800x600 size screen
screen = pygame.display.set_mode([800, 600])
#Set the title of the window
pygame.display.set_caption("Snake")
allspriteslist = pygame.sprite.Group()
#Create an initial snake
snake_segments = []
for i in range(snake_length):
x = 250 - (segment_width + segment_margin) * i
y = 30
segment = Segment(x, y)
snake_segments.append(segment)
allspriteslist.add(segment)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#Set the speed based on the key pressed
#We want the speed to be enough that we move a full
#Segment, plus the margin
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = (segment_width + segment_margin) * -1
y_change = 0
if event.key == pygame.K_RIGHT:
x_change = (segment_width + segment_margin)
y_change = 0
if event.key == pygame.K_UP:
x_change = 0
y_change = (segment_height + segment_margin) * -1
if event.key == pygame.K_DOWN:
x_change = 0
y_change = (segment_width + segment_margin)
#Get rid of last segment of the snake
#.pop() command removes last item in list
old_segment = snake_segments.pop()
allspriteslist.remove(old_segment)
#Figure out where new segment will be
x = snake_segments[0].rect.x + x_change
y = snake_segments[0].rect.y + y_change
segment = Segment(x, y)
#Insert new segment to the list
snake_segments.insert(0, segment)
allspriteslist.add(segment)
#Draw
#Clear screen
screen.fill(BLACK)
allspriteslist.draw(screen)
#Flip screen
pygame.display.flip()
#Pause
clock.tick(5)
pygame.quit()
i took your code and i think i work something out, pls note that this only monitors when the snake goes over the block, then it prints: yummy, so you will have to add the detail, also note that i dont use your class to generate the food:
import pygame
import random
#Global variables
#Color
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
#Start length of snake
snake_length = 3
#Set the width of the segments of the snake
segment_width = 15
segment_height = 15
# Margin within each segment
segment_margin = 3
#Set initial speed
x_change = segment_width + segment_margin
y_change = 0
#def (?)
class Food():
#Class to print food
x_food = random.randint(0, 785)
y_food = random.randint(0, 585)
class Segment(pygame.sprite.Sprite):
""" Class to represent the segment of the snake. """
# Methods
# Constructer function
def __init__(self, x, y):
#Call the parents constructor
super().__init__()
#Set height, width
self.image = pygame.Surface([segment_width, segment_height])
self.image.fill(WHITE)
#Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
#Call this function so the Pygame library can initialize itself
pygame.init()
#Create an 800x600 size screen
screen = pygame.display.set_mode([800, 600])
#Set the title of the window
pygame.display.set_caption("Snake")
allspriteslist = pygame.sprite.Group()
#Create an initial snake
snake_segments = []
for i in range(snake_length):
x = 250 - (segment_width + segment_margin) * i
y = 30
segment = Segment(x, y)
snake_segments.append(segment)
allspriteslist.add(segment)
clock = pygame.time.Clock()
done = False
x_food = random.randint(0, 785)
y_food = random.randint(0, 585)
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
#Set the speed based on the key pressed
#We want the speed to be enough that we move a full
#Segment, plus the margin
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = (segment_width + segment_margin) * -1
y_change = 0
if event.key == pygame.K_RIGHT:
x_change = (segment_width + segment_margin)
y_change = 0
if event.key == pygame.K_UP:
x_change = 0
y_change = (segment_height + segment_margin) * -1
if event.key == pygame.K_DOWN:
x_change = 0
y_change = (segment_width + segment_margin)
if y < y_food+30:
if x > x_food and x < x_food+30 or x+20 > x_food and x+20<x_food+30:
print('yummy')
#Get rid of last segment of the snake
#.pop() command removes last item in list
old_segment = snake_segments.pop()
allspriteslist.remove(old_segment)
#Figure out where new segment will be
x = snake_segments[0].rect.x + x_change
y = snake_segments[0].rect.y + y_change
segment = Segment(x, y)
#Insert new segment to the list
snake_segments.insert(0, segment)
allspriteslist.add(segment)
#Draw
#Clear screen
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, [x_food, y_food, 30, 30])
allspriteslist.draw(screen)
#Flip screen
pygame.display.flip()
#Pause
clock.tick(5)
pygame.quit()
hope this helped, thanks!
if x >= x_food && x <= x_food + 15 || y >= y_food && y <= y_food + 15:
Why do you OR these pairs of conditions? Don't all 4 tests have to be true at the same time?
if x >= x_food && x <= x_food + 15 && y >= y_food && y <= y_food + 15:
how about using:
if snake_headx == foodx and snake_heady == foody:
food_eated()
snake_grow()
just a suggestion though
didnt read all ur code, just thought u might find it usefull.
actuely ive came to a solution, so basicly what you want is a square, and when the snake comes near that square something should happen?, well ive got a racegame that makes you crash when you hit a square car, so il just copy the code here:
if y < thing_starty+thing_height:
if x > thing_startx and x < thing_startx+thing_width or x+car_width > thing_startx and x+car_width<thing_startx+thing_width:
snake_eated()
snake_grow()
this monitors the x and y of your car (or snake) and checks when the thing (or food) 's y is smaller than your car, then it checks the x's and alot of other things, and basicly it creates a big line all around your square that you cannot cross in your case you'd just need to add the rest, would this work?
Make your food a sprite with a simple filled rectangle as the image, and then use sprite collision pygame.sprite.spritecollide() to check if your snake collides with your food. Pygame will take care of the actual logic whether two rectangles overlap for you.
Also, since you are already using sprite groups, I suggest you write an update function for your snake segments which moves them instead of creating a new segment every turn. Then you can simply call allspriteslist.update() in your main game loop, which will call the update function for every snake segment.
Finally, you might want to have a look at the numerous snake examples on the pygame website.
Related
So, I've been studying programming for a short time and decided to make the snake game in pygame. However, while making the base of the program I realized that the rectangle (snake) controlled by the player is teleporting (maybe by the lag) every second while moving. Here is the code:
import pygame
pygame.init()
# Window
window = (1280, 720)
center = (window[0]//2, window[1]//2)
screen = pygame.display.set_mode(window)
pygame.display.set_caption("Snake")
# Colors
COLOR_LIGHT_GREY = (200, 200, 200)
COLOR_DARK_GREY = pygame.Color('gray12')
# Game loop
game_loop = True
game_clock = pygame.time.Clock()
# Create image
def img(name):
img_path = "./assets/natanael.lucena_" + name + ".png"
return pygame.image.load(img_path).convert_alpha()
# Set object coordinates
def set_obj_coordinates(obj, x, y):
obj.x = x
obj.y = y
# Check player key press
def check_player_key(b):
global snake_direction
if event.key == pygame.K_w or event.key == pygame.K_s or event.key == pygame.K_a or event.key == pygame.K_d:
snake_direction[event.key] = b
# Check key events in-game
def event_conditional():
global game_loop
if event.type == pygame.QUIT:
game_loop = False
elif event.type == pygame.KEYDOWN:
check_player_key(True)
elif event.type == pygame.KEYUP:
check_player_key(False)
# Check if the snake collided and the game is over
def game_over():
if snake.y < 0 or snake.y > 720 or snake.x < 0 or snake. x > 1280:
return True
# Snake
snake_img = img("snake")
snake = snake_img.get_rect()
move_keys = [pygame.K_w, pygame.K_d, pygame.K_s, pygame.K_a]
snake_direction = {k: False for k in move_keys}
snake_score = 0
snake_vel = 10
set_obj_coordinates(snake, center[0], center[1])
# Apple
apple_img = img("apple")
apple = apple_img.get_rect()
apple_eaten = False
set_obj_coordinates(apple, 40, 40)
# Main game loop
while game_loop:
for event in pygame.event.get():
event_conditional()
# score_text = text_render(snake_score)
if not game_over():
for i in range(4):
if i % 2:
coord_aux = "x "
else:
coord_aux = "y "
if i % 3:
op = "+= "
else:
op = "-= "
if snake_direction[move_keys[i]]:
exec("snake." + coord_aux + op + "snake_vel")
# the for loop above is equivalent to :
# if snake_direction[move_keys[0]]:
# snake.y -= snake_vel
# if snake_direction[move_keys[1]]:
# snake.x += snake_vel
# if snake_direction[move_keys[2]]:
# snake.y += snake_vel
# if snake_direction[move_keys[3]]:
# snake.x -= snake_vel
screen.fill(COLOR_DARK_GREY)
screen.blit(snake_img, snake)
screen.blit(apple_img, apple)
# Update screen
pygame.display.flip()
game_clock.tick(60)
pygame.quit()
If someone can tell me the reason for the problem, I really appreciate it.
Edit: looks like the problem is just happening with me
Thats a common problem with pygame, especially since pygame 2/sdl 2 where you can't use the directx video driver and enable vsync anymore.
You should do the following:
keep track of the sub-pixel coordinates of your moving game objects. A Rect can only store integer values in its x and y attributes, so you'll need another variable to store this. I usually use a Vector2 because it's easy to use and the performance hit usually does not matter anyway.
use an accurate clock. Pygame's clock object only uses milliseconds, which is not accurate enough for really smooth movement. If you're on windows, usually the best method for timing is the GetSystemTimePreciseAsFileTime function.
use a delta timing.
You could also use different threads for the parts of your game that needs different timing methods (e.g. your game logic expects fixed 30 or 60 FPS and your drawing code wants to run as fast as possible), but that's overkill for your small game.
So here's an example I hacked together that gives you smooth movement (at least that's what I use usually since it works fine for me. Note that it's windows specific):
import pygame
import ctypes.wintypes
pygame.init()
screen = pygame.display.set_mode((1280, 720))
center = screen.get_rect().center
pygame.display.set_caption("Snake")
game_loop = True
# https://stackoverflow.com/a/28574340/142637
def utcnow_microseconds():
system_time = ctypes.wintypes.FILETIME()
ctypes.windll.kernel32.GetSystemTimePreciseAsFileTime(ctypes.byref(system_time))
large = (system_time.dwHighDateTime << 32) + system_time.dwLowDateTime
return large // 10 - 11644473600000000
# Snake
snake_img = pygame.Surface((40, 40))
snake_img.fill('white')
snake = snake_img.get_rect()
snake_vel = 10
snake_pos = pygame.Vector2(center[0], center[1])
snake.topleft = snake_pos.x, snake_pos.y
# Apple
apple_img = pygame.Surface((40, 40))
apple_img.fill('red')
apple = apple_img.get_rect(topleft=(40, 40))
dt = 0
while game_loop:
t1 = utcnow_microseconds()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_loop = False
keys = pygame.key.get_pressed()
snake_pos.x += (keys[pygame.K_d] - keys[pygame.K_a]) * snake_vel * dt
snake_pos.y += (keys[pygame.K_s] - keys[pygame.K_w]) * snake_vel * dt
snake.topleft = snake_pos.x, snake_pos.y
screen.fill('darkgrey')
screen.blit(snake_img, snake)
screen.blit(apple_img, apple)
pygame.display.flip()
t2 = utcnow_microseconds()
dt = (t2 - t1) / 1000. / 1000. * 30
pygame.quit()
Further reading.
Very likely the bottleneck is the line
exec("snake." + coord_aux + op + "snake_vel")
exec has to parse and interpret the text in the argument.
This code can be easily improved
if not game_over():
for i in range(4):
if snake_direction[move_keys[i]]:
sign = 1 if i % 3 else -1
if i % 2:
snake.x += sign * snake_vel
else:
snake.y += sign * snake_vel
Since snake is a pygame.Rect object, you can even do the following:
if not game_over():
for i in range(4):
if snake_direction[move_keys[i]]:
sign = 1 if i % 3 else -1
snake[(i+1) % 2] += sign * snake_vel
However:
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
pygame.key.get_pressed() returns a list with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.
Use pygame.key.get_pressed() for a smooth continuous movement:
# Main game loop
while game_loop:
for event in pygame.event.get():
event_conditional()
# score_text = text_render(snake_score)
if not game_over():
keys = pygame.key.get_pressed()
snake.x += (keys[pygame.K_d] - keys[pygame.K_a]) * snake_vel
snake.y += (keys[pygame.K_s] - keys[pygame.K_w]) * snake_vel
# [...]
I'm not sure what the name of the shape that is being created, but I think is a combination of circle and square or maybe is similar to a cylinder. You can run the code to see what shape it makes. And could you suggest a site where I can learn to code a game (algorithms behind the basic games)? I hope you understand what I mean because I'm not good at English.
import pygame
import sys
import math
pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode((width,height))
img = pygame.Surface((50,50))
img.set_colorkey((255,0,0))
angle = 0
clock = pygame.time.Clock()
c_list = []
x = 100
y = 100
vel = 5
def draw_line(surface, color, pos1, pos2):
pygame.draw.line(surface, color, pos1, pos2)
while True:
screen.fill((122,122,122))
keys = pygame.key.get_pressed()
angle -= 3
if angle % 360 < 90:
x -= math.sin(angle/180*math.pi)**2*vel
y -= math.cos(angle/180*math.pi)**2*vel
elif angle % 360 < 180:
x -= math.sin(angle/180*math.pi)**2*vel
y += math.cos(angle/180*math.pi)**2*vel
elif angle % 360 < 270:
x += math.sin(angle/180*math.pi)**2*vel
y += math.cos(angle/180*math.pi)**2*vel
else:
x += math.sin(angle/180*math.pi)**2*vel
y -= math.cos(angle/180*math.pi)**2*vel
if (x,y) not in c_list:
c_list.append((x,y))
for i in range(len(c_list)-1):
draw_line(screen,(0,0,0),c_list[i],c_list[i+1])
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(-1)
img_copy = pygame.transform.rotate(img, angle)
screen.blit(img_copy,(x-int(img_copy.get_width()/2),y-int(img_copy.get_width()/2)))
pygame.display.flip()
You have to find the tangent of the circle. If you have an angle then the vector to the point on the circle is:
vx, vy = cos(angle), sin(angle)
The tangent to the circle is the vector rotated by 90°:
tx, ty = -vy, vy
Add the tangent multiplied by the velocity to the point (x, y) in every frame:
x -= math.sin(angle*math.pi/180)*vel
y += math.cos(angle*math.pi/180)*vel
angle += 3
See also Move and rotate.
Minimal example:
import pygame
import sys
import math
pygame.init()
width = 640
height = 480
screen = pygame.display.set_mode((width,height))
clock = pygame.time.Clock()
img = pygame.Surface((50,50))
img.set_colorkey((255,0,0))
angle = 0
c_list = []
x, y = 300, 200
vel = 5
def draw_line(surface, color, pos1, pos2):
pygame.draw.line(surface, color, pos1, pos2)
start = False
while True:
screen.fill((122,122,122))
keys = pygame.key.get_pressed()
x -= math.sin(angle*math.pi/180)*vel
y += math.cos(angle*math.pi/180)*vel
angle += 3
if (x,y) not in c_list:
c_list.append((x,y))
for i in range(len(c_list)-1):
draw_line(screen,(0,0,0),c_list[i],c_list[i+1])
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(-1)
img_copy = pygame.transform.rotate(img, -angle)
screen.blit(img_copy,(x-int(img_copy.get_width()/2),y-int(img_copy.get_width()/2)))
pygame.display.flip()
I'm making a Space Invaders like game and I recently got an error saying that "i" is undefined, when I stored the enemy's variables into lists in order add more enemies to the game trough a "for i in range(num_of_enemies) loop. I'm using Python 3.8 and PyCharm. I said everything right now but I have to keep writing in order to be able to post this.
import pygame
import random
import math
# Initiate pygame
pygame.init()
# Display the game window
screen = pygame.display.set_mode((800, 600))
# Enemies
enemySprite = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemySprite.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(0, 736))
enemyY.append(random.randint(50, 150))
enemyX_change.append(4)
enemyY_change.append(20)
def enemy(x, y, i):
screen.blit(enemySprite[i], (x, y))
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# Game Loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for i in range(num_of_enemies):
# Enemies movement
enemyX[i] += enemyX_change[i]
# Prevents the enemies from going off the border
if enemyX[i] <= 0 or enemyX[i] >= 736:
enemyX_change[i] *= -1
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = 'ready'
score += 1
print(score)
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
enemy(enemyX[i], enemyY[i], i)
pygame.display.update()
It's a matter of Indentation. You have to the enemy logic in the for loop, which iterates the enemies, rather than the main application loop.
Furthermore bulletX, bulletY are not defined. You have to define this variables before the main application loop.
Clear the display or draw the background image before you draw the enemies and draw the enemies in a separate loop.
Use pygame.time.Clock() to control the frames per second.
bulletX, bulletY = 0, 0
# Game Loop
clock = pygame.time.Clock()
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for i in range(num_of_enemies):
# Enemies movement
enemyX[i] += enemyX_change[i]
# Prevents the enemies from going off the border
if enemyX[i] <= 0 or enemyX[i] >= 736:
enemyX_change[i] *= -1
enemyY[i] += enemyY_change[i]
# Collision
collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
if collision:
bulletY = 480
bullet_state = 'ready'
score += 1
print(score)
enemyX[i] = random.randint(0, 736)
enemyY[i] = random.randint(50, 150)
# draw background image
# [...]
# d raw enemies
for i in range(num_of_enemies):
enemy(enemyX[i], enemyY[i], i)
# update display
pygame.display.update()
The code below bounces a ball but for some reason the ball goes through the ground after it finishes its bounces. Anyone Know Why? The idea of the code is a ball starts at the top left corner and then falls and bounces and then goes up and back down and so on until it stops bouncing, but when it stops bouncing it starts jittering and slowly sinks through the ground. Idk why and I cant figure it out. Anyone know why? Thanks for the help
import pygame
pygame.init()
#All keyboard and mouse input will be handled by the following function
def handleEvents():
#This next line of code lets this function access the dx and dy
#variables without passing them to the function or returning them.
global dx,dy
#Check for new events
for event in pygame.event.get():
#This if makes it so that clicking the X actually closes the game
#weird that that wouldn't be default.
if event.type == pygame.QUIT:
pygame.quit(); exit()
#Has any key been pressed?
elif event.type == pygame.KEYDOWN:
#Escape key also closes the game.
if event.key == pygame.K_ESCAPE:
pygame.quit(); exit()
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
dx = dx + 5
elif event.key == pygame.K_LEFT or event.key == pygame.K_a:
dx = dx - 5
elif event.key == pygame.K_UP or event.key == pygame.K_w:
dy = dy - 5
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
dy = dy + 5
width = 1000
height = 600
size = (width, height)
black = (0, 0, 0) #r g b
screen = pygame.display.set_mode(size)
clock = pygame.time.Clock()
ball = pygame.image.load("ball.gif")
ballrect = ball.get_rect()
x = 0
y = 0
dx = 3
dy = 3
done = False
while not done:
handleEvents()
#Move the ball
x = x + dx
y = y + dy
ballrect.topleft = (x,y)
#PART A
if ballrect.left < 0 or ballrect.right > width:
dx = -dx
if ballrect.top < 0 or ballrect.bottom > height:
dy = -dy
'''If the ball is outside of the range delta y,
then delta y becomes the negative version of it, and the same goes
for delta x if it is outside the boundries of delta x
'''
#PART B
dy = dy * 0.99
dx = dx * 0.99
'''Could be useful if you want
the ball to stop moving after a certain amount of time,
or the opposite, it could make the ball slowly move a greater distance each frame'''
#PART C
dy = dy + 0.3
'''dy slowly gets .3 added to itself each frame, making the bounce
smaller each time until eventually it stops fully'''
#Draw everything
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
#Delay to get 30 fps
clock.tick(30)
pygame.quit()
Since the falling speed of the ball is greater than 1 pixel, you have to make sure that the ball does not fall below the lower edge of the window.
You need to constrain the bottom of the ball to the bottom of the window:
done = False
while not done:
# [...]
x = x + dx
y = y + dy
ballrect.topleft = (x,y)
#PART A
if ballrect.left < 0 or ballrect.right > width:
dx = -dx
if ballrect.top < 0:
dy = -dy
if ballrect.bottom > height:
ballrect.bottom = height # <---
y = ballrect.top # <---
dy = -dy
# [...]
I don't know how to turn this code into a class statement and then run it!
I want to have the same result as this but using class statements.
import pygame
import random
pygame.init()
winh = 500
winl = 500
win = pygame.display.set_mode((winh, winl))
width = 20
vel = 5
y = 250
x = 250
score = 0
direction = "up"
class Dot():
def __init__(self):
self.x = x
self.y = y
self.width = width
self.direction = 'right'
def direction(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.direction = "up"
if keys[pygame.K_a]:
self.direction = "left"
if keys[pygame.K_s]:
self.direction = "down"
if keys[pygame.K_d]:
self.direction = "right"
p = True
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
direction = "up"
if keys[pygame.K_a]:
direction = "left"
if keys[pygame.K_s]:
direction = "down"
if keys[pygame.K_d]:
direction = "right"
if direction == "up":
y -= width
if direction == "down":
y += width
if direction == "left":
x -= width
if direction == "right":
x += width
if y > winh - 20:
y = 20
if y < 20:
y = winh - 20
if x > winl - 20:
x = 20
if x < 0:
x = winl - 20
win.fill((0,0,0))
dot = pygame.draw.rect(win, (0, 255, 0), (x, y, width, width))
pygame.display.update()
pygame.quit()
So you're class was getting there already. A class is an encapsulation of data and functions that are common to that "object". Anything for or about that object should go into this class. But when code for keyboard handling was put into a Dot class, this was going in the wrong direction. A Dot is a thing draw to a screen, it has a size and colour, and position. It should not be responsible for handling user-input. That's outside the scope of what a Dot is.
When updating the class, I chose to base it on the PyGame sprite class. This is a little bit more work at first, and it needs to be written in a particular way - have an image, and a rect, and (hopefully) an update() function. But being a sprite it gets lots of functionality that's already written, including the PyGame collision routines.
Near the main loop, there's a couple of additions. The first is creating the sprite dotty, and a sprite-group sprites to hold it. It's a bit weird to create a sprite group for a single sprite, but I assumed in the future there would be more than one.
Then in the actual loop, the code calls sprites.update(). This is a handy routine that calls the update() function for every sprite in the group. Then later on, there's a call to sprites.draw( win ) which paints every sprite in the group to the screen. This uses the sprite's image and the rect to know where, and what to paint.
import pygame
import random
pygame.init()
WIN_H = 500
WIN_L = 500
win = pygame.display.set_mode((WIN_H, WIN_L))
width = 20
vel = 5
y = 250
x = 250
score = 0
direction = "up"
class Dot( pygame.sprite.Sprite ):
def __init__( self, x,y, size=20, direction='right', colour=(0,255,0) ):
pygame.sprite.Sprite.__init__( self )
self.size = size
self.colour = colour
self.direction = direction
self.image = pygame.Surface( ( size, size ), pygame.SRCALPHA )
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.image.fill( colour )
def move( self, x_dir, y_dir ):
global WIN_H, WIN_L
# Adjust our co-oridinates
self.rect.x += x_dir
self.rect.y += y_dir
# Stay on the screen, and wrap around
if (self.rect.left >= WIN_L ):
self.rect.right = 0
elif (self.rect.right <= 0 ):
self.rect.left = WIN_L
if (self.rect.top >= WIN_H ):
self.rect.bottom = 0
elif (self.rect.bottom <= 0):
self.rect.top = WIN_H
def update( self ):
# TODO - handle animation, collisions, whatever
pass
# make some sprites
dotty = Dot( x,y )
sprites = pygame.sprite.Group() # a group, for a single sprite (or more)
sprites.add( dotty )
p = True
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
direction = "up"
if keys[pygame.K_a]:
direction = "left"
if keys[pygame.K_s]:
direction = "down"
if keys[pygame.K_d]:
direction = "right"
if direction == "up":
dotty.move( 0, -width )
if direction == "down":
dotty.move( 0, width )
if direction == "left":
dotty.move( -width, 0 )
if direction == "right":
dotty.move( width, 0 )
# update all the sprites
sprites.update()
# repaint the screen
win.fill((0,0,0))
sprites.draw( win )
#dot = pygame.draw.rect(win, (0, 255, 0), (x, y, width, width))
pygame.display.update()
pygame.quit()
The movement code was moved into the Dot class. This allows the Dot to adjust its position, but also take care of screen-wrapping issues. If this sprite was say, some kind of projectile, maybe when it crossed the screen boundary it would call the sprite.kill() function to remove itself from the sprite group. But since a Dot is clearly not a projectile, it can warp to the other side.