Made tons of progress, can now detect collisions and print index of card clicked on.

This commit is contained in:
maxneedspats 2022-07-31 23:14:09 -05:00
parent c61d3878fe
commit dce97c2a39
5 changed files with 107 additions and 108 deletions

56
card.py
View file

@ -1,26 +1,48 @@
import pygame import turtle
from image_sprite import ImageSprite from tkinter import PhotoImage
class Card(ImageSprite): class Card(turtle.Turtle):
def __init__(self, image_path, screen_width, screen_height): def __init__(self, image_path):
""" """
Initializes Card object. Initializes Card object.
:param image_path: Path to image :param image_path: Path to image
:param screen_width: Width of screen
:param screen_height: Height of screen
""" """
super().__init__(image_path, screen_width, screen_height) super().__init__()
self.size = 150 # image height and width (in pixels) # self.size = 150 # desired image height and width (in pixels)
self.card_back = pygame.transform.scale(pygame.image.load('images/turtle.jpg'), (self.size, self.size)) self.penup()
self.card_front = pygame.transform.scale(pygame.image.load(image_path), (self.size, self.size)) self.speed(8)
self.image = self.card_back self.smaller_back = PhotoImage(file='images/turtle.png').subsample(4, 4)
turtle.addshape('card_back', turtle.Shape('image', self.smaller_back))
self.smaller_front = PhotoImage(file=image_path).subsample(4, 4)
turtle.addshape('card_front', turtle.Shape('image', self.smaller_front))
self.shape('card_back')
self.temp_count = 0 def to_front(self):
self.shape('card_front')
def flip_card(self): def to_back(self):
if self.image == self.card_back: self.shape('card_back')
self.image = self.card_front
else: def is_mouse_over(self, x, y):
self.image = self.card_back # Collision code reused from D. Atkinson's Turtle Crossing program, with some minor modifications.
top_edge = self.ycor() + 103
bottom_edge = self.ycor() - 103
car_left_edge = self.xcor() - 103
car_right_edge = self.xcor() + 103
if (
(
(y - bottom_edge > 0 and top_edge - y > 0)
or
(top_edge - y > 0 and y - bottom_edge > 0)
)
and
(
(x - car_left_edge > 0 and car_right_edge - x > 0)
or
(x - car_left_edge > 0 and car_right_edge - x > 0)
)
):
return True
return False

View file

@ -1,38 +0,0 @@
import pygame
class ImageSprite(pygame.sprite.Sprite):
def __init__(self, image_path, screen_width, screen_height):
"""
Initializes Card object.
:param image_path: Path of
:param screen_width:
:param screen_height:
"""
super().__init__()
self.image = pygame.image.load(image_path)
self.rect = self.image.get_rect()
self.rect.move(screen_width / 2, screen_height / 2)
self.width = screen_width
self.height = screen_height
def is_clicked(self):
"""
Tests if the sprite is clicked
:return: Returns True if clicked, False otherwise
"""
mouse_pos = pygame.mouse.get_pos()
if self.rect.collidepoint(mouse_pos) and pygame.mouse.get_pressed()[0]:
return True
else:
return False
def move(self, x, y):
"""
Moves to the given x and y coordinates
:param x: x coordinate
:param y: y coordinate
:return: None
"""
self.rect.move(x / self.width, y / self.height)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 189 KiB

BIN
images/turtle.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

121
main.py
View file

@ -1,65 +1,80 @@
import os try:
import random import os
import pygame import random
import time
import turtle
from card import Card from card import Card
# CONSTANTS # CONSTANTS
WIDTH = 1600 WIDTH = 1600
HEIGHT = 900 HEIGHT = 840
BACKGROUND_COLOR = (66, 135, 245) BACKGROUND_COLOR = (66, 135, 245)
screen = pygame.display.set_mode((WIDTH, HEIGHT)) screen = turtle.Screen()
pygame.display.set_caption('Turtle Cards') turtle.bgcolor('#46a38d')
screen.setup(WIDTH, HEIGHT)
# Creates list of images, doubles it, and shuffles it
image_files = os.listdir('images')
image_files.remove('turtle.jpg')
image_files.extend(image_files)
random.shuffle(image_files)
# Create sprites def coord_translation(x, y):
cards = [Card(f'images/{file}', WIDTH, HEIGHT) for file in image_files] """
for card in cards: Translates coordinates from the screen to turtle.
screen.blit(card.image, card.rect) :param x: x coordinate
pygame.display.flip() :param y: y coordinate
:return: Translated coordinates
"""
return x - (WIDTH / 2), y - (HEIGHT / 2)
# Move sprites
# TODO: Fix initial movement of sprites
for i in range(16):
# Note: Coordinates start from (0, 0) at top left of screen.
# Arrange cards in a grid, 4x4, with a margin of 20 pixels between each card.
# Array from left to right, then top to bottom.
cards[i].move((150 * (i % 4)) + 85, (150 * int(i / 4)) + 85)
print(str((150 * (i % 4)) + 85), str((150 * int(i / 4)) + 85))
print(cards[i].rect)
game_is_running = True # Creates list of images, doubles it, and shuffles it
clicked_cards = [] image_files = os.listdir('images')
image_files.remove('turtle.png')
image_files.extend(image_files)
random.shuffle(image_files)
while game_is_running: cards = [Card(f'images/{file}') for file in image_files]
# Draw things
screen.fill(BACKGROUND_COLOR)
for card in cards:
screen.blit(card.image, card.rect)
if clicked_cards[0].image == clicked_cards[1].image: # Move sprites
# Code for if cards match for i in range(16):
print('Cards match!') # Note: Coordinates start from (0, 0) at top left of screen.
clicked_cards = [] # Arrange cards in a grid, 4x4, with a margin of 20 pixels between each card.
else: # Array from left to right, then top to bottom.
# Code for if cards don't match x, y = coord_translation((210 * (i % 4)) + 105, (210 * int(i / 4)) + 105)
print('Cards don\'t match!') cards[i].goto(x, y)
clicked_cards[0].flip_card()
clicked_cards[1].flip_card()
clicked_cards = []
for event in pygame.event.get():
if event.type == pygame.QUIT: def clicked_card(x, y):
game_is_running = False """
:return: The card which was clicked
"""
for card in cards: for card in cards:
if card.is_clicked(): if card.is_mouse_over(x, y):
print(cards.index(card))
card.to_front()
clicked_cards.append(card) clicked_cards.append(card)
card.flip_card()
cards[0].move(1, 0)
pygame.display.flip() screen.onclick(fun=clicked_card)
game_is_running = True
clicked_cards = []
score = 0
while game_is_running:
time.sleep(0.1)
if len(clicked_cards) == 2:
if clicked_cards[0].shape() != clicked_cards[1].shape():
time.sleep(2)
clicked_cards[0].to_back()
clicked_cards[1].to_back()
print('Wrong!')
score -= 1
else:
print('Correct!')
score += 5
clicked_cards = []
screen.update()
screen.mainloop()
except turtle.Terminator:
exit(0)